Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Sourcery refactored master branch #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/eegclassify/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ def _row_stats(s: pd.Series):
def _clean_signal_quality(
df: pd.DataFrame, max_uv_abs: float = None, max_std: float = None
) -> pd.DataFrame:
bads = []
for i, row in df.iterrows():
# print(_row_stats(row))
if not _check_row_signal_quality(row, max_uv_abs, max_std):
bads.append(i)
bads = [
i
for i, row in df.iterrows()
if not _check_row_signal_quality(row, max_uv_abs, max_std)
]
Comment on lines -115 to +119
Copy link
Author

Choose a reason for hiding this comment

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

Function _clean_signal_quality refactored with the following changes:

This removes the following comments ( why? ):

# print(_row_stats(row))


logger.warning(f"Dropping {len(bads)} bad rows due to bad signal quality")
return df.drop(bads)
Expand Down
2 changes: 1 addition & 1 deletion src/eegclassify/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def signal_ndarray(df: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
X = np.zeros((n_trials, n_channels, n_samples))
y = np.empty((n_trials))

catmap = dict(((cls, i) for i, cls in enumerate(df["class"].cat.categories)))
catmap = {cls: i for i, cls in enumerate(df["class"].cat.categories)}
Copy link
Author

Choose a reason for hiding this comment

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

Function signal_ndarray refactored with the following changes:

# pprint(catmap)

i_t = 0
Expand Down
6 changes: 2 additions & 4 deletions src/eegclassify/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def test_unison_shuffled_copies():
b = np.array(range(1, 11))
c = np.array(range(2, 12))
sa, sb, sc = unison_shuffled_copies(a, b, c)
assert all([v1 == v2 - 1 == v3 - 2 for v1, v2, v3 in zip(sa, sb, sc)])
assert all(v1 == v2 - 1 == v3 - 2 for v1, v2, v3 in zip(sa, sb, sc))
Copy link
Author

Choose a reason for hiding this comment

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

Function test_unison_shuffled_copies refactored with the following changes:

assert all(a == np.array(range(10))), "input array was mutated"
assert all(c == np.array(range(2, 12))), "input array was mutated"

Expand Down Expand Up @@ -114,10 +114,8 @@ def aggregate_windows_to_epochs(
map(lambda v: map_cls[v], predicted[test][i_start : i_stop + 1])
)
vote = sum(y_preds) / len(y_preds)
votes.append(vote > 0.5)
else:
# Use the mean probability
vote = np.mean(predicted_proba[test][i_start : i_stop + 1, 1])
votes.append(vote > 0.5)

votes.append(vote > 0.5)
Comment on lines -117 to +120
Copy link
Author

Choose a reason for hiding this comment

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

Function aggregate_windows_to_epochs refactored with the following changes:

return np.array(ys_epoch), np.array(votes)
10 changes: 3 additions & 7 deletions src/eegwatch/devices/_brainflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def start(self, filename: str = None, duration=None, extras: dict = None) -> Non
def record():
# NOTE: This runs in a seperate process/thread
self.board.start_stream()
for i in range(duration):
for _ in range(duration):
Copy link
Author

Choose a reason for hiding this comment

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

Function BrainflowDevice.start.record refactored with the following changes:

sleep(1)
self._save()
self._stop_brainflow()
Expand Down Expand Up @@ -87,8 +87,7 @@ def check(self, max_uv_abs=200) -> List[str]:
channel_names = BoardShim.get_eeg_names(self.brainflow_id)
# FIXME: _check_samples expects different (Muse) inputs
checked = _check_samples(data.T, channel_names, max_uv_abs=max_uv_abs) # type: ignore
bads = [ch for ch, ok in checked.items() if not ok]
return bads
return [ch for ch, ok in checked.items() if not ok]
Copy link
Author

Choose a reason for hiding this comment

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

Function BrainflowDevice.check refactored with the following changes:


def _init_brainflow(self) -> None:
"""
Expand Down Expand Up @@ -201,13 +200,10 @@ def get_data(self, clear_buffer=True) -> pd.DataFrame:
total_data, stim_array, 1
) # Append the stim array to data.

# Subtract five seconds of settling time from beginning
# total_data = total_data[5 * self.sfreq :]
df = pd.DataFrame(
return pd.DataFrame(
total_data,
columns=["timestamps"] + ch_names + (["stim"] if self.markers else []),
)
return df
Comment on lines -204 to -210
Copy link
Author

Choose a reason for hiding this comment

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

Function BrainflowDevice.get_data refactored with the following changes:

This removes the following comments ( why? ):

# total_data = total_data[5 * self.sfreq :]
# Subtract five seconds of settling time from beginning


def _save(self) -> None:
"""Saves the data to a CSV file."""
Expand Down
14 changes: 5 additions & 9 deletions src/eegwatch/devices/muse.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ def __init__(self, device_name: str):

@property
def started(self) -> bool:
if self.stream_process:
return self.stream_process.exitcode is None
return False
return self.stream_process.exitcode is None if self.stream_process else False
Copy link
Author

Choose a reason for hiding this comment

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

Function MuseDevice.started refactored with the following changes:


def start(self, filename: str = None, duration=None, extras: dict = None):
"""
Expand Down Expand Up @@ -123,15 +121,14 @@ def _read_buffer(self) -> np.ndarray:

inlets = _get_inlets(verbose=False)

for i in range(5):
for _ in range(5):
for inlet in inlets:
inlet.pull(timeout=0.5) # type: ignore
inlets = [inlet for inlet in inlets if inlet.buffer.any()] # type: ignore
if inlets:
break
else:
logger.info("No inlets with data, trying again in a second...")
sleep(1)
logger.info("No inlets with data, trying again in a second...")
sleep(1)
Comment on lines -126 to +131
Copy link
Author

Choose a reason for hiding this comment

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

Function MuseDevice._read_buffer refactored with the following changes:


if not inlets:
raise Exception("No inlets found")
Expand All @@ -149,5 +146,4 @@ def check(self, max_uv_abs: float) -> List[str]:
channels=["TP9", "AF7", "AF8", "TP10"],
max_uv_abs=max_uv_abs,
)
bads = [ch for ch, ok in checked.items() if not ok]
return bads
return [ch for ch, ok in checked.items() if not ok]
Comment on lines -152 to +149
Copy link
Author

