language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def add_targets_stripped(time_agg, df): "target = achieved if improvement > 1% without intermediate loss of more than 0.2%" def close_delta_ratio(tix1, tix2, cix): assert tix1 <= tix2 last_close = df.iat[tix1, cix] this_close = df.iat[tix2, cix] delta = (this_close - last_close) / last_close return delta # print(f"{datetime.now()}: add_targets {time_agg}") df["target"] = TARGETS[HOLD] lix = df.columns.get_loc("target") cix = df.columns.get_loc("close") win = dict() loss = dict() lossix = dict() winix = dict() for slot in range(0, time_agg): win[slot] = loss[slot] = 0. winix[slot] = lossix[slot] = slot for tix in range(time_agg, len(df), 1): # tix = time index slot = (tix % time_agg) delta = close_delta_ratio(tix - time_agg, tix, cix) if delta < 0: if loss[slot] < 0: # loss monitoring is running loss[slot] = close_delta_ratio(lossix[slot], tix, cix) else: # first time bar of decrease period lossix[slot] = tix loss[slot] = delta if win[slot] > 0: # win monitoring is running win[slot] = close_delta_ratio(winix[slot], tix, cix) if win[slot] < 0: # reset win monitor because it is below start price win[slot] = 0. while loss[slot] < SELL_THRESHOLD: # while loop for multiple small decreases and then a big decrease step # -> multiple SELL signals required win[slot] = 0. # reset win monitor -> dip exceeded threshold df.iat[lossix[slot], lix] = TARGETS[SELL] if (lossix[slot] + time_agg) > tix: break lossix[slot] += time_agg loss[slot] = close_delta_ratio(lossix[slot], tix, cix) elif delta > 0: if win[slot] > 0: # win monitoring is running win[slot] = close_delta_ratio(winix[slot], tix, cix) else: # first time bar of increase period winix[slot] = tix win[slot] = delta if loss[slot] < 0: # loss monitoring is running loss[slot] = close_delta_ratio(lossix[slot], tix, cix) if loss[slot] > 0: loss[slot] = 0. # reset loss monitor -> recovered before sell threshold while win[slot] > BUY_THRESHOLD: loss[slot] = 0. # reset win monitor -> dip exceeded threshold df.iat[winix[slot], lix] = TARGETS[BUY] if (winix[slot] + time_agg) > tix: break winix[slot] += time_agg win[slot] = close_delta_ratio(winix[slot], tix, cix) # report_setsize("complete set", df)
def add_targets_stripped(time_agg, df): "target = achieved if improvement > 1% without intermediate loss of more than 0.2%" def close_delta_ratio(tix1, tix2, cix): assert tix1 <= tix2 last_close = df.iat[tix1, cix] this_close = df.iat[tix2, cix] delta = (this_close - last_close) / last_close return delta # print(f"{datetime.now()}: add_targets {time_agg}") df["target"] = TARGETS[HOLD] lix = df.columns.get_loc("target") cix = df.columns.get_loc("close") win = dict() loss = dict() lossix = dict() winix = dict() for slot in range(0, time_agg): win[slot] = loss[slot] = 0. winix[slot] = lossix[slot] = slot for tix in range(time_agg, len(df), 1): # tix = time index slot = (tix % time_agg) delta = close_delta_ratio(tix - time_agg, tix, cix) if delta < 0: if loss[slot] < 0: # loss monitoring is running loss[slot] = close_delta_ratio(lossix[slot], tix, cix) else: # first time bar of decrease period lossix[slot] = tix loss[slot] = delta if win[slot] > 0: # win monitoring is running win[slot] = close_delta_ratio(winix[slot], tix, cix) if win[slot] < 0: # reset win monitor because it is below start price win[slot] = 0. while loss[slot] < SELL_THRESHOLD: # while loop for multiple small decreases and then a big decrease step # -> multiple SELL signals required win[slot] = 0. # reset win monitor -> dip exceeded threshold df.iat[lossix[slot], lix] = TARGETS[SELL] if (lossix[slot] + time_agg) > tix: break lossix[slot] += time_agg loss[slot] = close_delta_ratio(lossix[slot], tix, cix) elif delta > 0: if win[slot] > 0: # win monitoring is running win[slot] = close_delta_ratio(winix[slot], tix, cix) else: # first time bar of increase period winix[slot] = tix win[slot] = delta if loss[slot] < 0: # loss monitoring is running loss[slot] = close_delta_ratio(lossix[slot], tix, cix) if loss[slot] > 0: loss[slot] = 0. # reset loss monitor -> recovered before sell threshold while win[slot] > BUY_THRESHOLD: loss[slot] = 0. # reset win monitor -> dip exceeded threshold df.iat[winix[slot], lix] = TARGETS[BUY] if (winix[slot] + time_agg) > tix: break winix[slot] += time_agg win[slot] = close_delta_ratio(winix[slot], tix, cix) # report_setsize("complete set", df)
Python
def target_performance(self): """calculates the time aggregation specific performance of target_key """ # print(f"{datetime.now()}: calculate target_performance") target_df = self.minute_data perf = 0. ta_holding = False col_ix = target_df.columns.get_loc("target") assert col_ix > 0, f"did not find column {col_ix} of {self.target_key}" close_ix = target_df.columns.get_loc("close") assert target_df.index.is_unique, "unexpected not unique index" last = target_df.iat[0, close_ix] for tix in range(len(target_df)): # tix = time index this = target_df.iat[tix, close_ix] tix_perf = ((this - last) / last) # no longer in per mille * 1000) last = this signal = target_df.iat[tix, col_ix] if ta_holding: perf += tix_perf if (signal == TARGETS[BUY]) and (not ta_holding): perf -= FEE ta_holding = True if (signal == TARGETS[SELL]) and ta_holding: perf -= FEE ta_holding = False return perf
def target_performance(self): """calculates the time aggregation specific performance of target_key """ # print(f"{datetime.now()}: calculate target_performance") target_df = self.minute_data perf = 0. ta_holding = False col_ix = target_df.columns.get_loc("target") assert col_ix > 0, f"did not find column {col_ix} of {self.target_key}" close_ix = target_df.columns.get_loc("close") assert target_df.index.is_unique, "unexpected not unique index" last = target_df.iat[0, close_ix] for tix in range(len(target_df)): # tix = time index this = target_df.iat[tix, close_ix] tix_perf = ((this - last) / last) # no longer in per mille * 1000) last = this signal = target_df.iat[tix, col_ix] if ta_holding: perf += tix_perf if (signal == TARGETS[BUY]) and (not ta_holding): perf -= FEE ta_holding = True if (signal == TARGETS[SELL]) and ta_holding: perf -= FEE ta_holding = False return perf
Python
def use_settype_total(): """Uses the set_type of "total" and apllies it to all sets with such timeblock. """ cdf = self.analysis.set_index("end") cdf["set_type"] = cdf.loc[cdf.sym == "total"]["set_type"] # cdf["end"] = cdf.index # is already doen by reset_index self.analysis = cdf.reset_index()
def use_settype_total(): """Uses the set_type of "total" and apllies it to all sets with such timeblock. """ cdf = self.analysis.set_index("end") cdf["set_type"] = cdf.loc[cdf.sym == "total"]["set_type"] # cdf["end"] = cdf.index # is already doen by reset_index self.analysis = cdf.reset_index()
Python
def prepare_training(self): """Prepares training, validation and test sets with targets and admin info (see class description). These determine the samples per set_type and whether they are used in a step. It is assumed that load_sets_config was called and self.analysis contains the proper config fiel content. """ def samples_concat(target, to_be_added): if target.empty: target = to_be_added # print("target empty --> target = to_be_added", target.head(), target.tail()) return to_be_added if False: # debugging output elen = len(target) xdf = target.tail() if ("step" in xdf.columns): xdf = xdf[["target", "timestamp", "step"]] else: xdf = xdf[["target", "timestamp"]] print(f"target len: {elen}", xdf) ydf = to_be_added.head() if ("step" in ydf.columns): ydf = ydf[["target", "timestamp", "step"]] else: ydf = ydf[["target", "timestamp"]] print(f"time agg timeblock len: {len(to_be_added)}", ydf) target = pd.concat([target, to_be_added], sort=False) if False: # debugging output zdf = target.iloc[range(elen-5, elen+5)] elen = len(target) if ("step" in zdf.columns): zdf = zdf[["target", "timestamp", "step"]] else: zdf = zdf[["target", "timestamp"]] print(f"concat with new len {elen} result at interface: ", zdf) return target def extract_set_type_targets(base, tf, set_type): sym = base + "_" + QUOTE try: # print(f"extracting {set_type} for {sym}") dfcfg = self.analysis.loc[(self.analysis.set_type == set_type) & (self.analysis.sym == sym)] except KeyError: print(f"no {set_type} set for {sym}") return None dft = tf.minute_data extract = None for block in dfcfg.index: df = dft.loc[(dft.index >= dfcfg.at[block, "start"]) & (dft.index <= dfcfg.at[block, "end"]), ["target", "close"]] df["timestamp"] = df.index df["sym"] = sym df["use"] = True df["buy_prob"] = float(0) df["sell_prop"] = float(0) df["hold_prop"] = float(0) if set_type == TRAIN: df["tcount"] = int(0) df["step"] = int(0) if extract is None: extract = df else: extract = samples_concat(extract, df) return extract # here comes the core of prepare_training() for base in self.bases: tf = TargetsFeatures(base, QUOTE) try: tf.load_classifier_features() except MissingHistoryData: continue self.bases[base] = tf tfv = tf.vec tdf = extract_set_type_targets(base, tf, TRAIN) tdf = tdf[tdf.index.isin(tfv.index)] self.ctrl[TRAIN] = samples_concat(self.ctrl[TRAIN], tdf) vdf = extract_set_type_targets(base, tf, VAL) vdf = vdf[vdf.index.isin(tfv.index)] self.ctrl[VAL] = samples_concat(self.ctrl[VAL], vdf) tstdf = extract_set_type_targets(base, tf, TEST) tstdf = tstdf[tstdf.index.isin(tfv.index)] self.ctrl[TEST] = samples_concat(self.ctrl[TEST], tstdf)
def prepare_training(self): """Prepares training, validation and test sets with targets and admin info (see class description). These determine the samples per set_type and whether they are used in a step. It is assumed that load_sets_config was called and self.analysis contains the proper config fiel content. """ def samples_concat(target, to_be_added): if target.empty: target = to_be_added # print("target empty --> target = to_be_added", target.head(), target.tail()) return to_be_added if False: # debugging output elen = len(target) xdf = target.tail() if ("step" in xdf.columns): xdf = xdf[["target", "timestamp", "step"]] else: xdf = xdf[["target", "timestamp"]] print(f"target len: {elen}", xdf) ydf = to_be_added.head() if ("step" in ydf.columns): ydf = ydf[["target", "timestamp", "step"]] else: ydf = ydf[["target", "timestamp"]] print(f"time agg timeblock len: {len(to_be_added)}", ydf) target = pd.concat([target, to_be_added], sort=False) if False: # debugging output zdf = target.iloc[range(elen-5, elen+5)] elen = len(target) if ("step" in zdf.columns): zdf = zdf[["target", "timestamp", "step"]] else: zdf = zdf[["target", "timestamp"]] print(f"concat with new len {elen} result at interface: ", zdf) return target def extract_set_type_targets(base, tf, set_type): sym = base + "_" + QUOTE try: # print(f"extracting {set_type} for {sym}") dfcfg = self.analysis.loc[(self.analysis.set_type == set_type) & (self.analysis.sym == sym)] except KeyError: print(f"no {set_type} set for {sym}") return None dft = tf.minute_data extract = None for block in dfcfg.index: df = dft.loc[(dft.index >= dfcfg.at[block, "start"]) & (dft.index <= dfcfg.at[block, "end"]), ["target", "close"]] df["timestamp"] = df.index df["sym"] = sym df["use"] = True df["buy_prob"] = float(0) df["sell_prop"] = float(0) df["hold_prop"] = float(0) if set_type == TRAIN: df["tcount"] = int(0) df["step"] = int(0) if extract is None: extract = df else: extract = samples_concat(extract, df) return extract # here comes the core of prepare_training() for base in self.bases: tf = TargetsFeatures(base, QUOTE) try: tf.load_classifier_features() except MissingHistoryData: continue self.bases[base] = tf tfv = tf.vec tdf = extract_set_type_targets(base, tf, TRAIN) tdf = tdf[tdf.index.isin(tfv.index)] self.ctrl[TRAIN] = samples_concat(self.ctrl[TRAIN], tdf) vdf = extract_set_type_targets(base, tf, VAL) vdf = vdf[vdf.index.isin(tfv.index)] self.ctrl[VAL] = samples_concat(self.ctrl[VAL], vdf) tstdf = extract_set_type_targets(base, tf, TEST) tstdf = tstdf[tstdf.index.isin(tfv.index)] self.ctrl[TEST] = samples_concat(self.ctrl[TEST], tstdf)
Python
def label_steps(self): """Each sample is assigned to a step. The smallest class has MANDATORY_STEPS, i.e. each sample is labeled with a step between 0 and MANDATORY_STEPS - 1. The larger classes have more step labels according to their ratio with the smallest class. This is determined per sym, timeblock and target class. This sample distribution over steps shall balance the training of classes not bias the classifier too much in an early learning cycle. """ self.max_steps["total"] = 0 for base in self.bases: sym = base + "_" + QUOTE tdf = self.ctrl[TRAIN] tdf = tdf[tdf.sym == sym] self.max_steps[base] = {HOLD: 0, BUY: 0, SELL: 0} holds = len(tdf[(tdf.target == TARGETS[HOLD]) & (tdf.use is True)]) sells = len(tdf[(tdf.target == TARGETS[SELL]) & (tdf.use is True)]) buys = len(tdf[(tdf.target == TARGETS[BUY]) & (tdf.use is True)]) all_use = len(tdf[(tdf.use is True)]) all_sym = len(tdf) samples = holds + sells + buys # print(f"{sym} buys:{buys} sells:{sells} holds:{holds} total:{samples} on {TRAIN}") if all_use != samples: print(f"samples {samples} != all use {all_use} as subset from all {sym} {all_sym}") min_step = min([buys, sells, holds]) if min_step == 0: continue b_step = round(buys / min_step * MANDATORY_STEPS) s_step = round(sells / min_step * MANDATORY_STEPS) h_step = round(holds / min_step * MANDATORY_STEPS) bi = si = hi = 0 tix = tdf.columns.get_loc("target") iix = tdf.columns.get_loc("step") for ix in range(len(tdf.index)): target = tdf.iat[ix, tix] if target == TARGETS[BUY]: tdf.iat[ix, iix] = bi bi = (bi + 1) % b_step elif target == TARGETS[SELL]: tdf.iat[ix, iix] = si si = (si + 1) % s_step elif target == TARGETS[HOLD]: tdf.iat[ix, iix] = hi hi = (hi + 1) % h_step else: # hold print(f"error: unexpected target {target}") self.ctrl[TRAIN].loc[(self.ctrl[TRAIN].sym == sym), "step"] = tdf.step self.max_steps[base][BUY] = b_step self.max_steps[base][SELL] = s_step self.max_steps[base][HOLD] = h_step self.max_steps[base]["max"] = max([h_step, b_step, s_step]) self.max_steps["total"] += self.max_steps[base]["max"] return self.max_steps["total"]
def label_steps(self): """Each sample is assigned to a step. The smallest class has MANDATORY_STEPS, i.e. each sample is labeled with a step between 0 and MANDATORY_STEPS - 1. The larger classes have more step labels according to their ratio with the smallest class. This is determined per sym, timeblock and target class. This sample distribution over steps shall balance the training of classes not bias the classifier too much in an early learning cycle. """ self.max_steps["total"] = 0 for base in self.bases: sym = base + "_" + QUOTE tdf = self.ctrl[TRAIN] tdf = tdf[tdf.sym == sym] self.max_steps[base] = {HOLD: 0, BUY: 0, SELL: 0} holds = len(tdf[(tdf.target == TARGETS[HOLD]) & (tdf.use is True)]) sells = len(tdf[(tdf.target == TARGETS[SELL]) & (tdf.use is True)]) buys = len(tdf[(tdf.target == TARGETS[BUY]) & (tdf.use is True)]) all_use = len(tdf[(tdf.use is True)]) all_sym = len(tdf) samples = holds + sells + buys # print(f"{sym} buys:{buys} sells:{sells} holds:{holds} total:{samples} on {TRAIN}") if all_use != samples: print(f"samples {samples} != all use {all_use} as subset from all {sym} {all_sym}") min_step = min([buys, sells, holds]) if min_step == 0: continue b_step = round(buys / min_step * MANDATORY_STEPS) s_step = round(sells / min_step * MANDATORY_STEPS) h_step = round(holds / min_step * MANDATORY_STEPS) bi = si = hi = 0 tix = tdf.columns.get_loc("target") iix = tdf.columns.get_loc("step") for ix in range(len(tdf.index)): target = tdf.iat[ix, tix] if target == TARGETS[BUY]: tdf.iat[ix, iix] = bi bi = (bi + 1) % b_step elif target == TARGETS[SELL]: tdf.iat[ix, iix] = si si = (si + 1) % s_step elif target == TARGETS[HOLD]: tdf.iat[ix, iix] = hi hi = (hi + 1) % h_step else: # hold print(f"error: unexpected target {target}") self.ctrl[TRAIN].loc[(self.ctrl[TRAIN].sym == sym), "step"] = tdf.step self.max_steps[base][BUY] = b_step self.max_steps[base][SELL] = s_step self.max_steps[base][HOLD] = h_step self.max_steps[base]["max"] = max([h_step, b_step, s_step]) self.max_steps["total"] += self.max_steps[base]["max"] return self.max_steps["total"]
Python
def analyze_bases(self): """Analyses the baselist and creates a config file of sets split into equal timeblock length. Additionally an artificial "total" set is created with the sum of all bases for each timeblock. """ def first_week_ts(tf): df = tf.vec assert df is not None first_tic = df.index[0].to_pydatetime() last_tic = df.index[len(df.index)-1].to_pydatetime() if self.fixtic is None: self.fixtic = last_tic fullweeks = math.ceil((self.fixtic - first_tic) / timedelta(minutes=self.timeblock)) assert fullweeks > 0, \ f"{tf.cur_pair} {len(df)} {len(df.index)} {first_tic} {last_tic} {fullweeks}" wsts = self.fixtic - timedelta(minutes=fullweeks*self.timeblock-1) wets = wsts + timedelta(minutes=self.timeblock-1) return (wsts, wets) def next_week_ts(tf, wets): wsts = wets + timedelta(minutes=1) wets = wsts + timedelta(minutes=self.timeblock-1) df = tf.vec assert df is not None last_tic = df.index[len(df.index)-1].to_pydatetime() if last_tic < wsts: return (None, None) else: return (wsts, wets) # first and last tic of a block def analyze_timeblock(tf, wsts, wets, sym): dfm = tf.minute_data assert dfm is not None dfm = dfm.loc[(dfm.index >= wsts) & (dfm.index <= wets), ["target", "volume"]] buys = len(dfm.loc[dfm.target == TARGETS[BUY]]) sells = len(dfm.loc[dfm.target == TARGETS[SELL]]) vcount = len(dfm) avgvol = int(dfm["volume"].mean()) novol = len(dfm.loc[dfm.volume <= 0]) lastix = len(self.analysis) self.analysis.loc[lastix] = [sym, NA, wsts, wets, vcount, buys, sells, avgvol, novol] blocks = set() for base in self.bases: sym = base + "_usdt" tf = TargetsFeatures(base, QUOTE) tf.load_classifier_features() (wsts, wets) = first_week_ts(tf) while wets is not None: blocks.add(wets) analyze_timeblock(tf, wsts, wets, sym) (wsts, wets) = next_week_ts(tf, wets) blocklist = list(blocks) blocklist.sort() for wets in blocklist: df = self.analysis.loc[self.analysis.end == wets] buys = int(df["buys"].sum()) sells = int(df["sells"].sum()) avgvol = int(df["avg_vol"].mean()) novol = int(df["novol_count"].sum()) vcount = int(df["tics"].sum()) wsts = wets - timedelta(minutes=self.timeblock) lastix = len(self.analysis) sym = "total" self.analysis.loc[lastix] = [sym, NA, wsts, wets, vcount, buys, sells, avgvol, novol] cfname = sets_config_fname() self.analysis.to_csv(cfname, sep="\t", index=False)
def analyze_bases(self): """Analyses the baselist and creates a config file of sets split into equal timeblock length. Additionally an artificial "total" set is created with the sum of all bases for each timeblock. """ def first_week_ts(tf): df = tf.vec assert df is not None first_tic = df.index[0].to_pydatetime() last_tic = df.index[len(df.index)-1].to_pydatetime() if self.fixtic is None: self.fixtic = last_tic fullweeks = math.ceil((self.fixtic - first_tic) / timedelta(minutes=self.timeblock)) assert fullweeks > 0, \ f"{tf.cur_pair} {len(df)} {len(df.index)} {first_tic} {last_tic} {fullweeks}" wsts = self.fixtic - timedelta(minutes=fullweeks*self.timeblock-1) wets = wsts + timedelta(minutes=self.timeblock-1) return (wsts, wets) def next_week_ts(tf, wets): wsts = wets + timedelta(minutes=1) wets = wsts + timedelta(minutes=self.timeblock-1) df = tf.vec assert df is not None last_tic = df.index[len(df.index)-1].to_pydatetime() if last_tic < wsts: return (None, None) else: return (wsts, wets) # first and last tic of a block def analyze_timeblock(tf, wsts, wets, sym): dfm = tf.minute_data assert dfm is not None dfm = dfm.loc[(dfm.index >= wsts) & (dfm.index <= wets), ["target", "volume"]] buys = len(dfm.loc[dfm.target == TARGETS[BUY]]) sells = len(dfm.loc[dfm.target == TARGETS[SELL]]) vcount = len(dfm) avgvol = int(dfm["volume"].mean()) novol = len(dfm.loc[dfm.volume <= 0]) lastix = len(self.analysis) self.analysis.loc[lastix] = [sym, NA, wsts, wets, vcount, buys, sells, avgvol, novol] blocks = set() for base in self.bases: sym = base + "_usdt" tf = TargetsFeatures(base, QUOTE) tf.load_classifier_features() (wsts, wets) = first_week_ts(tf) while wets is not None: blocks.add(wets) analyze_timeblock(tf, wsts, wets, sym) (wsts, wets) = next_week_ts(tf, wets) blocklist = list(blocks) blocklist.sort() for wets in blocklist: df = self.analysis.loc[self.analysis.end == wets] buys = int(df["buys"].sum()) sells = int(df["sells"].sum()) avgvol = int(df["avg_vol"].mean()) novol = int(df["novol_count"].sum()) vcount = int(df["tics"].sum()) wsts = wets - timedelta(minutes=self.timeblock) lastix = len(self.analysis) sym = "total" self.analysis.loc[lastix] = [sym, NA, wsts, wets, vcount, buys, sells, avgvol, novol] cfname = sets_config_fname() self.analysis.to_csv(cfname, sep="\t", index=False)
Python
def tdelta(first: str, last: str) -> int: "returns date/time difference in minutes" my_min = pd.Timedelta(pd.Timestamp(last) - pd.to_datetime(first)) min_res = my_min.days*24*60 + int(my_min.seconds/60) return min_res
def tdelta(first: str, last: str) -> int: "returns date/time difference in minutes" my_min = pd.Timedelta(pd.Timestamp(last) - pd.to_datetime(first)) min_res = my_min.days*24*60 + int(my_min.seconds/60) return min_res
Python
def check_diff(cur_btc_usdt, cur_usdt): """ cur_usdt should be a subset of cur_btc_usdt. This function checks the average deviation. """ print("c-u first: {} last: {}".format( cur_usdt.index[0].strftime(t_f.DT_FORMAT), cur_usdt.index[len(cur_usdt)-1].strftime(t_f.DT_FORMAT))) print("c-b-u first: {} last: {}".format( cur_btc_usdt.index[0].strftime(t_f.DT_FORMAT), cur_btc_usdt.index[len(cur_btc_usdt)-1].strftime(t_f.DT_FORMAT))) diff = cur_btc_usdt[cur_btc_usdt.index.isin(cur_usdt.index)] for key in DATA_KEYS: if key != 'volume': diff[key] = (cur_btc_usdt[key] - cur_usdt[key]) / cur_usdt[key] else: diff[key] = cur_btc_usdt[key] - cur_usdt[key] diff_average = diff[key].sum() / len(cur_usdt) if key != 'volume': print(f"check_diff {key}: {diff_average:%}") else: print(f"check_diff {key}: {diff_average}")
def check_diff(cur_btc_usdt, cur_usdt): """ cur_usdt should be a subset of cur_btc_usdt. This function checks the average deviation. """ print("c-u first: {} last: {}".format( cur_usdt.index[0].strftime(t_f.DT_FORMAT), cur_usdt.index[len(cur_usdt)-1].strftime(t_f.DT_FORMAT))) print("c-b-u first: {} last: {}".format( cur_btc_usdt.index[0].strftime(t_f.DT_FORMAT), cur_btc_usdt.index[len(cur_btc_usdt)-1].strftime(t_f.DT_FORMAT))) diff = cur_btc_usdt[cur_btc_usdt.index.isin(cur_usdt.index)] for key in DATA_KEYS: if key != 'volume': diff[key] = (cur_btc_usdt[key] - cur_usdt[key]) / cur_usdt[key] else: diff[key] = cur_btc_usdt[key] - cur_usdt[key] diff_average = diff[key].sum() / len(cur_usdt) if key != 'volume': print(f"check_diff {key}: {diff_average:%}") else: print(f"check_diff {key}: {diff_average}")
Python
def visualize_results(self, epoch): tot_num_samples = min(self.sample_num, self.batch_size) image_frame_dim = int(np.floor(np.sqrt(tot_num_samples))) z_sample = np.random.uniform(-1, 1, size=(self.batch_size, self.z_dim)) """ random noise, random discrete code, fixed continuous code """ y = np.random.choice(self.len_discrete_code, self.batch_size) y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim*image_frame_dim,:,:,:], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes.png') """ specified condition, random noise """ n_styles = 10 # must be less than or equal to self.batch_size np.random.seed() si = np.random.choice(self.batch_size, n_styles) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim*image_frame_dim,:,:,:], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_%d.png' % l) samples = samples[si, :, :, :] if l == 0: all_samples = samples else: all_samples = np.concatenate((all_samples, samples), axis=0) """ save merged images to check style-consistency """ canvas = np.zeros_like(all_samples) for s in range(n_styles): for c in range(self.len_discrete_code): canvas[s * self.len_discrete_code + c, :, :, :] = all_samples[c * n_styles + s, :, :, :] save_images(canvas, [n_styles, self.len_discrete_code], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes_style_by_style.png')
def visualize_results(self, epoch): tot_num_samples = min(self.sample_num, self.batch_size) image_frame_dim = int(np.floor(np.sqrt(tot_num_samples))) z_sample = np.random.uniform(-1, 1, size=(self.batch_size, self.z_dim)) """ random noise, random discrete code, fixed continuous code """ y = np.random.choice(self.len_discrete_code, self.batch_size) y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim*image_frame_dim,:,:,:], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes.png') """ specified condition, random noise """ n_styles = 10 # must be less than or equal to self.batch_size np.random.seed() si = np.random.choice(self.batch_size, n_styles) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim*image_frame_dim,:,:,:], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_%d.png' % l) samples = samples[si, :, :, :] if l == 0: all_samples = samples else: all_samples = np.concatenate((all_samples, samples), axis=0) """ save merged images to check style-consistency """ canvas = np.zeros_like(all_samples) for s in range(n_styles): for c in range(self.len_discrete_code): canvas[s * self.len_discrete_code + c, :, :, :] = all_samples[c * n_styles + s, :, :, :] save_images(canvas, [n_styles, self.len_discrete_code], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes_style_by_style.png')
Python
def visualize_results(self, epoch): tot_num_samples = min(self.sample_num, self.batch_size) image_frame_dim = int(np.floor(np.sqrt(tot_num_samples))) """ random noise, random discrete code, fixed continuous code """ y = np.random.choice(self.len_discrete_code, self.batch_size) y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 z_sample = np.random.uniform(-1, 1, size=(self.batch_size, self.z_dim)) samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes.png') """ specified condition, random noise """ n_styles = 10 # must be less than or equal to self.batch_size np.random.seed() si = np.random.choice(self.batch_size, n_styles) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) # save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], # check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_%d.png' % l) samples = samples[si, :, :, :] if l == 0: all_samples = samples else: all_samples = np.concatenate((all_samples, samples), axis=0) """ save merged images to check style-consistency """ canvas = np.zeros_like(all_samples) for s in range(n_styles): for c in range(self.len_discrete_code): canvas[s * self.len_discrete_code + c, :, :, :] = all_samples[c * n_styles + s, :, :, :] save_images(canvas, [n_styles, self.len_discrete_code], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes_style_by_style.png') """ fixed noise """ assert self.len_continuous_code == 2 c1 = np.linspace(-1, 1, image_frame_dim) c2 = np.linspace(-1, 1, image_frame_dim) xv, yv = np.meshgrid(c1, c2) xv = xv[:image_frame_dim,:image_frame_dim] yv = yv[:image_frame_dim, :image_frame_dim] c1 = xv.flatten() c2 = yv.flatten() z_fixed = np.zeros([self.batch_size, self.z_dim]) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 y_one_hot[np.arange(image_frame_dim*image_frame_dim), self.len_discrete_code] = c1 y_one_hot[np.arange(image_frame_dim*image_frame_dim), self.len_discrete_code+1] = c2 samples = self.sess.run(self.fake_images, feed_dict={ self.z: z_fixed, self.y: y_one_hot}) save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_c1c2_%d.png' % l)
def visualize_results(self, epoch): tot_num_samples = min(self.sample_num, self.batch_size) image_frame_dim = int(np.floor(np.sqrt(tot_num_samples))) """ random noise, random discrete code, fixed continuous code """ y = np.random.choice(self.len_discrete_code, self.batch_size) y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 z_sample = np.random.uniform(-1, 1, size=(self.batch_size, self.z_dim)) samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes.png') """ specified condition, random noise """ n_styles = 10 # must be less than or equal to self.batch_size np.random.seed() si = np.random.choice(self.batch_size, n_styles) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample, self.y: y_one_hot}) # save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], # check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_%d.png' % l) samples = samples[si, :, :, :] if l == 0: all_samples = samples else: all_samples = np.concatenate((all_samples, samples), axis=0) """ save merged images to check style-consistency """ canvas = np.zeros_like(all_samples) for s in range(n_styles): for c in range(self.len_discrete_code): canvas[s * self.len_discrete_code + c, :, :, :] = all_samples[c * n_styles + s, :, :, :] save_images(canvas, [n_styles, self.len_discrete_code], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes_style_by_style.png') """ fixed noise """ assert self.len_continuous_code == 2 c1 = np.linspace(-1, 1, image_frame_dim) c2 = np.linspace(-1, 1, image_frame_dim) xv, yv = np.meshgrid(c1, c2) xv = xv[:image_frame_dim,:image_frame_dim] yv = yv[:image_frame_dim, :image_frame_dim] c1 = xv.flatten() c2 = yv.flatten() z_fixed = np.zeros([self.batch_size, self.z_dim]) for l in range(self.len_discrete_code): y = np.zeros(self.batch_size, dtype=np.int64) + l y_one_hot = np.zeros((self.batch_size, self.y_dim)) y_one_hot[np.arange(self.batch_size), y] = 1 y_one_hot[np.arange(image_frame_dim*image_frame_dim), self.len_discrete_code] = c1 y_one_hot[np.arange(image_frame_dim*image_frame_dim), self.len_discrete_code+1] = c2 samples = self.sess.run(self.fake_images, feed_dict={ self.z: z_fixed, self.y: y_one_hot}) save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_class_c1c2_%d.png' % l)
Python
def solve(self): """ Returns TRUE if SAT, False if UNSAT :return: whether there is a solution """ self.preprocess() while not self.are_all_variables_assigned(): conf_cls = self.unit_propagate() if conf_cls is not None: # there is conflict in unit propagation logger.fine('implication nodes: \n%s', self.nodes) lvl, learnt = self.conflict_analyze(conf_cls) logger.info('level reset to %s', lvl) logger.debug('learnt: %s', learnt) if lvl < 0: return False self.learnts.add(learnt) self.backtrack(lvl) self.level = lvl elif self.are_all_variables_assigned(): break else: # branching self.level += 1 self.branching_count += 1 bt_var, bt_val = self.pick_branching_variable() logger.info('--------decision level: %s ---------', self.level) self.assigns[bt_var] = bt_val self.branching_vars.add(bt_var) self.branching_history[self.level] = bt_var self.propagate_history[self.level] = deque() self.update_graph(bt_var) logger.info('picking %s to be %s', bt_var, 'TRUE' if bt_val == TRUE else 'FALSE') logger.debug('branching variables: %s', self.branching_history) logger.debug('propagate variables: %s', self.propagate_history) logger.debug('learnts: \n%s', self.learnts) return True
def solve(self): """ Returns TRUE if SAT, False if UNSAT :return: whether there is a solution """ self.preprocess() while not self.are_all_variables_assigned(): conf_cls = self.unit_propagate() if conf_cls is not None: # there is conflict in unit propagation logger.fine('implication nodes: \n%s', self.nodes) lvl, learnt = self.conflict_analyze(conf_cls) logger.info('level reset to %s', lvl) logger.debug('learnt: %s', learnt) if lvl < 0: return False self.learnts.add(learnt) self.backtrack(lvl) self.level = lvl elif self.are_all_variables_assigned(): break else: # branching self.level += 1 self.branching_count += 1 bt_var, bt_val = self.pick_branching_variable() logger.info('--------decision level: %s ---------', self.level) self.assigns[bt_var] = bt_val self.branching_vars.add(bt_var) self.branching_history[self.level] = bt_var self.propagate_history[self.level] = deque() self.update_graph(bt_var) logger.info('picking %s to be %s', bt_var, 'TRUE' if bt_val == TRUE else 'FALSE') logger.debug('branching variables: %s', self.branching_history) logger.debug('propagate variables: %s', self.propagate_history) logger.debug('learnts: \n%s', self.learnts) return True
Python
def read_file(filename): """ Reads a DIMACS CNF format file, returns clauses (set of frozenset) and literals (set of int). :param filename: the file name :raises FileFormatError: when file format is wrong :returns: (clauses, literals) """ with open(filename) as f: lines = [ line.strip().split() for line in f.readlines() if (not (line.startswith('c') or line.startswith('%') or line.startswith('0')) and line != '\n') ] if lines[0][:2] == ['p', 'cnf']: count_literals, count_clauses = map(int, lines[0][-2:]) else: raise FileFormatError('Number of literals and clauses are not declared properly.') literals = set() clauses = set() for line in lines[1:]: if line[-1] != '0': raise FileFormatError('Each line of clauses must end with 0.') clause = frozenset(map(int, line[:-1])) literals.update(map(abs, clause)) clauses.add(clause) if len(literals) != count_literals or len(lines) - 1 != count_clauses: raise FileFormatError( 'Unmatched literal count or clause count.' ' Literals expected: {}, actual: {}.' ' Clauses expected: {}, actual: {}.' .format(count_literals, len(literals), count_clauses, len(clauses))) logger.fine('clauses: %s', clauses) logger.fine('literals: %s', literals) return clauses, literals
def read_file(filename): """ Reads a DIMACS CNF format file, returns clauses (set of frozenset) and literals (set of int). :param filename: the file name :raises FileFormatError: when file format is wrong :returns: (clauses, literals) """ with open(filename) as f: lines = [ line.strip().split() for line in f.readlines() if (not (line.startswith('c') or line.startswith('%') or line.startswith('0')) and line != '\n') ] if lines[0][:2] == ['p', 'cnf']: count_literals, count_clauses = map(int, lines[0][-2:]) else: raise FileFormatError('Number of literals and clauses are not declared properly.') literals = set() clauses = set() for line in lines[1:]: if line[-1] != '0': raise FileFormatError('Each line of clauses must end with 0.') clause = frozenset(map(int, line[:-1])) literals.update(map(abs, clause)) clauses.add(clause) if len(literals) != count_literals or len(lines) - 1 != count_clauses: raise FileFormatError( 'Unmatched literal count or clause count.' ' Literals expected: {}, actual: {}.' ' Clauses expected: {}, actual: {}.' .format(count_literals, len(literals), count_clauses, len(clauses))) logger.fine('clauses: %s', clauses) logger.fine('literals: %s', literals) return clauses, literals
Python
def add(self, items: list): """ Add items to the list Args: items - list of DeliveryItems """ if items is None: raise Exception("items is None") items_list = list(map( lambda item: item.to_dict(), items )) items_list = items_list self.items += items_list
def add(self, items: list): """ Add items to the list Args: items - list of DeliveryItems """ if items is None: raise Exception("items is None") items_list = list(map( lambda item: item.to_dict(), items )) items_list = items_list self.items += items_list
Python
def is_valid(response_data, raise_exception=True): """ checks if the response is valid or has an error Args: response_data - data from the request raise_exception - boolean value whether to raise exception or not """ response_status = response_data.get('status') if not response_status and raise_exception: raise SendyAPIError(response_data.get('description', response_data.get('data'))) return bool(response_status)
def is_valid(response_data, raise_exception=True): """ checks if the response is valid or has an error Args: response_data - data from the request raise_exception - boolean value whether to raise exception or not """ response_status = response_data.get('status') if not response_status and raise_exception: raise SendyAPIError(response_data.get('description', response_data.get('data'))) return bool(response_status)
Python
def make_delivery(self, recipient, sender, to_location, from_location, delivery_details=None, vendor_type=1, order=False): """ Make a new delivery to requested location """ return self._request_delivery( recipient=recipient, sender=sender, to_location=to_location, from_location=from_location, vendor_type=vendor_type, order=order, delivery_details=delivery_details, request_type='delivery', )
def make_delivery(self, recipient, sender, to_location, from_location, delivery_details=None, vendor_type=1, order=False): """ Make a new delivery to requested location """ return self._request_delivery( recipient=recipient, sender=sender, to_location=to_location, from_location=from_location, vendor_type=vendor_type, order=order, delivery_details=delivery_details, request_type='delivery', )
Python
def _delivery_operations(self, operation, order_no): """Bundles all order_no specific operations together""" url_path = '{}#{}'.format(self.api_url, operation) pay_load = { 'command': operation, 'data': { **self.auth, 'order_no': order_no } } headers = {'content-type': 'application/json'} response = requests.post( url_path, data=json.dumps(pay_load), headers=headers ) response.raise_for_status() response_data = response.json() # check if response was successful else raise and error is_valid(response_data, raise_exception=True) return response_data
def _delivery_operations(self, operation, order_no): """Bundles all order_no specific operations together""" url_path = '{}#{}'.format(self.api_url, operation) pay_load = { 'command': operation, 'data': { **self.auth, 'order_no': order_no } } headers = {'content-type': 'application/json'} response = requests.post( url_path, data=json.dumps(pay_load), headers=headers ) response.raise_for_status() response_data = response.json() # check if response was successful else raise and error is_valid(response_data, raise_exception=True) return response_data
Python
def annuity(n,r): """Calculate the annuity factor for an asset with lifetime n years and discount rate of r, e.g. annuity(20,0.05)*20 = 1.6""" if r > 0: return r/(1. - 1./(1.+r)**n) else: return 1/n
def annuity(n,r): """Calculate the annuity factor for an asset with lifetime n years and discount rate of r, e.g. annuity(20,0.05)*20 = 1.6""" if r > 0: return r/(1. - 1./(1.+r)**n) else: return 1/n
Python
def ugettext(message, context=None): """Always return a stripped string, localized if possible""" stripped = strip_whitespace(message) message = add_context(context, stripped) if context else stripped ret = django_ugettext(message) # If the context isn't found, we need to return the string without it return stripped if ret == message else ret
def ugettext(message, context=None): """Always return a stripped string, localized if possible""" stripped = strip_whitespace(message) message = add_context(context, stripped) if context else stripped ret = django_ugettext(message) # If the context isn't found, we need to return the string without it return stripped if ret == message else ret
Python
def ungettext(singular, plural, number, context=None): """Always return a stripped string, localized if possible""" singular_stripped = strip_whitespace(singular) plural_stripped = strip_whitespace(plural) if context: singular = add_context(context, singular_stripped) plural = add_context(context, plural_stripped) else: singular = singular_stripped plural = plural_stripped ret = django_nugettext(singular, plural, number) # If the context isn't found, the string is returned as it came if ret == singular: return singular_stripped elif ret == plural: return plural_stripped return ret
def ungettext(singular, plural, number, context=None): """Always return a stripped string, localized if possible""" singular_stripped = strip_whitespace(singular) plural_stripped = strip_whitespace(plural) if context: singular = add_context(context, singular_stripped) plural = add_context(context, plural_stripped) else: singular = singular_stripped plural = plural_stripped ret = django_nugettext(singular, plural, number) # If the context isn't found, the string is returned as it came if ret == singular: return singular_stripped elif ret == plural: return plural_stripped return ret
Python
def install_jinja_translations(): """ Install our gettext and ngettext functions into Jinja2's environment. """ class Translation(object): """ We pass this object to jinja so it can find our gettext implementation. If we pass the GNUTranslation object directly, it won't have our context and whitespace stripping action. """ ugettext = staticmethod(ugettext) ungettext = staticmethod(ungettext) import jingo jingo.env.install_gettext_translations(Translation)
def install_jinja_translations(): """ Install our gettext and ngettext functions into Jinja2's environment. """ class Translation(object): """ We pass this object to jinja so it can find our gettext implementation. If we pass the GNUTranslation object directly, it won't have our context and whitespace stripping action. """ ugettext = staticmethod(ugettext) ungettext = staticmethod(ungettext) import jingo jingo.env.install_gettext_translations(Translation)
Python
async def shutdown(loop, process_signal=None): """Cleanup tasks tied to the service's shutdown.""" if process_signal: logger.info(f"Received exit signal {process_signal.name}...") tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] logger.info(f"Cancelling {len(tasks)} outstanding tasks") for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) # https://github.com/zeromq/pyzmq/issues/1167 logger.debug("Destroying ZMQ context.") MessagingSocket.ctx.destroy(linger=0) loop.stop()
async def shutdown(loop, process_signal=None): """Cleanup tasks tied to the service's shutdown.""" if process_signal: logger.info(f"Received exit signal {process_signal.name}...") tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] logger.info(f"Cancelling {len(tasks)} outstanding tasks") for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) # https://github.com/zeromq/pyzmq/issues/1167 logger.debug("Destroying ZMQ context.") MessagingSocket.ctx.destroy(linger=0) loop.stop()
Python
def validate_process_names(process_names: List[str]): """ Compare a list of names against the list of registered processes. If there are names given that do not exist in the list of registered processes a click exception will be raised. :param process_names: A list of names that will be validated against the registered processes. :raise: `ClickException` """ invalid_process_names = [ name for name in process_names if name not in AVAILABLE_PROCESSES ] if invalid_process_names: raise ClickException( f"Following process names are invalid: {', '.join(invalid_process_names)}" )
def validate_process_names(process_names: List[str]): """ Compare a list of names against the list of registered processes. If there are names given that do not exist in the list of registered processes a click exception will be raised. :param process_names: A list of names that will be validated against the registered processes. :raise: `ClickException` """ invalid_process_names = [ name for name in process_names if name not in AVAILABLE_PROCESSES ] if invalid_process_names: raise ClickException( f"Following process names are invalid: {', '.join(invalid_process_names)}" )
Python
def start_multiple_processes(process_names: List[str]): """ Start one or multiple processes using Python's multiprocessing module. While it is technically possible to start only one process with this method, it is rather pointless to do so. :param process_names: A list of process names that were registered with `register_process`. """ validate_process_names(process_names) processes = [] for name in process_names: entry_point = AVAILABLE_PROCESSES[name] processes.append( multiprocessing.Process( name=name, target=run_process, args=(entry_point,), daemon=False, ) ) for process_name in processes: time.sleep(0.1) process_name.start() for process_name in processes: process_name.join()
def start_multiple_processes(process_names: List[str]): """ Start one or multiple processes using Python's multiprocessing module. While it is technically possible to start only one process with this method, it is rather pointless to do so. :param process_names: A list of process names that were registered with `register_process`. """ validate_process_names(process_names) processes = [] for name in process_names: entry_point = AVAILABLE_PROCESSES[name] processes.append( multiprocessing.Process( name=name, target=run_process, args=(entry_point,), daemon=False, ) ) for process_name in processes: time.sleep(0.1) process_name.start() for process_name in processes: process_name.join()
Python
def register_process(name: str, path: str): """ Register a new process with the CLI and meru in general. :param name: The name of the process to be used for the CLI :param path: The entry point of the method. """ process_cli.command(name=name)(lambda: run_process(AVAILABLE_PROCESSES[name])) AVAILABLE_PROCESSES[name] = path
def register_process(name: str, path: str): """ Register a new process with the CLI and meru in general. :param name: The name of the process to be used for the CLI :param path: The entry point of the method. """ process_cli.command(name=name)(lambda: run_process(AVAILABLE_PROCESSES[name])) AVAILABLE_PROCESSES[name] = path
Python
def inspect_action_handler_args(func: callable): """ Inspects and action handler's calling arguments. An action handler can only have one action and state nodes as calling arguments. Calling args need to be annotated in order to be recognized. Having any other type or no type at all will raise an exception. This will be fine: async def do_something(action: SomeActionClass, some_state: SomeStateClass): pass This will not be fine, action is not annotated, some_param has an invalid type: async def do_something(action, some_param: int): pass :param func: :return: """ found_action = None required_states = set() signature = inspect.signature(func) for param in signature.parameters.values(): if issubclass(param.annotation, Action): if found_action is not None: raise HandlerException("An action handler can have only one action.") found_action = param.annotation elif issubclass(param.annotation, StateNode): if param.annotation in required_states: raise HandlerException( f"Type '{param.annotation.__name__}' has been added twice to handler '{func.__name__}'. " f"This is not possible." ) required_states.add(param.annotation) else: raise HandlerException( f"Error registering {func.__name__}. " f"An action handler can only have Actions and StateNodes as calling args. " f"'{param}' is invalid." ) if found_action is None: raise HandlerException("An action handler needs one action.") return found_action, required_states
def inspect_action_handler_args(func: callable): """ Inspects and action handler's calling arguments. An action handler can only have one action and state nodes as calling arguments. Calling args need to be annotated in order to be recognized. Having any other type or no type at all will raise an exception. This will be fine: async def do_something(action: SomeActionClass, some_state: SomeStateClass): pass This will not be fine, action is not annotated, some_param has an invalid type: async def do_something(action, some_param: int): pass :param func: :return: """ found_action = None required_states = set() signature = inspect.signature(func) for param in signature.parameters.values(): if issubclass(param.annotation, Action): if found_action is not None: raise HandlerException("An action handler can have only one action.") found_action = param.annotation elif issubclass(param.annotation, StateNode): if param.annotation in required_states: raise HandlerException( f"Type '{param.annotation.__name__}' has been added twice to handler '{func.__name__}'. " f"This is not possible." ) required_states.add(param.annotation) else: raise HandlerException( f"Error registering {func.__name__}. " f"An action handler can only have Actions and StateNodes as calling args. " f"'{param}' is invalid." ) if found_action is None: raise HandlerException("An action handler needs one action.") return found_action, required_states
Python
async def request_states(): """ Request states from the state manager. In order for this do have any effect all required states have to be registered:: register_state(SomeState) :return: All loaded states """ state_consumer = StateConsumerSocket() states_to_request = list(STATES.keys()) action = RequireState(states_to_request) await state_consumer.send(action) state = await state_consumer.receive() for node in state.nodes: STATES[node.__class__] = node logging.info(f"Loaded state from broker: {node.__class__.__name__}") return STATES
async def request_states(): """ Request states from the state manager. In order for this do have any effect all required states have to be registered:: register_state(SomeState) :return: All loaded states """ state_consumer = StateConsumerSocket() states_to_request = list(STATES.keys()) action = RequireState(states_to_request) await state_consumer.send(action) state = await state_consumer.receive() for node in state.nodes: STATES[node.__class__] = node logging.info(f"Loaded state from broker: {node.__class__.__name__}") return STATES
Python
def creg_com_settings(self): """ The CREG_COM_SETTINGS register is used to set the boards serial port baud rate and to enable (disable) the automatic transmission of sensor data and estimated states (telemetry). Payload structure: [31:28] : BAUD_RATE -- Sets the baud rate of the boards main serial port: :return: BAUD_RATE as bitField; """ addr = 0x00 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_SETTINGS') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for BAUD_RATE bit field baud_rate_val = (reg.raw_value >> 28) & 0x000F baud_rate_enum = reg.find_field_by(name='BAUD_RATE').find_enum_entry_by(value=baud_rate_val) return reg, baud_rate_enum
def creg_com_settings(self): """ The CREG_COM_SETTINGS register is used to set the boards serial port baud rate and to enable (disable) the automatic transmission of sensor data and estimated states (telemetry). Payload structure: [31:28] : BAUD_RATE -- Sets the baud rate of the boards main serial port: :return: BAUD_RATE as bitField; """ addr = 0x00 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_SETTINGS') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for BAUD_RATE bit field baud_rate_val = (reg.raw_value >> 28) & 0x000F baud_rate_enum = reg.find_field_by(name='BAUD_RATE').find_enum_entry_by(value=baud_rate_val) return reg, baud_rate_enum
Python
def creg_com_rates1(self): """ The CREG_COM_RATES1 register sets desired telemetry transmission rates in Hz for raw accelerometer 1, gyro 1, gyro 2 and magnetometer 1 data. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : RAW_ACCEL_1_RATE -- Specifies the desired raw accelerometer 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : RAW_GYRO_1_RATE -- Specifies the desired raw gyro 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz [15:8] : RAW_GYRO_2_RATE -- Specifies the desired raw gyro 2 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : RAW_MAG_1_RATE -- Specifies the desired raw magnetometer 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: RAW_ACCEL_1_RATE as uint8_t; RAW_GYRO_1_RATE as uint8_t; RAW_GYRO_2_RATE as uint8_t; RAW_MAG_1_RATE as uint8_t; """ addr = 0x01 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES1') reg.raw_value, = struct.unpack('>I', payload[0:4]) raw_accel_1_rate, raw_gyro_1_rate, raw_gyro_2_rate, raw_mag_1_rate = struct.unpack('>BBBB', payload[0:4]) return reg, raw_accel_1_rate, raw_gyro_1_rate, raw_gyro_2_rate, raw_mag_1_rate
def creg_com_rates1(self): """ The CREG_COM_RATES1 register sets desired telemetry transmission rates in Hz for raw accelerometer 1, gyro 1, gyro 2 and magnetometer 1 data. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : RAW_ACCEL_1_RATE -- Specifies the desired raw accelerometer 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : RAW_GYRO_1_RATE -- Specifies the desired raw gyro 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz [15:8] : RAW_GYRO_2_RATE -- Specifies the desired raw gyro 2 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : RAW_MAG_1_RATE -- Specifies the desired raw magnetometer 1 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: RAW_ACCEL_1_RATE as uint8_t; RAW_GYRO_1_RATE as uint8_t; RAW_GYRO_2_RATE as uint8_t; RAW_MAG_1_RATE as uint8_t; """ addr = 0x01 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES1') reg.raw_value, = struct.unpack('>I', payload[0:4]) raw_accel_1_rate, raw_gyro_1_rate, raw_gyro_2_rate, raw_mag_1_rate = struct.unpack('>BBBB', payload[0:4]) return reg, raw_accel_1_rate, raw_gyro_1_rate, raw_gyro_2_rate, raw_mag_1_rate
Python
def creg_com_rates2(self): """ The CREG_COM_RATES2 register sets desired telemetry transmission rates for the magnetometer 2, all raw data, and temperature data rate. The ALL_RAW_RATE setting has higher priority over the individual raw sensor data settings, i.e. whenever this bitfield is set, then the individual raw sensor settings are ignored and not used. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : TEMP_RATE -- Specifies the desired broadcast rate for temperature data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : RAW_MAG_2_RATE -- Specifies the desired raw magnetometer 2 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : ALL_RAW_RATE -- Specifies the desired broadcast rate for all raw sensor data. If set, this overrides the broadcast rate setting for individual raw data broadcast rates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: TEMP_RATE as uint8_t; RAW_MAG_2_RATE as uint8_t; ALL_RAW_RATE as uint8_t; """ addr = 0x02 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES2') reg.raw_value, = struct.unpack('>I', payload[0:4]) temp_rate, raw_mag_2_rate, all_raw_rate = struct.unpack('>BBxB', payload[0:4]) return reg, temp_rate, raw_mag_2_rate, all_raw_rate
def creg_com_rates2(self): """ The CREG_COM_RATES2 register sets desired telemetry transmission rates for the magnetometer 2, all raw data, and temperature data rate. The ALL_RAW_RATE setting has higher priority over the individual raw sensor data settings, i.e. whenever this bitfield is set, then the individual raw sensor settings are ignored and not used. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : TEMP_RATE -- Specifies the desired broadcast rate for temperature data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : RAW_MAG_2_RATE -- Specifies the desired raw magnetometer 2 data broadcast rate in Hz. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : ALL_RAW_RATE -- Specifies the desired broadcast rate for all raw sensor data. If set, this overrides the broadcast rate setting for individual raw data broadcast rates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: TEMP_RATE as uint8_t; RAW_MAG_2_RATE as uint8_t; ALL_RAW_RATE as uint8_t; """ addr = 0x02 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES2') reg.raw_value, = struct.unpack('>I', payload[0:4]) temp_rate, raw_mag_2_rate, all_raw_rate = struct.unpack('>BBxB', payload[0:4]) return reg, temp_rate, raw_mag_2_rate, all_raw_rate
Python
def creg_com_rates3(self): """ The CREG_COM_RATES3 register sets desired telemetry transmission rates for processed sensor data for the sensors: the accelerometer 1, gyro 1, gyro 2, and magnetometer 1. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : PROC_ACCEL_1_RATE -- Specifies the desired broadcast rate for processed accelerometer 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : PROC_GYRO_1_RATE -- Specifies the desired broadcast rate for processed rate gyro 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [15:8] : PROC_GYRO_2_RATE -- Specifies the desired broadcast rate for processed processed rate gyro 2 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : PROC_MAG_1_RATE -- Specifies the desired broadcast rate for processed magnetometer 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: PROC_ACCEL_1_RATE as uint8_t; PROC_GYRO_1_RATE as uint8_t; PROC_GYRO_2_RATE as uint8_t; PROC_MAG_1_RATE as uint8_t; """ addr = 0x03 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES3') reg.raw_value, = struct.unpack('>I', payload[0:4]) proc_accel_1_rate, proc_gyro_1_rate, proc_gyro_2_rate, proc_mag_1_rate = struct.unpack('>BBBB', payload[0:4]) return reg, proc_accel_1_rate, proc_gyro_1_rate, proc_gyro_2_rate, proc_mag_1_rate
def creg_com_rates3(self): """ The CREG_COM_RATES3 register sets desired telemetry transmission rates for processed sensor data for the sensors: the accelerometer 1, gyro 1, gyro 2, and magnetometer 1. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : PROC_ACCEL_1_RATE -- Specifies the desired broadcast rate for processed accelerometer 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : PROC_GYRO_1_RATE -- Specifies the desired broadcast rate for processed rate gyro 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [15:8] : PROC_GYRO_2_RATE -- Specifies the desired broadcast rate for processed processed rate gyro 2 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : PROC_MAG_1_RATE -- Specifies the desired broadcast rate for processed magnetometer 1 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: PROC_ACCEL_1_RATE as uint8_t; PROC_GYRO_1_RATE as uint8_t; PROC_GYRO_2_RATE as uint8_t; PROC_MAG_1_RATE as uint8_t; """ addr = 0x03 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES3') reg.raw_value, = struct.unpack('>I', payload[0:4]) proc_accel_1_rate, proc_gyro_1_rate, proc_gyro_2_rate, proc_mag_1_rate = struct.unpack('>BBBB', payload[0:4]) return reg, proc_accel_1_rate, proc_gyro_1_rate, proc_gyro_2_rate, proc_mag_1_rate
Python
def creg_com_rates4(self): """ The CREG_COM_RATES4 register defines the desired telemetry transmission rates for the processed data for the magnetometer 2, and for all processed data. The ALL_PROC_RATE setting has higher priority over the individual processed sensor data settings, i.e. whenever this bitfield is set, then the individual processed sensor transmission rate settings are ignored and not used. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : PROC_MAG_2_RATE -- Specifies the desired broadcast rate for processed magnetometer 2 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : ALL_PROC_RATE -- Specifies the desired broadcast rate for raw all processed sensor data. If set, this overrides the broadcast rate setting for individual processed data broadcast rates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: PROC_MAG_2_RATE as uint8_t; ALL_PROC_RATE as uint8_t; """ addr = 0x04 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES4') reg.raw_value, = struct.unpack('>I', payload[0:4]) proc_mag_2_rate, all_proc_rate = struct.unpack('>BxxB', payload[0:4]) return reg, proc_mag_2_rate, all_proc_rate
def creg_com_rates4(self): """ The CREG_COM_RATES4 register defines the desired telemetry transmission rates for the processed data for the magnetometer 2, and for all processed data. The ALL_PROC_RATE setting has higher priority over the individual processed sensor data settings, i.e. whenever this bitfield is set, then the individual processed sensor transmission rate settings are ignored and not used. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : PROC_MAG_2_RATE -- Specifies the desired broadcast rate for processed magnetometer 2 data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : ALL_PROC_RATE -- Specifies the desired broadcast rate for raw all processed sensor data. If set, this overrides the broadcast rate setting for individual processed data broadcast rates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: PROC_MAG_2_RATE as uint8_t; ALL_PROC_RATE as uint8_t; """ addr = 0x04 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES4') reg.raw_value, = struct.unpack('>I', payload[0:4]) proc_mag_2_rate, all_proc_rate = struct.unpack('>BxxB', payload[0:4]) return reg, proc_mag_2_rate, all_proc_rate
Python
def creg_com_rates5(self): """ The CREG_COM_RATES5 register sets desired telemetry transmission rates for quaternions, Euler Angles, position, and velocity estimates. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : QUAT_RATE -- Specifies the desired broadcast rate for quaternion data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : EULER_RATE -- Specifies the desired broadcast rate for Euler Angle data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [15:8] : POSITION_RATE -- Specifies the desired broadcast rate position. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : VELOCITY_RATE -- Specifies the desired broadcast rate for velocity. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: QUAT_RATE as uint8_t; EULER_RATE as uint8_t; POSITION_RATE as uint8_t; VELOCITY_RATE as uint8_t; """ addr = 0x05 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES5') reg.raw_value, = struct.unpack('>I', payload[0:4]) quat_rate, euler_rate, position_rate, velocity_rate = struct.unpack('>BBBB', payload[0:4]) return reg, quat_rate, euler_rate, position_rate, velocity_rate
def creg_com_rates5(self): """ The CREG_COM_RATES5 register sets desired telemetry transmission rates for quaternions, Euler Angles, position, and velocity estimates. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : QUAT_RATE -- Specifies the desired broadcast rate for quaternion data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [23:16] : EULER_RATE -- Specifies the desired broadcast rate for Euler Angle data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [15:8] : POSITION_RATE -- Specifies the desired broadcast rate position. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : VELOCITY_RATE -- Specifies the desired broadcast rate for velocity. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: QUAT_RATE as uint8_t; EULER_RATE as uint8_t; POSITION_RATE as uint8_t; VELOCITY_RATE as uint8_t; """ addr = 0x05 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES5') reg.raw_value, = struct.unpack('>I', payload[0:4]) quat_rate, euler_rate, position_rate, velocity_rate = struct.unpack('>BBBB', payload[0:4]) return reg, quat_rate, euler_rate, position_rate, velocity_rate
Python
def creg_com_rates6(self): """ The CREG_COM_RATES6 register sets desired telemetry transmission rates for pose (Euler/position packet), health, and gyro bias estimates for the gyro 1 and gyro 2. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : POSE_RATE -- Specifies the desired broadcast rate for pose (Euler Angle and position) data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [19:16] : HEALTH_RATE -- Specifies the desired broadcast rate for the sensor health packet. [15:8] : GYRO_BIAS_1_RATE -- Specifies the desired broadcast rate for gyro 1 bias estimates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : GYRO_BIAS_2_RATE -- Specifies the desired broadcast rate for gyro 2 bias estimates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: POSE_RATE as uint8_t; HEALTH_RATE as bitField; GYRO_BIAS_1_RATE as uint8_t; GYRO_BIAS_2_RATE as uint8_t; """ addr = 0x06 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES6') reg.raw_value, = struct.unpack('>I', payload[0:4]) pose_rate, gyro_bias_1_rate, gyro_bias_2_rate = struct.unpack('>BxBB', payload[0:4]) reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for HEALTH_RATE bit field health_rate_val = (reg.raw_value >> 16) & 0x000F health_rate_enum = reg.find_field_by(name='HEALTH_RATE').find_enum_entry_by(value=health_rate_val) return reg, pose_rate, gyro_bias_1_rate, gyro_bias_2_rate, reg, health_rate_enum
def creg_com_rates6(self): """ The CREG_COM_RATES6 register sets desired telemetry transmission rates for pose (Euler/position packet), health, and gyro bias estimates for the gyro 1 and gyro 2. If the specified rate is 0, then no data is transmitted. Payload structure: [31:24] : POSE_RATE -- Specifies the desired broadcast rate for pose (Euler Angle and position) data. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [19:16] : HEALTH_RATE -- Specifies the desired broadcast rate for the sensor health packet. [15:8] : GYRO_BIAS_1_RATE -- Specifies the desired broadcast rate for gyro 1 bias estimates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. [7:0] : GYRO_BIAS_2_RATE -- Specifies the desired broadcast rate for gyro 2 bias estimates. The data is stored as an unsigned 8-bit integer, yielding a maximum rate of 255 Hz. :return: POSE_RATE as uint8_t; HEALTH_RATE as bitField; GYRO_BIAS_1_RATE as uint8_t; GYRO_BIAS_2_RATE as uint8_t; """ addr = 0x06 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_COM_RATES6') reg.raw_value, = struct.unpack('>I', payload[0:4]) pose_rate, gyro_bias_1_rate, gyro_bias_2_rate = struct.unpack('>BxBB', payload[0:4]) reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for HEALTH_RATE bit field health_rate_val = (reg.raw_value >> 16) & 0x000F health_rate_enum = reg.find_field_by(name='HEALTH_RATE').find_enum_entry_by(value=health_rate_val) return reg, pose_rate, gyro_bias_1_rate, gyro_bias_2_rate, reg, health_rate_enum
Python
def creg_misc_settings(self): """ This register contains miscellaneous filter and sensor control options. Payload structure: [8] : PPS -- If set, this bit causes the TX2 pin on the IO Expansion header to be used as the PPS input from an external GPS module. PPS pulses will then be used to synchronize the system clock to UTC time of day. [3] : ZG -- If set, this bit causes the devicee to attempt to measure the rate gyro bias on startup. The sensor must be stationary on startup for this feature to work properly. [2] : Q -- If this bit is set, the sensor will run in quaternion mode instead of Euler Angle mode. [1] : MAG1 -- If set, the magnetometer 1 will be used in state updates. [0] : MAG2 -- If set, the magnetometer 2 will be used in state updates. :return: PPS as bitField; ZG as bitField; Q as bitField; MAG1 as bitField; MAG2 as bitField; """ addr = 0x08 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MISC_SETTINGS') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for PPS bit field pps_val = (reg.raw_value >> 8) & 0x0001 pps_enum = reg.find_field_by(name='PPS').find_enum_entry_by(value=pps_val) # find value for ZG bit field zg_val = (reg.raw_value >> 3) & 0x0001 zg_enum = reg.find_field_by(name='ZG').find_enum_entry_by(value=zg_val) # find value for Q bit field q_val = (reg.raw_value >> 2) & 0x0001 q_enum = reg.find_field_by(name='Q').find_enum_entry_by(value=q_val) # find value for MAG1 bit field mag1_val = (reg.raw_value >> 1) & 0x0001 mag1_enum = reg.find_field_by(name='MAG1').find_enum_entry_by(value=mag1_val) # find value for MAG2 bit field mag2_val = (reg.raw_value >> 0) & 0x0001 mag2_enum = reg.find_field_by(name='MAG2').find_enum_entry_by(value=mag2_val) return reg, pps_enum, zg_enum, q_enum, mag1_enum, mag2_enum
def creg_misc_settings(self): """ This register contains miscellaneous filter and sensor control options. Payload structure: [8] : PPS -- If set, this bit causes the TX2 pin on the IO Expansion header to be used as the PPS input from an external GPS module. PPS pulses will then be used to synchronize the system clock to UTC time of day. [3] : ZG -- If set, this bit causes the devicee to attempt to measure the rate gyro bias on startup. The sensor must be stationary on startup for this feature to work properly. [2] : Q -- If this bit is set, the sensor will run in quaternion mode instead of Euler Angle mode. [1] : MAG1 -- If set, the magnetometer 1 will be used in state updates. [0] : MAG2 -- If set, the magnetometer 2 will be used in state updates. :return: PPS as bitField; ZG as bitField; Q as bitField; MAG1 as bitField; MAG2 as bitField; """ addr = 0x08 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MISC_SETTINGS') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for PPS bit field pps_val = (reg.raw_value >> 8) & 0x0001 pps_enum = reg.find_field_by(name='PPS').find_enum_entry_by(value=pps_val) # find value for ZG bit field zg_val = (reg.raw_value >> 3) & 0x0001 zg_enum = reg.find_field_by(name='ZG').find_enum_entry_by(value=zg_val) # find value for Q bit field q_val = (reg.raw_value >> 2) & 0x0001 q_enum = reg.find_field_by(name='Q').find_enum_entry_by(value=q_val) # find value for MAG1 bit field mag1_val = (reg.raw_value >> 1) & 0x0001 mag1_enum = reg.find_field_by(name='MAG1').find_enum_entry_by(value=mag1_val) # find value for MAG2 bit field mag2_val = (reg.raw_value >> 0) & 0x0001 mag2_enum = reg.find_field_by(name='MAG2').find_enum_entry_by(value=mag2_val) return reg, pps_enum, zg_enum, q_enum, mag1_enum, mag2_enum
Python
def creg_gyro_1_meas_range(self): """ The CREG_GYRO_1_MEAS_RANGE register sets the desired measurement range for the gyro 1 sensor. If the rate is not set, then the default value of 2000 deg/s will be used as a measurement range. Payload structure: [1:0] : MEAS_GYRO1 -- Specifies the desired measurement range for the gyro 1 measurements. :return: MEAS_GYRO1 as bitField; """ addr = 0x09 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_GYRO1 bit field meas_gyro1_val = (reg.raw_value >> 0) & 0x0003 meas_gyro1_enum = reg.find_field_by(name='MEAS_GYRO1').find_enum_entry_by(value=meas_gyro1_val) return reg, meas_gyro1_enum
def creg_gyro_1_meas_range(self): """ The CREG_GYRO_1_MEAS_RANGE register sets the desired measurement range for the gyro 1 sensor. If the rate is not set, then the default value of 2000 deg/s will be used as a measurement range. Payload structure: [1:0] : MEAS_GYRO1 -- Specifies the desired measurement range for the gyro 1 measurements. :return: MEAS_GYRO1 as bitField; """ addr = 0x09 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_GYRO1 bit field meas_gyro1_val = (reg.raw_value >> 0) & 0x0003 meas_gyro1_enum = reg.find_field_by(name='MEAS_GYRO1').find_enum_entry_by(value=meas_gyro1_val) return reg, meas_gyro1_enum
Python
def creg_gyro_1_trim_x(self): """ This register sets the x-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_X -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_X as float; """ addr = 0x0A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_x,
def creg_gyro_1_trim_x(self): """ This register sets the x-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_X -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_X as float; """ addr = 0x0A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_x,
Python
def creg_gyro_1_trim_y(self): """ This register sets the y-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_Y -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_Y as float; """ addr = 0x0B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_y,
def creg_gyro_1_trim_y(self): """ This register sets the y-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_Y -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_Y as float; """ addr = 0x0B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_y,
Python
def creg_gyro_1_trim_z(self): """ This register sets the z-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_Z -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_Z as float; """ addr = 0x0C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_z,
def creg_gyro_1_trim_z(self): """ This register sets the z-axis rate gyro 1 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_1_TRIM_Z -- 32-bit IEEE Floating Point Value :return: GYRO_1_TRIM_Z as float; """ addr = 0x0C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_1_TRIM_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_trim_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_trim_z,
Python
def creg_gyro_2_meas_range(self): """ The CREG_GYRO_2_MEAS_RANGE register sets the desired measurement range for the gyro 2 sensor. If the rate is not set, then the default value of 2000 deg/s will be used as a measurement range. Payload structure: [1:0] : MEAS_GYRO2 -- Specifies the desired measurement range for the gyro 2 measurements. :return: MEAS_GYRO2 as bitField; """ addr = 0x0D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_GYRO2 bit field meas_gyro2_val = (reg.raw_value >> 0) & 0x0003 meas_gyro2_enum = reg.find_field_by(name='MEAS_GYRO2').find_enum_entry_by(value=meas_gyro2_val) return reg, meas_gyro2_enum
def creg_gyro_2_meas_range(self): """ The CREG_GYRO_2_MEAS_RANGE register sets the desired measurement range for the gyro 2 sensor. If the rate is not set, then the default value of 2000 deg/s will be used as a measurement range. Payload structure: [1:0] : MEAS_GYRO2 -- Specifies the desired measurement range for the gyro 2 measurements. :return: MEAS_GYRO2 as bitField; """ addr = 0x0D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_GYRO2 bit field meas_gyro2_val = (reg.raw_value >> 0) & 0x0003 meas_gyro2_enum = reg.find_field_by(name='MEAS_GYRO2').find_enum_entry_by(value=meas_gyro2_val) return reg, meas_gyro2_enum
Python
def creg_gyro_2_trim_x(self): """ This register sets the x-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_X -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_X as float; """ addr = 0x0E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_x,
def creg_gyro_2_trim_x(self): """ This register sets the x-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_X -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_X as float; """ addr = 0x0E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_x,
Python
def creg_gyro_2_trim_y(self): """ This register sets the y-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_Y -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_Y as float; """ addr = 0x0F ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_y,
def creg_gyro_2_trim_y(self): """ This register sets the y-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_Y -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_Y as float; """ addr = 0x0F ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_y,
Python
def creg_gyro_2_trim_z(self): """ This register sets the z-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_Z -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_Z as float; """ addr = 0x10 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_z,
def creg_gyro_2_trim_z(self): """ This register sets the z-axis rate gyro 2 trim, which is used to add additional bias compensation for the rate gyros during calls to the ZERO_GYRO_BIAS command. Payload structure: [31:0] : GYRO_2_TRIM_Z -- 32-bit IEEE Floating Point Value :return: GYRO_2_TRIM_Z as float; """ addr = 0x10 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_GYRO_2_TRIM_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_trim_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_trim_z,
Python
def creg_mag_1_bias_x(self): """ This register stores a bias term for the magnetometer 1 x-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_X -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_X as float; """ addr = 0x1A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_x, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_x,
def creg_mag_1_bias_x(self): """ This register stores a bias term for the magnetometer 1 x-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_X -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_X as float; """ addr = 0x1A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_x, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_x,
Python
def creg_mag_1_bias_y(self): """ This register stores a bias term for the magnetometer 1 y-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_Y -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_Y as float; """ addr = 0x1B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_y, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_y,
def creg_mag_1_bias_y(self): """ This register stores a bias term for the magnetometer 1 y-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_Y -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_Y as float; """ addr = 0x1B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_y, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_y,
Python
def creg_mag_1_bias_z(self): """ This register stores a bias term for the magnetometer 1 z-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_Z -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_Z as float; """ addr = 0x1C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_z, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_z,
def creg_mag_1_bias_z(self): """ This register stores a bias term for the magnetometer 1 z-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_1_BIAS_Z -- 32-bit IEEE Floating Point Value :return: MAG_1_BIAS_Z as float; """ addr = 0x1C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_1_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_bias_z, = struct.unpack('>f', payload[0:4]) return reg, mag_1_bias_z,
Python
def creg_mag_2_bias_x(self): """ This register stores a bias term for the magnetometer 2 x-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_X -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_X as float; """ addr = 0x26 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_x, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_x,
def creg_mag_2_bias_x(self): """ This register stores a bias term for the magnetometer 2 x-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_X -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_X as float; """ addr = 0x26 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_x, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_x,
Python
def creg_mag_2_bias_y(self): """ This register stores a bias term for the magnetometer 2 y-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_Y -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_Y as float; """ addr = 0x27 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_y, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_y,
def creg_mag_2_bias_y(self): """ This register stores a bias term for the magnetometer 2 y-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_Y -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_Y as float; """ addr = 0x27 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_y, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_y,
Python
def creg_mag_2_bias_z(self): """ This register stores a bias term for the magnetometer 2 z-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_Z -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_Z as float; """ addr = 0x28 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_z, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_z,
def creg_mag_2_bias_z(self): """ This register stores a bias term for the magnetometer 2 z-axis for hard-iron calibration. This term can be computed by performing magnetometer calibration with the Redshift labs Serial Interface. Payload structure: [31:0] : MAG_2_BIAS_Z -- 32-bit IEEE Floating Point Value :return: MAG_2_BIAS_Z as float; """ addr = 0x28 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_MAG_2_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_bias_z, = struct.unpack('>f', payload[0:4]) return reg, mag_2_bias_z,
Python
def creg_accel_1_meas_range(self): """ The CREG_ACCEL_1_MEAS_RANGE register sets the desired measurement range for the accelerometer 1. If the rate is not set, then the default value of the +-2 g will be used as a measurement range. Payload structure: [1:0] : MEAS_ACC1 -- Specifies the desired measurement range for the accelerometer 1 measurements. :return: MEAS_ACC1 as bitField; """ addr = 0x29 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_ACC1 bit field meas_acc1_val = (reg.raw_value >> 0) & 0x0003 meas_acc1_enum = reg.find_field_by(name='MEAS_ACC1').find_enum_entry_by(value=meas_acc1_val) return reg, meas_acc1_enum
def creg_accel_1_meas_range(self): """ The CREG_ACCEL_1_MEAS_RANGE register sets the desired measurement range for the accelerometer 1. If the rate is not set, then the default value of the +-2 g will be used as a measurement range. Payload structure: [1:0] : MEAS_ACC1 -- Specifies the desired measurement range for the accelerometer 1 measurements. :return: MEAS_ACC1 as bitField; """ addr = 0x29 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_MEAS_RANGE') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for MEAS_ACC1 bit field meas_acc1_val = (reg.raw_value >> 0) & 0x0003 meas_acc1_enum = reg.find_field_by(name='MEAS_ACC1').find_enum_entry_by(value=meas_acc1_val) return reg, meas_acc1_enum
Python
def creg_accel_1_bias_x(self): """ This register stores a bias term for the accelerometer 1 x-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_X -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_X as float; """ addr = 0x33 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_x, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_x,
def creg_accel_1_bias_x(self): """ This register stores a bias term for the accelerometer 1 x-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_X -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_X as float; """ addr = 0x33 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_x, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_x,
Python
def creg_accel_1_bias_y(self): """ This register stores a bias term for the accelerometer 1 y-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_Y -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_Y as float; """ addr = 0x34 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_y, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_y,
def creg_accel_1_bias_y(self): """ This register stores a bias term for the accelerometer 1 y-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_Y -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_Y as float; """ addr = 0x34 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_y, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_y,
Python
def creg_accel_1_bias_z(self): """ This register stores a bias term for the accelerometer 1 z-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_Z -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_Z as float; """ addr = 0x35 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_z, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_z,
def creg_accel_1_bias_z(self): """ This register stores a bias term for the accelerometer 1 z-axis for bias calibration. This term can be computed by performing calibrate accelerometers command within the Redshift labs Serial Interface. Payload structure: [31:0] : ACCEL_1_BIAS_Z -- 32-bit IEEE Floating Point Value :return: ACCEL_1_BIAS_Z as float; """ addr = 0x35 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='CREG_ACCEL_1_BIAS_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_bias_z, = struct.unpack('>f', payload[0:4]) return reg, accel_1_bias_z,
Python
def dreg_health(self): """ The health register reports the current status of the sensors on the board. Monitoring the health register is the easiest way to watch for other problems that could affect the behavior of the board, status of the sensors. The analogous to the health register, the status of the GPS signal can be monitored in the DREG_GPS_HEALTH Payload structure: [8] : OVF -- Overflow bit. This bit is set if the board is attempting to transmit data over the serial port faster than is allowed given the baud-rate. If this bit is set, reduce broadcast rates in the COM_RATES registers. [7] : ACC1_N -- This bit is set if the sensor detects that the norm of the accelerometer measurement is too far away from 1G to be used (i.e. during aggressive acceleration or high vibration). [6] : MAG1_N -- This bit is set if the sensor detects that the norm of the magnetometer measurement for the magnetometer 1 is too far away from 1.0 to be trusted. Usually indicates bad calibration, local field distortions, or both. [5] : MAG2_N -- This bit is set if the sensor detects that the norm of the magnetometer measurement for the magnetometer 2 is too far away from 1.0 to be trusted. Usually indicates bad calibration, local field distortions, or both. [4] : ACCEL1 -- This bit will be set if the accelerometer 1 fails to initialize on startup. [3] : GYRO1 -- This bit will be set if the rate gyro 1 fails to initialize on startup. [2] : GYRO2 -- This bit will be set if the rate gyro 2 fails to initialize on startup. [1] : MAG1 -- This bit will be set if the magnetometer 1 fails to initialize on startup. [0] : MAG2 -- This bit will be set if the magnetometer 2 fails to initialize on startup. :return: OVF as bitField; ACC1_N as bitField; MAG1_N as bitField; MAG2_N as bitField; ACCEL1 as bitField; GYRO1 as bitField; GYRO2 as bitField; MAG1 as bitField; MAG2 as bitField; """ addr = 0x55 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_HEALTH') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for OVF bit field ovf_val = (reg.raw_value >> 8) & 0x0001 ovf_enum = reg.find_field_by(name='OVF').find_enum_entry_by(value=ovf_val) # find value for ACC1_N bit field acc1_n_val = (reg.raw_value >> 7) & 0x0001 acc1_n_enum = reg.find_field_by(name='ACC1_N').find_enum_entry_by(value=acc1_n_val) # find value for MAG1_N bit field mag1_n_val = (reg.raw_value >> 6) & 0x0001 mag1_n_enum = reg.find_field_by(name='MAG1_N').find_enum_entry_by(value=mag1_n_val) # find value for MAG2_N bit field mag2_n_val = (reg.raw_value >> 5) & 0x0001 mag2_n_enum = reg.find_field_by(name='MAG2_N').find_enum_entry_by(value=mag2_n_val) # find value for ACCEL1 bit field accel1_val = (reg.raw_value >> 4) & 0x0001 accel1_enum = reg.find_field_by(name='ACCEL1').find_enum_entry_by(value=accel1_val) # find value for GYRO1 bit field gyro1_val = (reg.raw_value >> 3) & 0x0001 gyro1_enum = reg.find_field_by(name='GYRO1').find_enum_entry_by(value=gyro1_val) # find value for GYRO2 bit field gyro2_val = (reg.raw_value >> 2) & 0x0001 gyro2_enum = reg.find_field_by(name='GYRO2').find_enum_entry_by(value=gyro2_val) # find value for MAG1 bit field mag1_val = (reg.raw_value >> 1) & 0x0001 mag1_enum = reg.find_field_by(name='MAG1').find_enum_entry_by(value=mag1_val) # find value for MAG2 bit field mag2_val = (reg.raw_value >> 0) & 0x0001 mag2_enum = reg.find_field_by(name='MAG2').find_enum_entry_by(value=mag2_val) return reg, ovf_enum, acc1_n_enum, mag1_n_enum, mag2_n_enum, accel1_enum, gyro1_enum, gyro2_enum, mag1_enum, mag2_enum
def dreg_health(self): """ The health register reports the current status of the sensors on the board. Monitoring the health register is the easiest way to watch for other problems that could affect the behavior of the board, status of the sensors. The analogous to the health register, the status of the GPS signal can be monitored in the DREG_GPS_HEALTH Payload structure: [8] : OVF -- Overflow bit. This bit is set if the board is attempting to transmit data over the serial port faster than is allowed given the baud-rate. If this bit is set, reduce broadcast rates in the COM_RATES registers. [7] : ACC1_N -- This bit is set if the sensor detects that the norm of the accelerometer measurement is too far away from 1G to be used (i.e. during aggressive acceleration or high vibration). [6] : MAG1_N -- This bit is set if the sensor detects that the norm of the magnetometer measurement for the magnetometer 1 is too far away from 1.0 to be trusted. Usually indicates bad calibration, local field distortions, or both. [5] : MAG2_N -- This bit is set if the sensor detects that the norm of the magnetometer measurement for the magnetometer 2 is too far away from 1.0 to be trusted. Usually indicates bad calibration, local field distortions, or both. [4] : ACCEL1 -- This bit will be set if the accelerometer 1 fails to initialize on startup. [3] : GYRO1 -- This bit will be set if the rate gyro 1 fails to initialize on startup. [2] : GYRO2 -- This bit will be set if the rate gyro 2 fails to initialize on startup. [1] : MAG1 -- This bit will be set if the magnetometer 1 fails to initialize on startup. [0] : MAG2 -- This bit will be set if the magnetometer 2 fails to initialize on startup. :return: OVF as bitField; ACC1_N as bitField; MAG1_N as bitField; MAG2_N as bitField; ACCEL1 as bitField; GYRO1 as bitField; GYRO2 as bitField; MAG1 as bitField; MAG2 as bitField; """ addr = 0x55 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_HEALTH') reg.raw_value, = struct.unpack('>I', payload[0:4]) # find value for OVF bit field ovf_val = (reg.raw_value >> 8) & 0x0001 ovf_enum = reg.find_field_by(name='OVF').find_enum_entry_by(value=ovf_val) # find value for ACC1_N bit field acc1_n_val = (reg.raw_value >> 7) & 0x0001 acc1_n_enum = reg.find_field_by(name='ACC1_N').find_enum_entry_by(value=acc1_n_val) # find value for MAG1_N bit field mag1_n_val = (reg.raw_value >> 6) & 0x0001 mag1_n_enum = reg.find_field_by(name='MAG1_N').find_enum_entry_by(value=mag1_n_val) # find value for MAG2_N bit field mag2_n_val = (reg.raw_value >> 5) & 0x0001 mag2_n_enum = reg.find_field_by(name='MAG2_N').find_enum_entry_by(value=mag2_n_val) # find value for ACCEL1 bit field accel1_val = (reg.raw_value >> 4) & 0x0001 accel1_enum = reg.find_field_by(name='ACCEL1').find_enum_entry_by(value=accel1_val) # find value for GYRO1 bit field gyro1_val = (reg.raw_value >> 3) & 0x0001 gyro1_enum = reg.find_field_by(name='GYRO1').find_enum_entry_by(value=gyro1_val) # find value for GYRO2 bit field gyro2_val = (reg.raw_value >> 2) & 0x0001 gyro2_enum = reg.find_field_by(name='GYRO2').find_enum_entry_by(value=gyro2_val) # find value for MAG1 bit field mag1_val = (reg.raw_value >> 1) & 0x0001 mag1_enum = reg.find_field_by(name='MAG1').find_enum_entry_by(value=mag1_val) # find value for MAG2 bit field mag2_val = (reg.raw_value >> 0) & 0x0001 mag2_enum = reg.find_field_by(name='MAG2').find_enum_entry_by(value=mag2_val) return reg, ovf_enum, acc1_n_enum, mag1_n_enum, mag2_n_enum, accel1_enum, gyro1_enum, gyro2_enum, mag1_enum, mag2_enum
Python
def dreg_gyro_1_raw_xy(self): """ Contains raw X and Y axis rate gyro 1 data. Payload structure: [31:16] : GYRO_1_RAW_X -- Gyro X (2s complement 16-bit integer) [15:0] : GYRO_1_RAW_Y -- Gyro Y (2s complement 16-bit integer) :return: GYRO_1_RAW_X as int16_t; GYRO_1_RAW_Y as int16_t; """ addr = 0x56 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) gyro_1_raw_x, gyro_1_raw_y = struct.unpack('>hh', payload[0:4]) return reg, gyro_1_raw_x, gyro_1_raw_y
def dreg_gyro_1_raw_xy(self): """ Contains raw X and Y axis rate gyro 1 data. Payload structure: [31:16] : GYRO_1_RAW_X -- Gyro X (2s complement 16-bit integer) [15:0] : GYRO_1_RAW_Y -- Gyro Y (2s complement 16-bit integer) :return: GYRO_1_RAW_X as int16_t; GYRO_1_RAW_Y as int16_t; """ addr = 0x56 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) gyro_1_raw_x, gyro_1_raw_y = struct.unpack('>hh', payload[0:4]) return reg, gyro_1_raw_x, gyro_1_raw_y
Python
def dreg_gyro_2_raw_xy(self): """ Contains raw X and Y axis rate gyro 2 data. Payload structure: [31:16] : GYRO_2_RAW_X -- Gyro X (2s complement 16-bit integer) [15:0] : GYRO_2_RAW_Y -- Gyro Y (2s complement 16-bit integer) :return: GYRO_2_RAW_X as int16_t; GYRO_2_RAW_Y as int16_t; """ addr = 0x59 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) gyro_2_raw_x, gyro_2_raw_y = struct.unpack('>hh', payload[0:4]) return reg, gyro_2_raw_x, gyro_2_raw_y
def dreg_gyro_2_raw_xy(self): """ Contains raw X and Y axis rate gyro 2 data. Payload structure: [31:16] : GYRO_2_RAW_X -- Gyro X (2s complement 16-bit integer) [15:0] : GYRO_2_RAW_Y -- Gyro Y (2s complement 16-bit integer) :return: GYRO_2_RAW_X as int16_t; GYRO_2_RAW_Y as int16_t; """ addr = 0x59 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) gyro_2_raw_x, gyro_2_raw_y = struct.unpack('>hh', payload[0:4]) return reg, gyro_2_raw_x, gyro_2_raw_y
Python
def dreg_accel_1_raw_xy(self): """ Contains raw X and Y axis accelerometer 1 data. Payload structure: [31:16] : ACCEL_1_RAW_X -- Accel X (2s complement 16-bit integer) [15:0] : ACCEL_1_RAW_Y -- Accel Y (2s complement 16-bit integer) :return: ACCEL_1_RAW_X as int16_t; ACCEL_1_RAW_Y as int16_t; """ addr = 0x5C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) accel_1_raw_x, accel_1_raw_y = struct.unpack('>hh', payload[0:4]) return reg, accel_1_raw_x, accel_1_raw_y
def dreg_accel_1_raw_xy(self): """ Contains raw X and Y axis accelerometer 1 data. Payload structure: [31:16] : ACCEL_1_RAW_X -- Accel X (2s complement 16-bit integer) [15:0] : ACCEL_1_RAW_Y -- Accel Y (2s complement 16-bit integer) :return: ACCEL_1_RAW_X as int16_t; ACCEL_1_RAW_Y as int16_t; """ addr = 0x5C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) accel_1_raw_x, accel_1_raw_y = struct.unpack('>hh', payload[0:4]) return reg, accel_1_raw_x, accel_1_raw_y
Python
def dreg_accel_1_raw_time(self): """ Contains time at which the last raw data sample for the accelerometer 1 was acquired. Payload structure: [31:0] : ACCEL_1_RAW_TIME -- 32-bit IEEE Floating Point Value :return: ACCEL_1_RAW_TIME as float; """ addr = 0x5E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_raw_time, = struct.unpack('>f', payload[0:4]) return reg, accel_1_raw_time,
def dreg_accel_1_raw_time(self): """ Contains time at which the last raw data sample for the accelerometer 1 was acquired. Payload structure: [31:0] : ACCEL_1_RAW_TIME -- 32-bit IEEE Floating Point Value :return: ACCEL_1_RAW_TIME as float; """ addr = 0x5E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_raw_time, = struct.unpack('>f', payload[0:4]) return reg, accel_1_raw_time,
Python
def dreg_mag_1_raw_time(self): """ Contains time at which the last magnetometer data from the magnetometer 1 was acquired. Payload structure: [31:0] : MAG_1_RAW_TIME -- 32-bit IEEE Floating Point Value :return: MAG_1_RAW_TIME as float; """ addr = 0x62 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_raw_time, = struct.unpack('>f', payload[0:4]) return reg, mag_1_raw_time,
def dreg_mag_1_raw_time(self): """ Contains time at which the last magnetometer data from the magnetometer 1 was acquired. Payload structure: [31:0] : MAG_1_RAW_TIME -- 32-bit IEEE Floating Point Value :return: MAG_1_RAW_TIME as float; """ addr = 0x62 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_raw_time, = struct.unpack('>f', payload[0:4]) return reg, mag_1_raw_time,
Python
def dreg_mag_2_raw_xy(self): """ Contains raw X and Y axis magnetometer 2 data. Payload structure: [31:16] : MAG_2_RAW_X -- Magnetometer X (2s complement 16-bit integer) [15:0] : MAG_2_RAW_Y -- Magnetometer Y (2s complement 16-bit integer) :return: MAG_2_RAW_X as int16_t; MAG_2_RAW_Y as int16_t; """ addr = 0x63 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) mag_2_raw_x, mag_2_raw_y = struct.unpack('>hh', payload[0:4]) return reg, mag_2_raw_x, mag_2_raw_y
def dreg_mag_2_raw_xy(self): """ Contains raw X and Y axis magnetometer 2 data. Payload structure: [31:16] : MAG_2_RAW_X -- Magnetometer X (2s complement 16-bit integer) [15:0] : MAG_2_RAW_Y -- Magnetometer Y (2s complement 16-bit integer) :return: MAG_2_RAW_X as int16_t; MAG_2_RAW_Y as int16_t; """ addr = 0x63 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_RAW_XY') reg.raw_value, = struct.unpack('>I', payload[0:4]) mag_2_raw_x, mag_2_raw_y = struct.unpack('>hh', payload[0:4]) return reg, mag_2_raw_x, mag_2_raw_y
Python
def dreg_mag_2_raw_time(self): """ Contains time at which the last magnetometer data from the magnetometer 2 was acquired. Payload structure: [31:0] : MAG_2_RAW_TIME -- 32-bit IEEE Floating Point Value :return: MAG_2_RAW_TIME as float; """ addr = 0x65 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_raw_time, = struct.unpack('>f', payload[0:4]) return reg, mag_2_raw_time,
def dreg_mag_2_raw_time(self): """ Contains time at which the last magnetometer data from the magnetometer 2 was acquired. Payload structure: [31:0] : MAG_2_RAW_TIME -- 32-bit IEEE Floating Point Value :return: MAG_2_RAW_TIME as float; """ addr = 0x65 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_RAW_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_raw_time, = struct.unpack('>f', payload[0:4]) return reg, mag_2_raw_time,
Python
def dreg_temperature(self): """ Contains the temperature output of the onboard temperature sensor. Payload structure: [31:0] : TEMPERATURE -- Temperature in degrees Celcius (32-bit IEEE Floating Point) :return: TEMPERATURE as float; """ addr = 0x66 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_TEMPERATURE') reg.raw_value, = struct.unpack('>f', payload[0:4]) temperature, = struct.unpack('>f', payload[0:4]) return reg, temperature,
def dreg_temperature(self): """ Contains the temperature output of the onboard temperature sensor. Payload structure: [31:0] : TEMPERATURE -- Temperature in degrees Celcius (32-bit IEEE Floating Point) :return: TEMPERATURE as float; """ addr = 0x66 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_TEMPERATURE') reg.raw_value, = struct.unpack('>f', payload[0:4]) temperature, = struct.unpack('>f', payload[0:4]) return reg, temperature,
Python
def dreg_temperature_time(self): """ Contains time at which the last temperature was acquired. Payload structure: [31:0] : TEMPERATURE_TIME -- 32-bit IEEE Floating Point Value :return: TEMPERATURE_TIME as float; """ addr = 0x67 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_TEMPERATURE_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) temperature_time, = struct.unpack('>f', payload[0:4]) return reg, temperature_time,
def dreg_temperature_time(self): """ Contains time at which the last temperature was acquired. Payload structure: [31:0] : TEMPERATURE_TIME -- 32-bit IEEE Floating Point Value :return: TEMPERATURE_TIME as float; """ addr = 0x67 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_TEMPERATURE_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) temperature_time, = struct.unpack('>f', payload[0:4]) return reg, temperature_time,
Python
def dreg_gyro_1_proc_x(self): """ Contains the actual measured angular rate from the gyro 1 for the x axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_X -- Gyro X in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_X as float; """ addr = 0x68 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_x,
def dreg_gyro_1_proc_x(self): """ Contains the actual measured angular rate from the gyro 1 for the x axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_X -- Gyro X in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_X as float; """ addr = 0x68 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_x,
Python
def dreg_gyro_1_proc_y(self): """ Contains the actual measured angular rate from the gyro 1 for the y axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_Y -- Gyro Y in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_Y as float; """ addr = 0x69 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_y,
def dreg_gyro_1_proc_y(self): """ Contains the actual measured angular rate from the gyro 1 for the y axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_Y -- Gyro Y in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_Y as float; """ addr = 0x69 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_y,
Python
def dreg_gyro_1_proc_z(self): """ Contains the actual measured angular rate from the gyro 1 for the z axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_Z -- Gyro Z in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_Z as float; """ addr = 0x6A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_z,
def dreg_gyro_1_proc_z(self): """ Contains the actual measured angular rate from the gyro 1 for the z axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_1_PROC_Z -- Gyro Z in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_1_PROC_Z as float; """ addr = 0x6A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_1_proc_z,
Python
def dreg_gyro_2_proc_x(self): """ Contains the actual measured angular rate from the gyro 2 for the x axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_X -- Gyro X in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_X as float; """ addr = 0x6C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_x,
def dreg_gyro_2_proc_x(self): """ Contains the actual measured angular rate from the gyro 2 for the x axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_X -- Gyro X in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_X as float; """ addr = 0x6C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_x, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_x,
Python
def dreg_gyro_2_proc_y(self): """ Contains the actual measured angular rate from the gyro 2 for the y axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_Y -- Gyro Y in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_Y as float; """ addr = 0x6D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_y,
def dreg_gyro_2_proc_y(self): """ Contains the actual measured angular rate from the gyro 2 for the y axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_Y -- Gyro Y in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_Y as float; """ addr = 0x6D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_y, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_y,
Python
def dreg_gyro_2_proc_z(self): """ Contains the actual measured angular rate from the gyro 2 for the z axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_Z -- Gyro Z in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_Z as float; """ addr = 0x6E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_z,
def dreg_gyro_2_proc_z(self): """ Contains the actual measured angular rate from the gyro 2 for the z axis in degrees/sec after calibration has been applied. Payload structure: [31:0] : GYRO_2_PROC_Z -- Gyro Z in degrees / sec (32-bit IEEE Floating Point Value) :return: GYRO_2_PROC_Z as float; """ addr = 0x6E ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_GYRO_2_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) gyro_2_proc_z, = struct.unpack('>f', payload[0:4]) return reg, gyro_2_proc_z,
Python
def dreg_accel_1_proc_x(self): """ Contains the actual measured acceleration from the accelerometer 1 for the x axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_X -- Acceleration X in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_X as float; """ addr = 0x70 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_x,
def dreg_accel_1_proc_x(self): """ Contains the actual measured acceleration from the accelerometer 1 for the x axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_X -- Acceleration X in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_X as float; """ addr = 0x70 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_x,
Python
def dreg_accel_1_proc_y(self): """ Contains the actual measured acceleration from the accelerometer 1 for the y axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_Y -- Acceleration Y in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_Y as float; """ addr = 0x71 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_y,
def dreg_accel_1_proc_y(self): """ Contains the actual measured acceleration from the accelerometer 1 for the y axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_Y -- Acceleration Y in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_Y as float; """ addr = 0x71 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_y,
Python
def dreg_accel_1_proc_z(self): """ Contains the actual measured acceleration from the accelerometer 1 for the z axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_Z -- Acceleration Z in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_Z as float; """ addr = 0x72 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_z,
def dreg_accel_1_proc_z(self): """ Contains the actual measured acceleration from the accelerometer 1 for the z axis in m/s2 after calibration has been applied. Payload structure: [31:0] : ACCEL_1_PROC_Z -- Acceleration Z in m/s2 (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_Z as float; """ addr = 0x72 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_z,
Python
def dreg_accel_1_proc_time(self): """ Contains the time at which the last acceleration data from the accelerometer 1 was measured. Payload structure: [31:0] : ACCEL_1_PROC_TIME -- Accelerometer 1 time stamp (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_TIME as float; """ addr = 0x73 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_time, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_time,
def dreg_accel_1_proc_time(self): """ Contains the time at which the last acceleration data from the accelerometer 1 was measured. Payload structure: [31:0] : ACCEL_1_PROC_TIME -- Accelerometer 1 time stamp (32-bit IEEE Floating Point Value) :return: ACCEL_1_PROC_TIME as float; """ addr = 0x73 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_ACCEL_1_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) accel_1_proc_time, = struct.unpack('>f', payload[0:4]) return reg, accel_1_proc_time,
Python
def dreg_mag_1_proc_x(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the x axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_X -- Magnetometer X in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_X as float; """ addr = 0x74 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_x,
def dreg_mag_1_proc_x(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the x axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_X -- Magnetometer X in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_X as float; """ addr = 0x74 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_x, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_x,
Python
def dreg_mag_1_proc_y(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the y axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_Y -- Magnetometer Y in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_Y as float; """ addr = 0x75 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_y,
def dreg_mag_1_proc_y(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the y axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_Y -- Magnetometer Y in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_Y as float; """ addr = 0x75 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_y, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_y,
Python
def dreg_mag_1_proc_z(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the z axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_Z -- Magnetometer Z in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_Z as float; """ addr = 0x76 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_z,
def dreg_mag_1_proc_z(self): """ Contains the actual measured magnetic field from the magnetometer 1 for the z axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_1_PROC_Z -- Magnetometer Z in mT (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_Z as float; """ addr = 0x76 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_z, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_z,
Python
def dreg_mag_1_norm(self): """ Contains the L2-norm (magnetic norm) for the measured magnetic field from the magnetometer 1 computed over the calibrated values. Payload structure: [31:0] : MAG_1_NORM -- Magnetic norm (32-bit IEEE Floating Point Value) :return: MAG_1_NORM as float; """ addr = 0x77 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_NORM') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_norm, = struct.unpack('>f', payload[0:4]) return reg, mag_1_norm,
def dreg_mag_1_norm(self): """ Contains the L2-norm (magnetic norm) for the measured magnetic field from the magnetometer 1 computed over the calibrated values. Payload structure: [31:0] : MAG_1_NORM -- Magnetic norm (32-bit IEEE Floating Point Value) :return: MAG_1_NORM as float; """ addr = 0x77 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_NORM') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_norm, = struct.unpack('>f', payload[0:4]) return reg, mag_1_norm,
Python
def dreg_mag_1_proc_time(self): """ Contains the time stamp at which the calibrated magnetometer 1 data was acquired. Payload structure: [31:0] : MAG_1_PROC_TIME -- Magnetometer 1 time stamp (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_TIME as float; """ addr = 0x78 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_time, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_time,
def dreg_mag_1_proc_time(self): """ Contains the time stamp at which the calibrated magnetometer 1 data was acquired. Payload structure: [31:0] : MAG_1_PROC_TIME -- Magnetometer 1 time stamp (32-bit IEEE Floating Point Value) :return: MAG_1_PROC_TIME as float; """ addr = 0x78 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_1_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_1_proc_time, = struct.unpack('>f', payload[0:4]) return reg, mag_1_proc_time,
Python
def dreg_mag_2_proc_x(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the x axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_X -- Magnetometer X in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_X as float; """ addr = 0x79 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_x, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_x,
def dreg_mag_2_proc_x(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the x axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_X -- Magnetometer X in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_X as float; """ addr = 0x79 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_X') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_x, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_x,
Python
def dreg_mag_2_proc_y(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the y axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_Y -- Magnetometer Y in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_Y as float; """ addr = 0x7A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_y, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_y,
def dreg_mag_2_proc_y(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the y axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_Y -- Magnetometer Y in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_Y as float; """ addr = 0x7A ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_Y') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_y, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_y,
Python
def dreg_mag_2_proc_z(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the z axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_Z -- Magnetometer Z in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_Z as float; """ addr = 0x7B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_z, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_z,
def dreg_mag_2_proc_z(self): """ Contains the actual measured magnetic field from the magnetometer 2 for the z axis in mT after calibration has been applied. Payload structure: [31:0] : MAG_2_PROC_Z -- Magnetometer Z in mT (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_Z as float; """ addr = 0x7B ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_Z') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_z, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_z,
Python
def dreg_mag_2_norm(self): """ Contains the L2-norm (magnetic norm) for the measured magnetic field from the magnetometer 2 computed over the calibrated values. Payload structure: [31:0] : MAG_2_NORM -- Magnetic norm (32-bit IEEE Floating Point Value) :return: MAG_2_NORM as float; """ addr = 0x7C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_NORM') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_norm, = struct.unpack('>f', payload[0:4]) return reg, mag_2_norm,
def dreg_mag_2_norm(self): """ Contains the L2-norm (magnetic norm) for the measured magnetic field from the magnetometer 2 computed over the calibrated values. Payload structure: [31:0] : MAG_2_NORM -- Magnetic norm (32-bit IEEE Floating Point Value) :return: MAG_2_NORM as float; """ addr = 0x7C ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_NORM') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_norm, = struct.unpack('>f', payload[0:4]) return reg, mag_2_norm,
Python
def dreg_mag_2_proc_time(self): """ Contains the time stamp at which the calibrated magnetometer 2 data was acquired. Payload structure: [31:0] : MAG_2_PROC_TIME -- Magnetometer 2 time stamp (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_TIME as float; """ addr = 0x7D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_time, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_time,
def dreg_mag_2_proc_time(self): """ Contains the time stamp at which the calibrated magnetometer 2 data was acquired. Payload structure: [31:0] : MAG_2_PROC_TIME -- Magnetometer 2 time stamp (32-bit IEEE Floating Point Value) :return: MAG_2_PROC_TIME as float; """ addr = 0x7D ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_MAG_2_PROC_TIME') reg.raw_value, = struct.unpack('>f', payload[0:4]) mag_2_proc_time, = struct.unpack('>f', payload[0:4]) return reg, mag_2_proc_time,
Python
def dreg_position_north(self): """ Contains the measured north position in meters from the latitude specified in CREG_HOME_NORTH. Payload structure: [31:0] : POSITION_NORTH -- North Position (32-bit IEEE Floating Point Value) :return: POSITION_NORTH as float; """ addr = 0x86 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_POSITION_NORTH') reg.raw_value, = struct.unpack('>f', payload[0:4]) position_north, = struct.unpack('>f', payload[0:4]) return reg, position_north,
def dreg_position_north(self): """ Contains the measured north position in meters from the latitude specified in CREG_HOME_NORTH. Payload structure: [31:0] : POSITION_NORTH -- North Position (32-bit IEEE Floating Point Value) :return: POSITION_NORTH as float; """ addr = 0x86 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_POSITION_NORTH') reg.raw_value, = struct.unpack('>f', payload[0:4]) position_north, = struct.unpack('>f', payload[0:4]) return reg, position_north,
Python
def dreg_position_east(self): """ Contains the measured east position in meters from the longitude specified in CREG_HOME_EAST. Payload structure: [31:0] : POSITION_EAST -- East Position (32-bit IEEE Floating Point Value) :return: POSITION_EAST as float; """ addr = 0x87 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_POSITION_EAST') reg.raw_value, = struct.unpack('>f', payload[0:4]) position_east, = struct.unpack('>f', payload[0:4]) return reg, position_east,
def dreg_position_east(self): """ Contains the measured east position in meters from the longitude specified in CREG_HOME_EAST. Payload structure: [31:0] : POSITION_EAST -- East Position (32-bit IEEE Floating Point Value) :return: POSITION_EAST as float; """ addr = 0x87 ok, payload = self.read_register(addr) if ok: reg = self.svd_parser.find_register_by(name='DREG_POSITION_EAST') reg.raw_value, = struct.unpack('>f', payload[0:4]) position_east, = struct.unpack('>f', payload[0:4]) return reg, position_east,
Python
def serve_autodetect_script(target_dir='./'): """ Copies RSL autodetect script in target directory :param target_dir: directory to copy autodetect script to :return: 0 -- execution successful """ autodetect_script = 'rsl_autodetect.py' src_path = Path(__file__).parent target_dir = Path(target_dir) autodetect_script_abspath = src_path / autodetect_script copy(autodetect_script_abspath, target_dir) # make copied file executable copied_file = target_dir / autodetect_script st = os.stat(copied_file) os.chmod(copied_file, st.st_mode | stat.S_IEXEC)
def serve_autodetect_script(target_dir='./'): """ Copies RSL autodetect script in target directory :param target_dir: directory to copy autodetect script to :return: 0 -- execution successful """ autodetect_script = 'rsl_autodetect.py' src_path = Path(__file__).parent target_dir = Path(target_dir) autodetect_script_abspath = src_path / autodetect_script copy(autodetect_script_abspath, target_dir) # make copied file executable copied_file = target_dir / autodetect_script st = os.stat(copied_file) os.chmod(copied_file, st.st_mode | stat.S_IEXEC)
Python
def open_gui_plot(self, list_sel, dropdown_sel): """ Function to open TopLevel GUI Plot with parameters :param list_sel: List of selected keywords :param dropdown_sel: Selected dropdown Item "timeframe" """ form_plot = gui_plot.GUIPlot( self, interest( list_sel, dropdown_sel ), list_sel ) form_plot.grab_set()
def open_gui_plot(self, list_sel, dropdown_sel): """ Function to open TopLevel GUI Plot with parameters :param list_sel: List of selected keywords :param dropdown_sel: Selected dropdown Item "timeframe" """ form_plot = gui_plot.GUIPlot( self, interest( list_sel, dropdown_sel ), list_sel ) form_plot.grab_set()
Python
def read(text): """ Processes the text and separates the sentences from each other. Also detect language of the text. :param text: Inserted Text from Textbox :return sentences: List of separated sentences :return language: Return language in ISO 639 short format for usage of stopwords """ language = detectlanguage(text, True) sentences_split = text.split(". ") sentences = [] for sentence in sentences_split: sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" ")) sentences.pop() return sentences, language
def read(text): """ Processes the text and separates the sentences from each other. Also detect language of the text. :param text: Inserted Text from Textbox :return sentences: List of separated sentences :return language: Return language in ISO 639 short format for usage of stopwords """ language = detectlanguage(text, True) sentences_split = text.split(". ") sentences = [] for sentence in sentences_split: sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" ")) sentences.pop() return sentences, language
Python
def sentence_similarity(sentence1, sentence2, stop_words=None): """ Calculate the similarity of two sentences :param sentence1: Sentence 1 which is compared with sentence 2 :param sentence2: Sentence 2 which is compared with sentence 1 :param stop_words: List of words which are very common but don't provide useful information for text analysis :return cosine_distance: Return calculated cosine similarity of two vectors (sentences) """ if stop_words is None: stop_words = [] sentence1 = [w.lower() for w in sentence1] # Each word of sentence is parsed. To generalized use lower cases sentence2 = [w.lower() for w in sentence2] all_words = list(set(sentence1+sentence2)) vector1 = [0] * len(all_words) # Create vectors for sentence 1 and 2 vector2 = [0] * len(all_words) for w in sentence1: if w in stop_words: continue vector1[all_words.index(w)] += 1 for w in sentence2: if w in stop_words: continue vector2[all_words.index(w)] += 1 return 1-cosine_distance(vector1, vector2)
def sentence_similarity(sentence1, sentence2, stop_words=None): """ Calculate the similarity of two sentences :param sentence1: Sentence 1 which is compared with sentence 2 :param sentence2: Sentence 2 which is compared with sentence 1 :param stop_words: List of words which are very common but don't provide useful information for text analysis :return cosine_distance: Return calculated cosine similarity of two vectors (sentences) """ if stop_words is None: stop_words = [] sentence1 = [w.lower() for w in sentence1] # Each word of sentence is parsed. To generalized use lower cases sentence2 = [w.lower() for w in sentence2] all_words = list(set(sentence1+sentence2)) vector1 = [0] * len(all_words) # Create vectors for sentence 1 and 2 vector2 = [0] * len(all_words) for w in sentence1: if w in stop_words: continue vector1[all_words.index(w)] += 1 for w in sentence2: if w in stop_words: continue vector2[all_words.index(w)] += 1 return 1-cosine_distance(vector1, vector2)
Python
def generate_sim_matrix(sentences, stop_words=None): """ Generate the similarity matrix of a text :param sentences: Get list of sentences of read-function :param stop_words: List of words which are very common but don't provide useful information for text analysis :return similarity_matrix: Return """ similarity_matrix = np.zeros((len(sentences), len(sentences))) # Create two-dimensional empty matrix for vector1 in range(len(sentences)): for vector2 in range(len(sentences)): if vector1 == vector2: continue similarity_matrix[vector1][vector2] = sentence_similarity( sentences[vector1], sentences[vector2], stop_words ) return similarity_matrix
def generate_sim_matrix(sentences, stop_words=None): """ Generate the similarity matrix of a text :param sentences: Get list of sentences of read-function :param stop_words: List of words which are very common but don't provide useful information for text analysis :return similarity_matrix: Return """ similarity_matrix = np.zeros((len(sentences), len(sentences))) # Create two-dimensional empty matrix for vector1 in range(len(sentences)): for vector2 in range(len(sentences)): if vector1 == vector2: continue similarity_matrix[vector1][vector2] = sentence_similarity( sentences[vector1], sentences[vector2], stop_words ) return similarity_matrix
Python
def build_summary(text, top_n=5): """ Build summary with built functions to generate a similarity matrix and with networkx sentences are ranked. With ranked sentences are then used to create the summary with a sort algorithm. :param text: Inserted Text from textbox :param top_n: maximum length with standard value of 5 :return: summarized text as a list """ install_stopwords() summarized_text = [] sentences, language = read(text) stop_words = stopwords.words(language) similarity_matrix = generate_sim_matrix(sentences, stop_words) similarity_graph = nx.from_numpy_array(similarity_matrix) # Create graph from 2D Matrix ranks = nx.pagerank(similarity_graph) # Create ranking of the nodes in the graph ranked_sentence = sorted( # Sorting to get top sentences ( (ranks[i], sentences_id) for i, sentences_id in enumerate(sentences) ), reverse=True) # to get the top sentences for i in range(top_n): summarized_text.append(" ".join(ranked_sentence[i][1])) # Build summary of ranked sentences list return summarized_text
def build_summary(text, top_n=5): """ Build summary with built functions to generate a similarity matrix and with networkx sentences are ranked. With ranked sentences are then used to create the summary with a sort algorithm. :param text: Inserted Text from textbox :param top_n: maximum length with standard value of 5 :return: summarized text as a list """ install_stopwords() summarized_text = [] sentences, language = read(text) stop_words = stopwords.words(language) similarity_matrix = generate_sim_matrix(sentences, stop_words) similarity_graph = nx.from_numpy_array(similarity_matrix) # Create graph from 2D Matrix ranks = nx.pagerank(similarity_graph) # Create ranking of the nodes in the graph ranked_sentence = sorted( # Sorting to get top sentences ( (ranks[i], sentences_id) for i, sentences_id in enumerate(sentences) ), reverse=True) # to get the top sentences for i in range(top_n): summarized_text.append(" ".join(ranked_sentence[i][1])) # Build summary of ranked sentences list return summarized_text
Python
def scrape(query, language): """ Web Scraping Function with BeautifulSoup as a Package :param query: Search Query -> Keyword which is searched on Google Scholar :param language: in which language? :return data: List of Dictionaries with search results """ # Header for POST-Call header = { "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } # Search parameter for POST-Call params = { "q": query, "hl": language, } html = requests.get("https://scholar.google.com/scholar", headers=header, params=params).text # HTML Post Query soup = BeautifulSoup(html, "lxml") # BeautifulSoup for web scraping # empty list data = [] # Container in which all the important information for result in soup.select('.gs_ri'): title = result.select_one('.gs_rt').text title_link = result.select_one('.gs_rt a')['href'] publication_info = result.select_one('.gs_a').text snippet = result.select_one('.gs_rs').text data.append({ 'title': title, 'publication_info': publication_info, 'snippet': snippet, 'title_link': title_link, }) return data
def scrape(query, language): """ Web Scraping Function with BeautifulSoup as a Package :param query: Search Query -> Keyword which is searched on Google Scholar :param language: in which language? :return data: List of Dictionaries with search results """ # Header for POST-Call header = { "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } # Search parameter for POST-Call params = { "q": query, "hl": language, } html = requests.get("https://scholar.google.com/scholar", headers=header, params=params).text # HTML Post Query soup = BeautifulSoup(html, "lxml") # BeautifulSoup for web scraping # empty list data = [] # Container in which all the important information for result in soup.select('.gs_ri'): title = result.select_one('.gs_rt').text title_link = result.select_one('.gs_rt a')['href'] publication_info = result.select_one('.gs_a').text snippet = result.select_one('.gs_rs').text data.append({ 'title': title, 'publication_info': publication_info, 'snippet': snippet, 'title_link': title_link, }) return data
Python
def install_stopwords(): """ Nltk Downloader is broken. There is a workaround to download the required "stopwords" package. This code disable the SSL Certificate Verification. Found solution on: https://github.com/gunthercox/ChatterBot/issues/930#issuecomment-322111087 """ try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context download("stopwords") # Adapted to download only the required package from nltk
def install_stopwords(): """ Nltk Downloader is broken. There is a workaround to download the required "stopwords" package. This code disable the SSL Certificate Verification. Found solution on: https://github.com/gunthercox/ChatterBot/issues/930#issuecomment-322111087 """ try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context download("stopwords") # Adapted to download only the required package from nltk
Python
def detectlanguage(text, short: bool): """ Automatic detection of the language + conversion from "de" to "German" using the packages Langdetect and ISO639. :param text: Inserted text from Textbox :param short: Should the recognised language be converted to ISO 639 format? :type short: Boolean: Yes or No :return: Returns language """ if short: # de to German language = iso639.to_name(detect(text)) else: language = detect(text) # de return language
def detectlanguage(text, short: bool): """ Automatic detection of the language + conversion from "de" to "German" using the packages Langdetect and ISO639. :param text: Inserted text from Textbox :param short: Should the recognised language be converted to ISO 639 format? :type short: Boolean: Yes or No :return: Returns language """ if short: # de to German language = iso639.to_name(detect(text)) else: language = detect(text) # de return language
Python
def extract_keywords(text, wordcount, duplication, max_keywords): """ Extract keywords from a given text and given parameter with :param text: inserted text from textbox :param wordcount: limit the word count of the extracted keyword, i.e. <= 3 :param duplication: limit the duplication of words in different keywords. 0.9 allows repetition of words in keywords :param max_keywords: determine the count of keywords which are extracted, i.e. <= 20 :return: list of tuples keywords with scores """ language = helpers.detectlanguage(text, False) extractor = yake.KeywordExtractor( lan=language, n=wordcount, dedupLim=duplication, top=max_keywords, features=None ) keywords = extractor.extract_keywords(text) keywords.sort(key=lambda a: a[1]) # Lower Score = the more relevant. For this: Sorting list of tuples of Item 1 return keywords
def extract_keywords(text, wordcount, duplication, max_keywords): """ Extract keywords from a given text and given parameter with :param text: inserted text from textbox :param wordcount: limit the word count of the extracted keyword, i.e. <= 3 :param duplication: limit the duplication of words in different keywords. 0.9 allows repetition of words in keywords :param max_keywords: determine the count of keywords which are extracted, i.e. <= 20 :return: list of tuples keywords with scores """ language = helpers.detectlanguage(text, False) extractor = yake.KeywordExtractor( lan=language, n=wordcount, dedupLim=duplication, top=max_keywords, features=None ) keywords = extractor.extract_keywords(text) keywords.sort(key=lambda a: a[1]) # Lower Score = the more relevant. For this: Sorting list of tuples of Item 1 return keywords
Python
def related_keywords(keyword): """ Find related keywords with given keyword via Google Trend API :param keyword: Selected Keyword from listbox :return list_top_kw: List of top keywords from Google API Call """ trend = TrendReq() keyword = [f"{keyword}"] # Necessary API String Format trend.build_payload(kw_list=keyword) # Google Trend API Call with given parameter related_kw = trend.related_topics() related_kw.values() data_top_kw = list(related_kw.values())[0]["top"] list_top_kw = [] for i in range(len(data_top_kw.values)): list_top_kw.append(data_top_kw.values[i][5]) return list_top_kw
def related_keywords(keyword): """ Find related keywords with given keyword via Google Trend API :param keyword: Selected Keyword from listbox :return list_top_kw: List of top keywords from Google API Call """ trend = TrendReq() keyword = [f"{keyword}"] # Necessary API String Format trend.build_payload(kw_list=keyword) # Google Trend API Call with given parameter related_kw = trend.related_topics() related_kw.values() data_top_kw = list(related_kw.values())[0]["top"] list_top_kw = [] for i in range(len(data_top_kw.values)): list_top_kw.append(data_top_kw.values[i][5]) return list_top_kw
Python
def interest_of_time(keyword_list, timeframe): """ Get dataset of relative interest of selected keywords :param keyword_list: Selected keywords (up to 5) from second listbox :param timeframe: dropdown menu Item with given timeframe for get time specific data :return data: Dataframe with y = Date; x = Keyword relative interest to top keyword """ trend = TrendReq() keywords = keyword_list trend.build_payload(kw_list=keywords, cat=None, timeframe=timeframe, geo="") data = trend.interest_over_time() return data
def interest_of_time(keyword_list, timeframe): """ Get dataset of relative interest of selected keywords :param keyword_list: Selected keywords (up to 5) from second listbox :param timeframe: dropdown menu Item with given timeframe for get time specific data :return data: Dataframe with y = Date; x = Keyword relative interest to top keyword """ trend = TrendReq() keywords = keyword_list trend.build_payload(kw_list=keywords, cat=None, timeframe=timeframe, geo="") data = trend.interest_over_time() return data
Python
def open_gui_summarize(self): """ Function to open TopLevel GUI Summarize """ form_summarize = gui_summarize.GUISummarize(self) form_summarize.grab_set()
def open_gui_summarize(self): """ Function to open TopLevel GUI Summarize """ form_summarize = gui_summarize.GUISummarize(self) form_summarize.grab_set()
Python
def open_gui_analyze(self): """ Function to open TopLevel GUI Analyze """ form_analyze = gui_analyze.GUIAnalyze(self) form_analyze.grab_set()
def open_gui_analyze(self): """ Function to open TopLevel GUI Analyze """ form_analyze = gui_analyze.GUIAnalyze(self) form_analyze.grab_set()
Python
def open_gui_research(self): """ Function to open TopLevel GUI Research """ form_research = gui_research.GUIResearch(self) form_research.grab_set()
def open_gui_research(self): """ Function to open TopLevel GUI Research """ form_research = gui_research.GUIResearch(self) form_research.grab_set()
Python
def plot(self, data, keywords): """ Function to plot data: y: Date, x: keywords with relative occurrence to top related keyword. :param data: DataFrame from :function: `~researchtool.keywordanalytics.interest_of_time` :param keywords: list of selected related keywords """ figure = Figure() plt = figure.add_subplot(1, 1, 1) for keyword in keywords: plt.plot(data.index, data[keyword], label=keyword) plt.legend() canvas = FigureCanvasTkAgg(figure, master=self) canvas.draw() canvas.get_tk_widget().grid(row=0, column=0)
def plot(self, data, keywords): """ Function to plot data: y: Date, x: keywords with relative occurrence to top related keyword. :param data: DataFrame from :function: `~researchtool.keywordanalytics.interest_of_time` :param keywords: list of selected related keywords """ figure = Figure() plt = figure.add_subplot(1, 1, 1) for keyword in keywords: plt.plot(data.index, data[keyword], label=keyword) plt.legend() canvas = FigureCanvasTkAgg(figure, master=self) canvas.draw() canvas.get_tk_widget().grid(row=0, column=0)