Choose a reason for hiding this comment

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

Function MuseDevice.check refactored with the following changes:

3 changes: 1 addition & 2 deletions src/eegwatch/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ def load_demo(duration=1) -> mne.io.RawArray:
ch_names = ["T7", "CP5", "FC5", "C3", "C4", "FC6", "CP6", "T8"]
sfreq = BoardShim.get_sampling_rate(BoardIds.SYNTHETIC_BOARD.value)
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
raw = mne.io.RawArray(eeg_data, info)
return raw
return mne.io.RawArray(eeg_data, info)
Copy link
Author

Choose a reason for hiding this comment

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

Function load_demo refactored with the following changes:



def test_load_demo():
Expand Down
4 changes: 2 additions & 2 deletions src/eegwatch/lslutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ def _get_inlets(plt=None, verbose=True) -> List["Inlet"]:
info.nominal_srate() != pylsl.IRREGULAR_RATE
or info.channel_format() != pylsl.cf_string
):
logger.warning("Invalid marker stream " + info.name())
logger.warning(f"Invalid marker stream {info.name()}")
if verbose:
logger.info("Adding marker inlet: " + info.name())
logger.info(f"Adding marker inlet: {info.name()}")
Comment on lines -41 to +43
Copy link
Author

Choose a reason for hiding this comment

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

Function _get_inlets refactored with the following changes:

inlets.append(MarkerInlet(info))
elif (
info.nominal_srate() != pylsl.IRREGULAR_RATE
Expand Down
22 changes: 10 additions & 12 deletions src/eegwatch/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,14 @@ def connect(
sleep(5)
continue
except Exception as e:
if "No Muses found" in str(e):
msg = "No Muses found, trying again in 5s..."
logger.warning(msg)
notify("Couldn't connect", msg)
sleep(5)
continue
else:
if "No Muses found" not in str(e):
raise

msg = "No Muses found, trying again in 5s..."
logger.warning(msg)
notify("Couldn't connect", msg)
sleep(5)
continue
Comment on lines -104 to +111
Copy link
Author

Choose a reason for hiding this comment

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

Function connect refactored with the following changes:

loud = True
started = time()
stop = started + duration
Expand Down Expand Up @@ -169,11 +168,10 @@ def check(device_name: str):
if all_good:
if not last_good:
logger.info("All channels good!")
else:
if bads != last_bads:
logger.warning(
"Warning, bad signal for channels: " + ", ".join(bads)
)
elif bads != last_bads:
logger.warning(
"Warning, bad signal for channels: " + ", ".join(bads)
)
Comment on lines -172 to +174
Copy link
Author

Choose a reason for hiding this comment

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

Function check refactored with the following changes:

last_good = all_good
last_check = time()
last_bads = bads
Expand Down
8 changes: 3 additions & 5 deletions src/eegwatch/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,11 @@ def generate_save_fn(
# create the directory if it doesn't exist
recording_dir.mkdir(parents=True, exist_ok=True)

# generate filename based on recording date-and-timestamp and then append to recording_dir
save_fp = recording_dir / (
"recording_%s" % time.strftime("%Y-%m-%d-%H.%M.%S", time.gmtime()) + ".csv"
return recording_dir / (
f'recording_{time.strftime("%Y-%m-%d-%H.%M.%S", time.gmtime())}'
+ ".csv"
)

return save_fp
Comment on lines -35 to -40
Copy link
Author

Choose a reason for hiding this comment

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

Function generate_save_fn refactored with the following changes:

This removes the following comments ( why? ):

# generate filename based on recording date-and-timestamp and then append to recording_dir



def print_statusline(msg: str):
"""From: https://stackoverflow.com/a/43952192/965332"""
Expand Down