body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
3b98f559db1ea58165f30a3ac7778a52f0ef13d8e0486cd210c6e49d792bdef2 | def load_roi_data(roi_trace_path):
'\n load_roi_data(roi_trace_path)\n\n Returns ROI data from ROI data file. \n\n Required args:\n - roi_trace_path (Path): full path name of the ROI data file\n\n Returns:\n - roi_ids (list) : ROI IDs\n - nrois (int) : total number of ROIs\n - tot_twop_fr (int): total number of two-photon frames recorded\n '
with h5py.File(roi_trace_path, 'r') as f:
dataset_name = ('data' if ('data' in f.keys()) else 'FC')
roi_ids = f['roi_names'][()].tolist()
nrois = f[dataset_name].shape[0]
tot_twop_fr = f[dataset_name].shape[1]
return (roi_ids, nrois, tot_twop_fr) | load_roi_data(roi_trace_path)
Returns ROI data from ROI data file.
Required args:
- roi_trace_path (Path): full path name of the ROI data file
Returns:
- roi_ids (list) : ROI IDs
- nrois (int) : total number of ROIs
- tot_twop_fr (int): total number of two-photon frames recorded | sess_util/sess_trace_util.py | load_roi_data | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def load_roi_data(roi_trace_path):
'\n load_roi_data(roi_trace_path)\n\n Returns ROI data from ROI data file. \n\n Required args:\n - roi_trace_path (Path): full path name of the ROI data file\n\n Returns:\n - roi_ids (list) : ROI IDs\n - nrois (int) : total number of ROIs\n - tot_twop_fr (int): total number of two-photon frames recorded\n '
with h5py.File(roi_trace_path, 'r') as f:
dataset_name = ('data' if ('data' in f.keys()) else 'FC')
roi_ids = f['roi_names'][()].tolist()
nrois = f[dataset_name].shape[0]
tot_twop_fr = f[dataset_name].shape[1]
return (roi_ids, nrois, tot_twop_fr) | def load_roi_data(roi_trace_path):
'\n load_roi_data(roi_trace_path)\n\n Returns ROI data from ROI data file. \n\n Required args:\n - roi_trace_path (Path): full path name of the ROI data file\n\n Returns:\n - roi_ids (list) : ROI IDs\n - nrois (int) : total number of ROIs\n - tot_twop_fr (int): total number of two-photon frames recorded\n '
with h5py.File(roi_trace_path, 'r') as f:
dataset_name = ('data' if ('data' in f.keys()) else 'FC')
roi_ids = f['roi_names'][()].tolist()
nrois = f[dataset_name].shape[0]
tot_twop_fr = f[dataset_name].shape[1]
return (roi_ids, nrois, tot_twop_fr)<|docstring|>load_roi_data(roi_trace_path)
Returns ROI data from ROI data file.
Required args:
- roi_trace_path (Path): full path name of the ROI data file
Returns:
- roi_ids (list) : ROI IDs
- nrois (int) : total number of ROIs
- tot_twop_fr (int): total number of two-photon frames recorded<|endoftext|> |
eef42d2465078e695163bd765c02d114a829b2e9c1e0f42809a5264729a689d7 | def get_roi_locations(roi_extract_dict):
'\n get_roi_locations(roi_extract_dict)\n\n Returns ROI locations, extracted from ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns \n - roi_locations (pd DataFrame): ROI locations dataframe\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
rois = roi_extract_dict['rois']
roi_locations_list = []
for i in range(len(rois)):
roi = rois[i]
mask = roi['mask']
roi_locations_list.append([roi['id'], roi['x'], roi['y'], roi['width'], roi['height'], roi['valid'], mask])
roi_locations = pd.DataFrame(data=roi_locations_list, columns=['id', 'x', 'y', 'width', 'height', 'valid', 'mask'])
return roi_locations | get_roi_locations(roi_extract_dict)
Returns ROI locations, extracted from ROI extraction dictionary.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
Returns
- roi_locations (pd DataFrame): ROI locations dataframe | sess_util/sess_trace_util.py | get_roi_locations | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_roi_locations(roi_extract_dict):
'\n get_roi_locations(roi_extract_dict)\n\n Returns ROI locations, extracted from ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns \n - roi_locations (pd DataFrame): ROI locations dataframe\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
rois = roi_extract_dict['rois']
roi_locations_list = []
for i in range(len(rois)):
roi = rois[i]
mask = roi['mask']
roi_locations_list.append([roi['id'], roi['x'], roi['y'], roi['width'], roi['height'], roi['valid'], mask])
roi_locations = pd.DataFrame(data=roi_locations_list, columns=['id', 'x', 'y', 'width', 'height', 'valid', 'mask'])
return roi_locations | def get_roi_locations(roi_extract_dict):
'\n get_roi_locations(roi_extract_dict)\n\n Returns ROI locations, extracted from ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns \n - roi_locations (pd DataFrame): ROI locations dataframe\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
rois = roi_extract_dict['rois']
roi_locations_list = []
for i in range(len(rois)):
roi = rois[i]
mask = roi['mask']
roi_locations_list.append([roi['id'], roi['x'], roi['y'], roi['width'], roi['height'], roi['valid'], mask])
roi_locations = pd.DataFrame(data=roi_locations_list, columns=['id', 'x', 'y', 'width', 'height', 'valid', 'mask'])
return roi_locations<|docstring|>get_roi_locations(roi_extract_dict)
Returns ROI locations, extracted from ROI extraction dictionary.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
Returns
- roi_locations (pd DataFrame): ROI locations dataframe<|endoftext|> |
1f94ad7bce4a29b4551145d5ea2c3a3fdc4bc0cfd8d3d7c6af0982246f02d825 | def add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations):
'\n Returns ROI metrics dataframe with ROI IDs added.\n\n Required args:\n - roi_metrics (pd DataFrame) : ROI metrics dataframe\n - roi_locations (pd DataFrame): ROI locations dataframe\n \n Returns:\n - roi_metrics (pd DataFrame): ROI metrics dataframe updated with \n locations information\n '
roi_metrics = roi_metrics.copy(deep=True)
ids = []
for row in roi_metrics.index:
minx = roi_metrics.iloc[row][' minx']
miny = roi_metrics.iloc[row][' miny']
wid = ((roi_metrics.iloc[row][' maxx'] - minx) + 1)
hei = ((roi_metrics.iloc[row][' maxy'] - miny) + 1)
id_vals = roi_locations[((((roi_locations.x == minx) & (roi_locations.y == miny)) & (roi_locations.width == wid)) & (roi_locations.height == hei))].id.values
if (len(id_vals) != 1):
if (len(id_vals) > 1):
msg = f'Multiple ROI matches found ({len(id_vals)}).'
else:
msg = 'No ROI matches found.'
raise OSError(msg)
ids.append(id_vals[0])
roi_metrics['cell_specimen_id'] = ids
return roi_metrics | Returns ROI metrics dataframe with ROI IDs added.
Required args:
- roi_metrics (pd DataFrame) : ROI metrics dataframe
- roi_locations (pd DataFrame): ROI locations dataframe
Returns:
- roi_metrics (pd DataFrame): ROI metrics dataframe updated with
locations information | sess_util/sess_trace_util.py | add_cell_specimen_ids_to_roi_metrics | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations):
'\n Returns ROI metrics dataframe with ROI IDs added.\n\n Required args:\n - roi_metrics (pd DataFrame) : ROI metrics dataframe\n - roi_locations (pd DataFrame): ROI locations dataframe\n \n Returns:\n - roi_metrics (pd DataFrame): ROI metrics dataframe updated with \n locations information\n '
roi_metrics = roi_metrics.copy(deep=True)
ids = []
for row in roi_metrics.index:
minx = roi_metrics.iloc[row][' minx']
miny = roi_metrics.iloc[row][' miny']
wid = ((roi_metrics.iloc[row][' maxx'] - minx) + 1)
hei = ((roi_metrics.iloc[row][' maxy'] - miny) + 1)
id_vals = roi_locations[((((roi_locations.x == minx) & (roi_locations.y == miny)) & (roi_locations.width == wid)) & (roi_locations.height == hei))].id.values
if (len(id_vals) != 1):
if (len(id_vals) > 1):
msg = f'Multiple ROI matches found ({len(id_vals)}).'
else:
msg = 'No ROI matches found.'
raise OSError(msg)
ids.append(id_vals[0])
roi_metrics['cell_specimen_id'] = ids
return roi_metrics | def add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations):
'\n Returns ROI metrics dataframe with ROI IDs added.\n\n Required args:\n - roi_metrics (pd DataFrame) : ROI metrics dataframe\n - roi_locations (pd DataFrame): ROI locations dataframe\n \n Returns:\n - roi_metrics (pd DataFrame): ROI metrics dataframe updated with \n locations information\n '
roi_metrics = roi_metrics.copy(deep=True)
ids = []
for row in roi_metrics.index:
minx = roi_metrics.iloc[row][' minx']
miny = roi_metrics.iloc[row][' miny']
wid = ((roi_metrics.iloc[row][' maxx'] - minx) + 1)
hei = ((roi_metrics.iloc[row][' maxy'] - miny) + 1)
id_vals = roi_locations[((((roi_locations.x == minx) & (roi_locations.y == miny)) & (roi_locations.width == wid)) & (roi_locations.height == hei))].id.values
if (len(id_vals) != 1):
if (len(id_vals) > 1):
msg = f'Multiple ROI matches found ({len(id_vals)}).'
else:
msg = 'No ROI matches found.'
raise OSError(msg)
ids.append(id_vals[0])
roi_metrics['cell_specimen_id'] = ids
return roi_metrics<|docstring|>Returns ROI metrics dataframe with ROI IDs added.
Required args:
- roi_metrics (pd DataFrame) : ROI metrics dataframe
- roi_locations (pd DataFrame): ROI locations dataframe
Returns:
- roi_metrics (pd DataFrame): ROI metrics dataframe updated with
locations information<|endoftext|> |
94b2ec0ab57be35268ee6051479d751202d21615b89a3fd844f2c35006a923d1 | def get_motion_border(roi_extract_dict):
'\n get_motion_border(roi_extract_dict)\n\n Returns motion border for motion corrected stack.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns:\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
coords = ['x0', 'x1', 'y0', 'y1']
motion_border = [roi_extract_dict['motion_border'][coord] for coord in coords]
return motion_border | get_motion_border(roi_extract_dict)
Returns motion border for motion corrected stack.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
Returns:
- motion border (list): motion border values for [x0, x1, y1, y0]
(right, left, down, up shifts) | sess_util/sess_trace_util.py | get_motion_border | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_motion_border(roi_extract_dict):
'\n get_motion_border(roi_extract_dict)\n\n Returns motion border for motion corrected stack.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns:\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
coords = ['x0', 'x1', 'y0', 'y1']
motion_border = [roi_extract_dict['motion_border'][coord] for coord in coords]
return motion_border | def get_motion_border(roi_extract_dict):
'\n get_motion_border(roi_extract_dict)\n\n Returns motion border for motion corrected stack.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n\n Returns:\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n '
if (not isinstance(roi_extract_dict, dict)):
roi_extract_dict = file_util.loadfile(roi_extract_dict)
coords = ['x0', 'x1', 'y0', 'y1']
motion_border = [roi_extract_dict['motion_border'][coord] for coord in coords]
return motion_border<|docstring|>get_motion_border(roi_extract_dict)
Returns motion border for motion corrected stack.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
Returns:
- motion border (list): motion border values for [x0, x1, y1, y0]
(right, left, down, up shifts)<|endoftext|> |
f4c5bc7ce1d7145bc42dce668daedf8f4c2272d03a51379980455bf309f98d7e | def get_roi_metrics(roi_extract_dict, objectlist_txt):
'\n get_roi_metrics(roi_extract_dict, objectlist_txt)\n\n Returns ROI metrics loaded from object list file and updated based on \n ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n - objectlist_txt (Path) : path to object list containing ROI metrics\n \n Returns:\n - roi_metrics (pd DataFrame): dataframe containing ROI metrics\n '
roi_locations = get_roi_locations(roi_extract_dict)
roi_metrics = pd.read_csv(objectlist_txt)
roi_names = np.sort(roi_locations.id.values)
roi_locations['unfiltered_cell_index'] = [np.where((roi_names == roi_id))[0][0] for roi_id in roi_locations.id.values]
roi_metrics = add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations)
roi_metrics['id'] = roi_metrics.cell_specimen_id.values
roi_metrics = pd.merge(roi_metrics, roi_locations, on='id')
cell_index = [np.where((np.sort(roi_metrics.cell_specimen_id.values) == roi_id))[0][0] for roi_id in roi_metrics.cell_specimen_id.values]
roi_metrics['cell_index'] = cell_index
return roi_metrics | get_roi_metrics(roi_extract_dict, objectlist_txt)
Returns ROI metrics loaded from object list file and updated based on
ROI extraction dictionary.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
- objectlist_txt (Path) : path to object list containing ROI metrics
Returns:
- roi_metrics (pd DataFrame): dataframe containing ROI metrics | sess_util/sess_trace_util.py | get_roi_metrics | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_roi_metrics(roi_extract_dict, objectlist_txt):
'\n get_roi_metrics(roi_extract_dict, objectlist_txt)\n\n Returns ROI metrics loaded from object list file and updated based on \n ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n - objectlist_txt (Path) : path to object list containing ROI metrics\n \n Returns:\n - roi_metrics (pd DataFrame): dataframe containing ROI metrics\n '
roi_locations = get_roi_locations(roi_extract_dict)
roi_metrics = pd.read_csv(objectlist_txt)
roi_names = np.sort(roi_locations.id.values)
roi_locations['unfiltered_cell_index'] = [np.where((roi_names == roi_id))[0][0] for roi_id in roi_locations.id.values]
roi_metrics = add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations)
roi_metrics['id'] = roi_metrics.cell_specimen_id.values
roi_metrics = pd.merge(roi_metrics, roi_locations, on='id')
cell_index = [np.where((np.sort(roi_metrics.cell_specimen_id.values) == roi_id))[0][0] for roi_id in roi_metrics.cell_specimen_id.values]
roi_metrics['cell_index'] = cell_index
return roi_metrics | def get_roi_metrics(roi_extract_dict, objectlist_txt):
'\n get_roi_metrics(roi_extract_dict, objectlist_txt)\n\n Returns ROI metrics loaded from object list file and updated based on \n ROI extraction dictionary.\n\n Required args:\n - roi_extract_dict (dict): ROI extraction dictionary\n - objectlist_txt (Path) : path to object list containing ROI metrics\n \n Returns:\n - roi_metrics (pd DataFrame): dataframe containing ROI metrics\n '
roi_locations = get_roi_locations(roi_extract_dict)
roi_metrics = pd.read_csv(objectlist_txt)
roi_names = np.sort(roi_locations.id.values)
roi_locations['unfiltered_cell_index'] = [np.where((roi_names == roi_id))[0][0] for roi_id in roi_locations.id.values]
roi_metrics = add_cell_specimen_ids_to_roi_metrics(roi_metrics, roi_locations)
roi_metrics['id'] = roi_metrics.cell_specimen_id.values
roi_metrics = pd.merge(roi_metrics, roi_locations, on='id')
cell_index = [np.where((np.sort(roi_metrics.cell_specimen_id.values) == roi_id))[0][0] for roi_id in roi_metrics.cell_specimen_id.values]
roi_metrics['cell_index'] = cell_index
return roi_metrics<|docstring|>get_roi_metrics(roi_extract_dict, objectlist_txt)
Returns ROI metrics loaded from object list file and updated based on
ROI extraction dictionary.
Required args:
- roi_extract_dict (dict): ROI extraction dictionary
- objectlist_txt (Path) : path to object list containing ROI metrics
Returns:
- roi_metrics (pd DataFrame): dataframe containing ROI metrics<|endoftext|> |
07ec2e9a107aa62450364dc1ec7e354731b66f7cb6817e2f2f621db383d707a7 | def get_tracked_rois(nway_match_path, idx_after_rem_bad=False):
'\n get_tracked_rois(nway_match_path)\n\n Returns ROI tracking indices.\n\n Required args:\n - nway_match_path (Path): path to nway matching file\n \n Optional args:\n - idx_after_rem_bad (bool): if True, the ROI indices are shifted to \n as if bad ROIs did not exist\n (bad ROIs computed for dF/F only)\n default: False\n\n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
with open(nway_match_path, 'r') as f:
nway_dict = json.load(f)
tracked_rois_df = pd.DataFrame().from_dict(nway_dict['rois'])
tracked_rois = tracked_rois_df['dff-ordered_roi_index'].values
if idx_after_rem_bad:
bad_rois_df = pd.DataFrame().from_dict(nway_dict['bad_rois'])
bad_rois = bad_rois_df['dff_local_bad_roi_idx'].values
adj_tracked_rois = []
for n in tracked_rois:
adj_tracked_rois.append((n - np.sum((bad_rois < n))))
tracked_rois = np.asarray(adj_tracked_rois)
return tracked_rois | get_tracked_rois(nway_match_path)
Returns ROI tracking indices.
Required args:
- nway_match_path (Path): path to nway matching file
Optional args:
- idx_after_rem_bad (bool): if True, the ROI indices are shifted to
as if bad ROIs did not exist
(bad ROIs computed for dF/F only)
default: False
Returns:
- tracked_rois (1D array): ordered indices of tracked ROIs | sess_util/sess_trace_util.py | get_tracked_rois | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_tracked_rois(nway_match_path, idx_after_rem_bad=False):
'\n get_tracked_rois(nway_match_path)\n\n Returns ROI tracking indices.\n\n Required args:\n - nway_match_path (Path): path to nway matching file\n \n Optional args:\n - idx_after_rem_bad (bool): if True, the ROI indices are shifted to \n as if bad ROIs did not exist\n (bad ROIs computed for dF/F only)\n default: False\n\n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
with open(nway_match_path, 'r') as f:
nway_dict = json.load(f)
tracked_rois_df = pd.DataFrame().from_dict(nway_dict['rois'])
tracked_rois = tracked_rois_df['dff-ordered_roi_index'].values
if idx_after_rem_bad:
bad_rois_df = pd.DataFrame().from_dict(nway_dict['bad_rois'])
bad_rois = bad_rois_df['dff_local_bad_roi_idx'].values
adj_tracked_rois = []
for n in tracked_rois:
adj_tracked_rois.append((n - np.sum((bad_rois < n))))
tracked_rois = np.asarray(adj_tracked_rois)
return tracked_rois | def get_tracked_rois(nway_match_path, idx_after_rem_bad=False):
'\n get_tracked_rois(nway_match_path)\n\n Returns ROI tracking indices.\n\n Required args:\n - nway_match_path (Path): path to nway matching file\n \n Optional args:\n - idx_after_rem_bad (bool): if True, the ROI indices are shifted to \n as if bad ROIs did not exist\n (bad ROIs computed for dF/F only)\n default: False\n\n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
with open(nway_match_path, 'r') as f:
nway_dict = json.load(f)
tracked_rois_df = pd.DataFrame().from_dict(nway_dict['rois'])
tracked_rois = tracked_rois_df['dff-ordered_roi_index'].values
if idx_after_rem_bad:
bad_rois_df = pd.DataFrame().from_dict(nway_dict['bad_rois'])
bad_rois = bad_rois_df['dff_local_bad_roi_idx'].values
adj_tracked_rois = []
for n in tracked_rois:
adj_tracked_rois.append((n - np.sum((bad_rois < n))))
tracked_rois = np.asarray(adj_tracked_rois)
return tracked_rois<|docstring|>get_tracked_rois(nway_match_path)
Returns ROI tracking indices.
Required args:
- nway_match_path (Path): path to nway matching file
Optional args:
- idx_after_rem_bad (bool): if True, the ROI indices are shifted to
as if bad ROIs did not exist
(bad ROIs computed for dF/F only)
default: False
Returns:
- tracked_rois (1D array): ordered indices of tracked ROIs<|endoftext|> |
a60e170ecaff86cc091e4d6b4eeb764562fa1dd6932eb6ef37035e36bdffb378 | def get_tracked_rois_nwb(sess_files):
'\n get_tracked_rois_nwb(sess_files)\n\n Returns ROI tracking indices.\n\n Required args:\n - sess_files (list): full path names of the session files\n \n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
tracking_key = 'tracking_id'
if (tracking_key not in plane_seg.colnames):
raise RuntimeError(f'No tracking data in {ophys_file}.')
roi_tracking = np.asarray(plane_seg[tracking_key].data)
tracked_idxs = np.where(np.isfinite(roi_tracking))[0]
tracking_order = np.argsort(roi_tracking[tracked_idxs])
tracked_rois = tracked_idxs[tracking_order]
return tracked_rois | get_tracked_rois_nwb(sess_files)
Returns ROI tracking indices.
Required args:
- sess_files (list): full path names of the session files
Returns:
- tracked_rois (1D array): ordered indices of tracked ROIs | sess_util/sess_trace_util.py | get_tracked_rois_nwb | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_tracked_rois_nwb(sess_files):
'\n get_tracked_rois_nwb(sess_files)\n\n Returns ROI tracking indices.\n\n Required args:\n - sess_files (list): full path names of the session files\n \n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
tracking_key = 'tracking_id'
if (tracking_key not in plane_seg.colnames):
raise RuntimeError(f'No tracking data in {ophys_file}.')
roi_tracking = np.asarray(plane_seg[tracking_key].data)
tracked_idxs = np.where(np.isfinite(roi_tracking))[0]
tracking_order = np.argsort(roi_tracking[tracked_idxs])
tracked_rois = tracked_idxs[tracking_order]
return tracked_rois | def get_tracked_rois_nwb(sess_files):
'\n get_tracked_rois_nwb(sess_files)\n\n Returns ROI tracking indices.\n\n Required args:\n - sess_files (list): full path names of the session files\n \n Returns:\n - tracked_rois (1D array): ordered indices of tracked ROIs\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
tracking_key = 'tracking_id'
if (tracking_key not in plane_seg.colnames):
raise RuntimeError(f'No tracking data in {ophys_file}.')
roi_tracking = np.asarray(plane_seg[tracking_key].data)
tracked_idxs = np.where(np.isfinite(roi_tracking))[0]
tracking_order = np.argsort(roi_tracking[tracked_idxs])
tracked_rois = tracked_idxs[tracking_order]
return tracked_rois<|docstring|>get_tracked_rois_nwb(sess_files)
Returns ROI tracking indices.
Required args:
- sess_files (list): full path names of the session files
Returns:
- tracked_rois (1D array): ordered indices of tracked ROIs<|endoftext|> |
cba4452201bbe7cbeab0a0a7ae1801a8444a682d9f14e6cb91e243aaadb83878 | def process_roi_masks(roi_masks, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n process_roi_masks(roi_masks)\n\n Required args:\n - roi_masks (3D): ROI masks (ROI x hei x wid)\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n\n Returns:\n - roi_masks (3D): processed ROI masks (ROI x hei x wid)\n '
roi_masks = copy.deepcopy(roi_masks)
if (len(roi_masks.shape) != 3):
raise ValueError('roi_masks should have 3 dimensions.')
roi_masks[(roi_masks < mask_threshold)] = 0
if (min_n_pix != 0):
set_empty = (np.sum(roi_masks, axis=(1, 2)) < min_n_pix)
roi_masks[set_empty] = 0
if make_bool:
roi_masks = roi_masks.astype(bool)
return roi_masks | process_roi_masks(roi_masks)
Required args:
- roi_masks (3D): ROI masks (ROI x hei x wid)
Optional args:
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D): processed ROI masks (ROI x hei x wid) | sess_util/sess_trace_util.py | process_roi_masks | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def process_roi_masks(roi_masks, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n process_roi_masks(roi_masks)\n\n Required args:\n - roi_masks (3D): ROI masks (ROI x hei x wid)\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n\n Returns:\n - roi_masks (3D): processed ROI masks (ROI x hei x wid)\n '
roi_masks = copy.deepcopy(roi_masks)
if (len(roi_masks.shape) != 3):
raise ValueError('roi_masks should have 3 dimensions.')
roi_masks[(roi_masks < mask_threshold)] = 0
if (min_n_pix != 0):
set_empty = (np.sum(roi_masks, axis=(1, 2)) < min_n_pix)
roi_masks[set_empty] = 0
if make_bool:
roi_masks = roi_masks.astype(bool)
return roi_masks | def process_roi_masks(roi_masks, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n process_roi_masks(roi_masks)\n\n Required args:\n - roi_masks (3D): ROI masks (ROI x hei x wid)\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n\n Returns:\n - roi_masks (3D): processed ROI masks (ROI x hei x wid)\n '
roi_masks = copy.deepcopy(roi_masks)
if (len(roi_masks.shape) != 3):
raise ValueError('roi_masks should have 3 dimensions.')
roi_masks[(roi_masks < mask_threshold)] = 0
if (min_n_pix != 0):
set_empty = (np.sum(roi_masks, axis=(1, 2)) < min_n_pix)
roi_masks[set_empty] = 0
if make_bool:
roi_masks = roi_masks.astype(bool)
return roi_masks<|docstring|>process_roi_masks(roi_masks)
Required args:
- roi_masks (3D): ROI masks (ROI x hei x wid)
Optional args:
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D): processed ROI masks (ROI x hei x wid)<|endoftext|> |
1af509f9d743762f1e36f95c535fa8ca059ee48a745fcf9d83aca1311d463e7d | def get_roi_masks_nwb(sess_files, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks_nwb(sess_files)\n\n Returns tracked ROIs, optionally converted to boolean.\n\n Required args:\n - sess_files (Path): full path names of the session files\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
roi_masks = np.asarray(plane_seg['image_mask'].data)
roi_ids = list(plane_seg['id'].data)
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids) | get_roi_masks_nwb(sess_files)
Returns tracked ROIs, optionally converted to boolean.
Required args:
- sess_files (Path): full path names of the session files
Optional args:
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D array): ROI masks, structured as
ROI x height x width
- roi_ids (list) : ID for each ROI | sess_util/sess_trace_util.py | get_roi_masks_nwb | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_roi_masks_nwb(sess_files, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks_nwb(sess_files)\n\n Returns tracked ROIs, optionally converted to boolean.\n\n Required args:\n - sess_files (Path): full path names of the session files\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
roi_masks = np.asarray(plane_seg['image_mask'].data)
roi_ids = list(plane_seg['id'].data)
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids) | def get_roi_masks_nwb(sess_files, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks_nwb(sess_files)\n\n Returns tracked ROIs, optionally converted to boolean.\n\n Required args:\n - sess_files (Path): full path names of the session files\n\n Optional args:\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
ophys_file = sess_file_util.select_nwb_sess_path(sess_files, ophys=True)
with pynwb.NWBHDF5IO(str(ophys_file), 'r') as f:
nwbfile_in = f.read()
ophys_module = nwbfile_in.get_processing_module('ophys')
main_field = 'ImageSegmentation'
data_field = 'PlaneSegmentation'
try:
plane_seg = ophys_module.get_data_interface(main_field).get_plane_segmentation(data_field)
except KeyError as err:
raise KeyError(f'Could not find plane segmentation data in image segmentation for {ophys_file} due to: {err}')
roi_masks = np.asarray(plane_seg['image_mask'].data)
roi_ids = list(plane_seg['id'].data)
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids)<|docstring|>get_roi_masks_nwb(sess_files)
Returns tracked ROIs, optionally converted to boolean.
Required args:
- sess_files (Path): full path names of the session files
Optional args:
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D array): ROI masks, structured as
ROI x height x width
- roi_ids (list) : ID for each ROI<|endoftext|> |
759afbaf5aa541dbfa354f880241002b1186e8845f47e8b3b2f6f5bc8a756480 | def get_roi_masks(mask_file=None, roi_extract_json=None, objectlist_txt=None, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks()\n\n Returns ROI masks, loaded either from an h5 or json file, and optionally \n converted to boolean.\n\n NOTE: If masks are loaded from roi_extract_json, they are already boolean.\n\n Optional args:\n - mask_file (Path) : ROI mask h5. If None, roi_extract_json and\n objectlist_txt are used.\n default: None\n - roi_extract_json (Path): ROI extraction json (only needed is \n mask_file is None)\n - objectlist_txt (Path) : ROI object list txt (only needed if \n mask_file is None)\n default: None\n - mask_threshold (float) : minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
if ((mask_file is None) and ((roi_extract_json is None) or (objectlist_txt is None))):
raise ValueError("Must provide 'mask_file' or both 'roi_extract_json' and 'objectlist_txt'.")
if (mask_file is None):
roi_extract_dict = file_util.loadfile(roi_extract_json)
h = roi_extract_dict['image']['height']
w = roi_extract_dict['image']['width']
roi_metrics = get_roi_metrics(roi_extract_dict, objectlist_txt)
roi_ids = np.sort(roi_metrics.cell_specimen_id.values)
nrois = len(roi_ids)
roi_masks = np.full([nrois, h, w], False).astype(bool)
for (i, roi_id) in enumerate(roi_ids):
m = roi_metrics[(roi_metrics.id == roi_id)].iloc[0]
mask = np.asarray(m['mask'])
binary_mask = np.zeros((h, w), dtype=np.uint8)
binary_mask[(int(m.y):(int(m.y) + int(m.height)), int(m.x):(int(m.x) + int(m.width)))] = mask
roi_masks[i] = binary_mask
else:
with h5py.File(mask_file, 'r') as f:
roi_masks = f['data'][()]
roi_ids = list(range(len(roi_masks)))
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids) | get_roi_masks()
Returns ROI masks, loaded either from an h5 or json file, and optionally
converted to boolean.
NOTE: If masks are loaded from roi_extract_json, they are already boolean.
Optional args:
- mask_file (Path) : ROI mask h5. If None, roi_extract_json and
objectlist_txt are used.
default: None
- roi_extract_json (Path): ROI extraction json (only needed is
mask_file is None)
- objectlist_txt (Path) : ROI object list txt (only needed if
mask_file is None)
default: None
- mask_threshold (float) : minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D array): ROI masks, structured as
ROI x height x width
- roi_ids (list) : ID for each ROI | sess_util/sess_trace_util.py | get_roi_masks | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_roi_masks(mask_file=None, roi_extract_json=None, objectlist_txt=None, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks()\n\n Returns ROI masks, loaded either from an h5 or json file, and optionally \n converted to boolean.\n\n NOTE: If masks are loaded from roi_extract_json, they are already boolean.\n\n Optional args:\n - mask_file (Path) : ROI mask h5. If None, roi_extract_json and\n objectlist_txt are used.\n default: None\n - roi_extract_json (Path): ROI extraction json (only needed is \n mask_file is None)\n - objectlist_txt (Path) : ROI object list txt (only needed if \n mask_file is None)\n default: None\n - mask_threshold (float) : minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
if ((mask_file is None) and ((roi_extract_json is None) or (objectlist_txt is None))):
raise ValueError("Must provide 'mask_file' or both 'roi_extract_json' and 'objectlist_txt'.")
if (mask_file is None):
roi_extract_dict = file_util.loadfile(roi_extract_json)
h = roi_extract_dict['image']['height']
w = roi_extract_dict['image']['width']
roi_metrics = get_roi_metrics(roi_extract_dict, objectlist_txt)
roi_ids = np.sort(roi_metrics.cell_specimen_id.values)
nrois = len(roi_ids)
roi_masks = np.full([nrois, h, w], False).astype(bool)
for (i, roi_id) in enumerate(roi_ids):
m = roi_metrics[(roi_metrics.id == roi_id)].iloc[0]
mask = np.asarray(m['mask'])
binary_mask = np.zeros((h, w), dtype=np.uint8)
binary_mask[(int(m.y):(int(m.y) + int(m.height)), int(m.x):(int(m.x) + int(m.width)))] = mask
roi_masks[i] = binary_mask
else:
with h5py.File(mask_file, 'r') as f:
roi_masks = f['data'][()]
roi_ids = list(range(len(roi_masks)))
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids) | def get_roi_masks(mask_file=None, roi_extract_json=None, objectlist_txt=None, mask_threshold=MASK_THRESHOLD, min_n_pix=MIN_N_PIX, make_bool=True):
'\n get_roi_masks()\n\n Returns ROI masks, loaded either from an h5 or json file, and optionally \n converted to boolean.\n\n NOTE: If masks are loaded from roi_extract_json, they are already boolean.\n\n Optional args:\n - mask_file (Path) : ROI mask h5. If None, roi_extract_json and\n objectlist_txt are used.\n default: None\n - roi_extract_json (Path): ROI extraction json (only needed is \n mask_file is None)\n - objectlist_txt (Path) : ROI object list txt (only needed if \n mask_file is None)\n default: None\n - mask_threshold (float) : minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: MASK_THRESHOLD\n - min_n_pix (int) : minimum number of pixels in an ROI below \n which, ROI is set to be empty\n default: MIN_N_PIX\n - make_bool (bool) : if True, ROIs are converted to boolean \n before being returned\n default: True \n \n Returns:\n - roi_masks (3D array): ROI masks, structured as \n ROI x height x width\n - roi_ids (list) : ID for each ROI\n '
if ((mask_file is None) and ((roi_extract_json is None) or (objectlist_txt is None))):
raise ValueError("Must provide 'mask_file' or both 'roi_extract_json' and 'objectlist_txt'.")
if (mask_file is None):
roi_extract_dict = file_util.loadfile(roi_extract_json)
h = roi_extract_dict['image']['height']
w = roi_extract_dict['image']['width']
roi_metrics = get_roi_metrics(roi_extract_dict, objectlist_txt)
roi_ids = np.sort(roi_metrics.cell_specimen_id.values)
nrois = len(roi_ids)
roi_masks = np.full([nrois, h, w], False).astype(bool)
for (i, roi_id) in enumerate(roi_ids):
m = roi_metrics[(roi_metrics.id == roi_id)].iloc[0]
mask = np.asarray(m['mask'])
binary_mask = np.zeros((h, w), dtype=np.uint8)
binary_mask[(int(m.y):(int(m.y) + int(m.height)), int(m.x):(int(m.x) + int(m.width)))] = mask
roi_masks[i] = binary_mask
else:
with h5py.File(mask_file, 'r') as f:
roi_masks = f['data'][()]
roi_ids = list(range(len(roi_masks)))
roi_masks = process_roi_masks(roi_masks, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=make_bool)
return (roi_masks, roi_ids)<|docstring|>get_roi_masks()
Returns ROI masks, loaded either from an h5 or json file, and optionally
converted to boolean.
NOTE: If masks are loaded from roi_extract_json, they are already boolean.
Optional args:
- mask_file (Path) : ROI mask h5. If None, roi_extract_json and
objectlist_txt are used.
default: None
- roi_extract_json (Path): ROI extraction json (only needed is
mask_file is None)
- objectlist_txt (Path) : ROI object list txt (only needed if
mask_file is None)
default: None
- mask_threshold (float) : minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: MASK_THRESHOLD
- min_n_pix (int) : minimum number of pixels in an ROI below
which, ROI is set to be empty
default: MIN_N_PIX
- make_bool (bool) : if True, ROIs are converted to boolean
before being returned
default: True
Returns:
- roi_masks (3D array): ROI masks, structured as
ROI x height x width
- roi_ids (list) : ID for each ROI<|endoftext|> |
fbcba9b966ba57897b0968f8cdcbf8b460e307905e0391bc4be9e6ef17eb5397 | def get_valid_mask(roi_objs, neuropil_trace=None):
'\n validate_masks(roi_objs)\n\n Returns a boolean mask for valid ROIs using the following exclusion \n criteria: duplicate, empty, motion_border, union, empty_neuropil (optional).\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion criterion is omitted.\n default: None\n \n Returns: \n - valid_mask (1D array): boolean array of valid masks\n '
excl_mask_dict = validate_masks(roi_objs, neuropil_trace)
valid_mask = np.ones(len(roi_objs)).astype(bool)
for (_, excl_mask) in excl_mask_dict.items():
valid_mask[np.where(excl_mask)] = False
return valid_mask | validate_masks(roi_objs)
Returns a boolean mask for valid ROIs using the following exclusion
criteria: duplicate, empty, motion_border, union, empty_neuropil (optional).
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- neuropil_traces (list) : neuropil traces from which to infer empty
neuropil masks. If none provided, this
exclusion criterion is omitted.
default: None
Returns:
- valid_mask (1D array): boolean array of valid masks | sess_util/sess_trace_util.py | get_valid_mask | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_valid_mask(roi_objs, neuropil_trace=None):
'\n validate_masks(roi_objs)\n\n Returns a boolean mask for valid ROIs using the following exclusion \n criteria: duplicate, empty, motion_border, union, empty_neuropil (optional).\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion criterion is omitted.\n default: None\n \n Returns: \n - valid_mask (1D array): boolean array of valid masks\n '
excl_mask_dict = validate_masks(roi_objs, neuropil_trace)
valid_mask = np.ones(len(roi_objs)).astype(bool)
for (_, excl_mask) in excl_mask_dict.items():
valid_mask[np.where(excl_mask)] = False
return valid_mask | def get_valid_mask(roi_objs, neuropil_trace=None):
'\n validate_masks(roi_objs)\n\n Returns a boolean mask for valid ROIs using the following exclusion \n criteria: duplicate, empty, motion_border, union, empty_neuropil (optional).\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion criterion is omitted.\n default: None\n \n Returns: \n - valid_mask (1D array): boolean array of valid masks\n '
excl_mask_dict = validate_masks(roi_objs, neuropil_trace)
valid_mask = np.ones(len(roi_objs)).astype(bool)
for (_, excl_mask) in excl_mask_dict.items():
valid_mask[np.where(excl_mask)] = False
return valid_mask<|docstring|>validate_masks(roi_objs)
Returns a boolean mask for valid ROIs using the following exclusion
criteria: duplicate, empty, motion_border, union, empty_neuropil (optional).
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- neuropil_traces (list) : neuropil traces from which to infer empty
neuropil masks. If none provided, this
exclusion criterion is omitted.
default: None
Returns:
- valid_mask (1D array): boolean array of valid masks<|endoftext|> |
065bcc20abb6c81e28a1bd706e340d3452e0f7b8c8020afa26b952bd276c0f4c | def validate_masks(roi_objs, neuropil_traces=None):
'\n validate_masks(roi_objs)\n\n Returns a dictionary with exclusion ROI masks for each exclusion criterion \n ("duplicate", "empty", "motion_border", "union", "empty_neuropil"). \n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion label is omitted\n default: None\n\n Returns:\n - excl_mask_dict (dict): dictionary of masks for different exclusion \n criteria, where ROIs labeled by the exclusion\n criterion are marked as True, with keys:\n ["duplicate"] : mask for duplicate ROIs\n ["empty"] : mask for empty ROIs\n ["motion_border"]: mask for motion border overlapping ROIs\n ["union"] : mask for union ROIs\n '
exclusion_labels = EXCLUSION_LABELS
if (('empty_neuropil' in exclusion_labels) and (neuropil_traces is None)):
logger.warning('Empty_neuropil label will be omitted as neuropil_traces is None.')
_ = exclusion_labels.remove('empty_neuropil')
excl_mask_dict = dict()
for lab in exclusion_labels:
excl_mask_dict[lab] = np.zeros(len(roi_objs)).astype(bool)
other_expl = []
for (r, roi_obj) in enumerate(roi_objs):
if (roi_obj.mask is None):
excl_mask_dict['empty'][r] = True
continue
if roi_obj.overlaps_motion_border:
excl_mask_dict['motion_border'][r] = True
other_expl.append(r)
if ('union' in roi_obj.labels):
excl_mask_dict['union'][r] = True
other_expl.append(r)
if ('duplicate' in roi_obj.labels):
excl_mask_dict['duplicate'][r] = True
other_expl.append(r)
if ('empty_neuropil' in exclusion_labels):
nan_idx = np.where(np.isnan(np.sum(neuropil_traces, axis=1)))[0]
empty_inferred = np.asarray(list((set(nan_idx) - set(other_expl))))
if (len(empty_inferred) != 0):
excl_mask_dict['empty_neuropil'][empty_inferred] = True
return excl_mask_dict | validate_masks(roi_objs)
Returns a dictionary with exclusion ROI masks for each exclusion criterion
("duplicate", "empty", "motion_border", "union", "empty_neuropil").
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- neuropil_traces (list) : neuropil traces from which to infer empty
neuropil masks. If none provided, this
exclusion label is omitted
default: None
Returns:
- excl_mask_dict (dict): dictionary of masks for different exclusion
criteria, where ROIs labeled by the exclusion
criterion are marked as True, with keys:
["duplicate"] : mask for duplicate ROIs
["empty"] : mask for empty ROIs
["motion_border"]: mask for motion border overlapping ROIs
["union"] : mask for union ROIs | sess_util/sess_trace_util.py | validate_masks | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def validate_masks(roi_objs, neuropil_traces=None):
'\n validate_masks(roi_objs)\n\n Returns a dictionary with exclusion ROI masks for each exclusion criterion \n ("duplicate", "empty", "motion_border", "union", "empty_neuropil"). \n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion label is omitted\n default: None\n\n Returns:\n - excl_mask_dict (dict): dictionary of masks for different exclusion \n criteria, where ROIs labeled by the exclusion\n criterion are marked as True, with keys:\n ["duplicate"] : mask for duplicate ROIs\n ["empty"] : mask for empty ROIs\n ["motion_border"]: mask for motion border overlapping ROIs\n ["union"] : mask for union ROIs\n '
exclusion_labels = EXCLUSION_LABELS
if (('empty_neuropil' in exclusion_labels) and (neuropil_traces is None)):
logger.warning('Empty_neuropil label will be omitted as neuropil_traces is None.')
_ = exclusion_labels.remove('empty_neuropil')
excl_mask_dict = dict()
for lab in exclusion_labels:
excl_mask_dict[lab] = np.zeros(len(roi_objs)).astype(bool)
other_expl = []
for (r, roi_obj) in enumerate(roi_objs):
if (roi_obj.mask is None):
excl_mask_dict['empty'][r] = True
continue
if roi_obj.overlaps_motion_border:
excl_mask_dict['motion_border'][r] = True
other_expl.append(r)
if ('union' in roi_obj.labels):
excl_mask_dict['union'][r] = True
other_expl.append(r)
if ('duplicate' in roi_obj.labels):
excl_mask_dict['duplicate'][r] = True
other_expl.append(r)
if ('empty_neuropil' in exclusion_labels):
nan_idx = np.where(np.isnan(np.sum(neuropil_traces, axis=1)))[0]
empty_inferred = np.asarray(list((set(nan_idx) - set(other_expl))))
if (len(empty_inferred) != 0):
excl_mask_dict['empty_neuropil'][empty_inferred] = True
return excl_mask_dict | def validate_masks(roi_objs, neuropil_traces=None):
'\n validate_masks(roi_objs)\n\n Returns a dictionary with exclusion ROI masks for each exclusion criterion \n ("duplicate", "empty", "motion_border", "union", "empty_neuropil"). \n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - neuropil_traces (list) : neuropil traces from which to infer empty\n neuropil masks. If none provided, this \n exclusion label is omitted\n default: None\n\n Returns:\n - excl_mask_dict (dict): dictionary of masks for different exclusion \n criteria, where ROIs labeled by the exclusion\n criterion are marked as True, with keys:\n ["duplicate"] : mask for duplicate ROIs\n ["empty"] : mask for empty ROIs\n ["motion_border"]: mask for motion border overlapping ROIs\n ["union"] : mask for union ROIs\n '
exclusion_labels = EXCLUSION_LABELS
if (('empty_neuropil' in exclusion_labels) and (neuropil_traces is None)):
logger.warning('Empty_neuropil label will be omitted as neuropil_traces is None.')
_ = exclusion_labels.remove('empty_neuropil')
excl_mask_dict = dict()
for lab in exclusion_labels:
excl_mask_dict[lab] = np.zeros(len(roi_objs)).astype(bool)
other_expl = []
for (r, roi_obj) in enumerate(roi_objs):
if (roi_obj.mask is None):
excl_mask_dict['empty'][r] = True
continue
if roi_obj.overlaps_motion_border:
excl_mask_dict['motion_border'][r] = True
other_expl.append(r)
if ('union' in roi_obj.labels):
excl_mask_dict['union'][r] = True
other_expl.append(r)
if ('duplicate' in roi_obj.labels):
excl_mask_dict['duplicate'][r] = True
other_expl.append(r)
if ('empty_neuropil' in exclusion_labels):
nan_idx = np.where(np.isnan(np.sum(neuropil_traces, axis=1)))[0]
empty_inferred = np.asarray(list((set(nan_idx) - set(other_expl))))
if (len(empty_inferred) != 0):
excl_mask_dict['empty_neuropil'][empty_inferred] = True
return excl_mask_dict<|docstring|>validate_masks(roi_objs)
Returns a dictionary with exclusion ROI masks for each exclusion criterion
("duplicate", "empty", "motion_border", "union", "empty_neuropil").
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- neuropil_traces (list) : neuropil traces from which to infer empty
neuropil masks. If none provided, this
exclusion label is omitted
default: None
Returns:
- excl_mask_dict (dict): dictionary of masks for different exclusion
criteria, where ROIs labeled by the exclusion
criterion are marked as True, with keys:
["duplicate"] : mask for duplicate ROIs
["empty"] : mask for empty ROIs
["motion_border"]: mask for motion border overlapping ROIs
["union"] : mask for union ROIs<|endoftext|> |
5b93d20afaa1ff790d6659941b973d5b38b4fa488781dae0811b68008f1d9b18 | def label_unions_and_duplicates(roi_objs, masks=None, duplicate_threshold=0.9, union_threshold=0.7, max_dist=10, set_size=2):
'\n \n Modified from allensdk.internal.brain_observatory.roi_filter.py\n \n Returns ROI objects with unions and duplicates labelled.\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - masks (3D array) : ROI mask arrays. If None provided, they \n are recreated from the ROI objects\n default: None\n - duplicate_threshold (float): threshold for identifying ROI duplicated\n (only the first of each set is labelled \n a duplicate)\n default: 0.9\n - union_threshold (float) : threshold for identifying ROIs that are \n unions of several ROIs\n default: 0.7\n - set_size (int) : number of ROIs forming sets to be checked\n for possibly being unions\n default: 2\n - max_dist (num) : max distance between ROIs to be checked\n for possibly being unions\n default: 10\n\n Returns:\n - roi_objs (ROI objects): ROI objects labelled for union, duplicate,\n empty and border overlapping mask conditions\n\n '
roi_objs = copy.deepcopy(roi_objs)
if (masks is None):
masks = roi_masks.create_roi_mask_array(roi_objs)
non_empty_mask = np.asarray([(roi_obj.mask is not None) for roi_obj in roi_objs]).astype(bool)
non_empty_idx = np.where(non_empty_mask)[0]
for idx in np.where((~ non_empty_mask))[0]:
roi_objs[idx].labels.append('empty')
ms = mask_set.MaskSet(masks=masks[non_empty_idx])
duplicates = ms.detect_duplicates(duplicate_threshold)
for duplicate in duplicates:
orig_idx = non_empty_idx[duplicate[0]]
if ('duplicate' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('duplicate')
unions = ms.detect_unions(set_size, max_dist, union_threshold)
if unions:
union_idxs = list(unions.keys())
for idx in union_idxs:
orig_idx = non_empty_idx[idx]
if ('union' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('union')
return roi_objs | Modified from allensdk.internal.brain_observatory.roi_filter.py
Returns ROI objects with unions and duplicates labelled.
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- masks (3D array) : ROI mask arrays. If None provided, they
are recreated from the ROI objects
default: None
- duplicate_threshold (float): threshold for identifying ROI duplicated
(only the first of each set is labelled
a duplicate)
default: 0.9
- union_threshold (float) : threshold for identifying ROIs that are
unions of several ROIs
default: 0.7
- set_size (int) : number of ROIs forming sets to be checked
for possibly being unions
default: 2
- max_dist (num) : max distance between ROIs to be checked
for possibly being unions
default: 10
Returns:
- roi_objs (ROI objects): ROI objects labelled for union, duplicate,
empty and border overlapping mask conditions | sess_util/sess_trace_util.py | label_unions_and_duplicates | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def label_unions_and_duplicates(roi_objs, masks=None, duplicate_threshold=0.9, union_threshold=0.7, max_dist=10, set_size=2):
'\n \n Modified from allensdk.internal.brain_observatory.roi_filter.py\n \n Returns ROI objects with unions and duplicates labelled.\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - masks (3D array) : ROI mask arrays. If None provided, they \n are recreated from the ROI objects\n default: None\n - duplicate_threshold (float): threshold for identifying ROI duplicated\n (only the first of each set is labelled \n a duplicate)\n default: 0.9\n - union_threshold (float) : threshold for identifying ROIs that are \n unions of several ROIs\n default: 0.7\n - set_size (int) : number of ROIs forming sets to be checked\n for possibly being unions\n default: 2\n - max_dist (num) : max distance between ROIs to be checked\n for possibly being unions\n default: 10\n\n Returns:\n - roi_objs (ROI objects): ROI objects labelled for union, duplicate,\n empty and border overlapping mask conditions\n\n '
roi_objs = copy.deepcopy(roi_objs)
if (masks is None):
masks = roi_masks.create_roi_mask_array(roi_objs)
non_empty_mask = np.asarray([(roi_obj.mask is not None) for roi_obj in roi_objs]).astype(bool)
non_empty_idx = np.where(non_empty_mask)[0]
for idx in np.where((~ non_empty_mask))[0]:
roi_objs[idx].labels.append('empty')
ms = mask_set.MaskSet(masks=masks[non_empty_idx])
duplicates = ms.detect_duplicates(duplicate_threshold)
for duplicate in duplicates:
orig_idx = non_empty_idx[duplicate[0]]
if ('duplicate' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('duplicate')
unions = ms.detect_unions(set_size, max_dist, union_threshold)
if unions:
union_idxs = list(unions.keys())
for idx in union_idxs:
orig_idx = non_empty_idx[idx]
if ('union' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('union')
return roi_objs | def label_unions_and_duplicates(roi_objs, masks=None, duplicate_threshold=0.9, union_threshold=0.7, max_dist=10, set_size=2):
'\n \n Modified from allensdk.internal.brain_observatory.roi_filter.py\n \n Returns ROI objects with unions and duplicates labelled.\n\n Required args:\n - roi_objs (ROI objects): ROI objects\n\n Optional args:\n - masks (3D array) : ROI mask arrays. If None provided, they \n are recreated from the ROI objects\n default: None\n - duplicate_threshold (float): threshold for identifying ROI duplicated\n (only the first of each set is labelled \n a duplicate)\n default: 0.9\n - union_threshold (float) : threshold for identifying ROIs that are \n unions of several ROIs\n default: 0.7\n - set_size (int) : number of ROIs forming sets to be checked\n for possibly being unions\n default: 2\n - max_dist (num) : max distance between ROIs to be checked\n for possibly being unions\n default: 10\n\n Returns:\n - roi_objs (ROI objects): ROI objects labelled for union, duplicate,\n empty and border overlapping mask conditions\n\n '
roi_objs = copy.deepcopy(roi_objs)
if (masks is None):
masks = roi_masks.create_roi_mask_array(roi_objs)
non_empty_mask = np.asarray([(roi_obj.mask is not None) for roi_obj in roi_objs]).astype(bool)
non_empty_idx = np.where(non_empty_mask)[0]
for idx in np.where((~ non_empty_mask))[0]:
roi_objs[idx].labels.append('empty')
ms = mask_set.MaskSet(masks=masks[non_empty_idx])
duplicates = ms.detect_duplicates(duplicate_threshold)
for duplicate in duplicates:
orig_idx = non_empty_idx[duplicate[0]]
if ('duplicate' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('duplicate')
unions = ms.detect_unions(set_size, max_dist, union_threshold)
if unions:
union_idxs = list(unions.keys())
for idx in union_idxs:
orig_idx = non_empty_idx[idx]
if ('union' not in roi_objs[orig_idx].labels):
roi_objs[orig_idx].labels.append('union')
return roi_objs<|docstring|>Modified from allensdk.internal.brain_observatory.roi_filter.py
Returns ROI objects with unions and duplicates labelled.
Required args:
- roi_objs (ROI objects): ROI objects
Optional args:
- masks (3D array) : ROI mask arrays. If None provided, they
are recreated from the ROI objects
default: None
- duplicate_threshold (float): threshold for identifying ROI duplicated
(only the first of each set is labelled
a duplicate)
default: 0.9
- union_threshold (float) : threshold for identifying ROIs that are
unions of several ROIs
default: 0.7
- set_size (int) : number of ROIs forming sets to be checked
for possibly being unions
default: 2
- max_dist (num) : max distance between ROIs to be checked
for possibly being unions
default: 10
Returns:
- roi_objs (ROI objects): ROI objects labelled for union, duplicate,
empty and border overlapping mask conditions<|endoftext|> |
c9ff21420a7fe966101b65cefb6f9bd9f95e4e39fec3c0c75ca2bab187f6c5e8 | def create_mask_objects(masks, motion_border, roi_ids, union_threshold=0.7):
'\n create_mask_objects(masks, motion_border, roi_ids)\n\n Returns mask objects, labeled for overlapping the motion border, as well\n as for labels, duplicates and being empty.\n\n Required args:\n - masks (3D array) : ROI masks, structured as ROI x height x width\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n - roi_ids (list) : ID for each ROI\n\n Returns:\n - all_mask_objs (list) : list of ROI Mask objects, with exclusion labels\n (allensdk roi_masks.py)\n '
all_mask_objs = []
(hei, wid) = masks.shape[1:]
for (_, (mask, roi_id)) in enumerate(zip(masks, roi_ids)):
all_mask_objs.append(roi_masks.create_roi_mask(wid, hei, motion_border, roi_mask=mask, label=str(roi_id)))
all_mask_objs[(- 1)].labels = []
all_mask_objs = label_unions_and_duplicates(all_mask_objs, masks, union_threshold=0.7)
return all_mask_objs | create_mask_objects(masks, motion_border, roi_ids)
Returns mask objects, labeled for overlapping the motion border, as well
as for labels, duplicates and being empty.
Required args:
- masks (3D array) : ROI masks, structured as ROI x height x width
- motion border (list): motion border values for [x0, x1, y1, y0]
(right, left, down, up shifts)
- roi_ids (list) : ID for each ROI
Returns:
- all_mask_objs (list) : list of ROI Mask objects, with exclusion labels
(allensdk roi_masks.py) | sess_util/sess_trace_util.py | create_mask_objects | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def create_mask_objects(masks, motion_border, roi_ids, union_threshold=0.7):
'\n create_mask_objects(masks, motion_border, roi_ids)\n\n Returns mask objects, labeled for overlapping the motion border, as well\n as for labels, duplicates and being empty.\n\n Required args:\n - masks (3D array) : ROI masks, structured as ROI x height x width\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n - roi_ids (list) : ID for each ROI\n\n Returns:\n - all_mask_objs (list) : list of ROI Mask objects, with exclusion labels\n (allensdk roi_masks.py)\n '
all_mask_objs = []
(hei, wid) = masks.shape[1:]
for (_, (mask, roi_id)) in enumerate(zip(masks, roi_ids)):
all_mask_objs.append(roi_masks.create_roi_mask(wid, hei, motion_border, roi_mask=mask, label=str(roi_id)))
all_mask_objs[(- 1)].labels = []
all_mask_objs = label_unions_and_duplicates(all_mask_objs, masks, union_threshold=0.7)
return all_mask_objs | def create_mask_objects(masks, motion_border, roi_ids, union_threshold=0.7):
'\n create_mask_objects(masks, motion_border, roi_ids)\n\n Returns mask objects, labeled for overlapping the motion border, as well\n as for labels, duplicates and being empty.\n\n Required args:\n - masks (3D array) : ROI masks, structured as ROI x height x width\n - motion border (list): motion border values for [x0, x1, y1, y0]\n (right, left, down, up shifts)\n - roi_ids (list) : ID for each ROI\n\n Returns:\n - all_mask_objs (list) : list of ROI Mask objects, with exclusion labels\n (allensdk roi_masks.py)\n '
all_mask_objs = []
(hei, wid) = masks.shape[1:]
for (_, (mask, roi_id)) in enumerate(zip(masks, roi_ids)):
all_mask_objs.append(roi_masks.create_roi_mask(wid, hei, motion_border, roi_mask=mask, label=str(roi_id)))
all_mask_objs[(- 1)].labels = []
all_mask_objs = label_unions_and_duplicates(all_mask_objs, masks, union_threshold=0.7)
return all_mask_objs<|docstring|>create_mask_objects(masks, motion_border, roi_ids)
Returns mask objects, labeled for overlapping the motion border, as well
as for labels, duplicates and being empty.
Required args:
- masks (3D array) : ROI masks, structured as ROI x height x width
- motion border (list): motion border values for [x0, x1, y1, y0]
(right, left, down, up shifts)
- roi_ids (list) : ID for each ROI
Returns:
- all_mask_objs (list) : list of ROI Mask objects, with exclusion labels
(allensdk roi_masks.py)<|endoftext|> |
78afc3173c45dbcdb6931a2a89450182e9ea37b60ed98c943a6b9134a68fd1ba | def save_roi_dataset(data, save_path, roi_names, data_name='data', excl_dict=None, replace=True, compression=None):
'\n save_roi_dataset(save_path, roi_names)\n\n Saves ROI dataset.\n\n Required args:\n - data (nd array) : ROI data, where first dimension are ROIs\n - save_path (Path) : path for saving the dataset\n - roi_names (array-like): list of names for each ROI\n \n Optional args:\n - data_name (str) : main dataset name\n default: "data"\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n - replace (bool) : if True, an existing file is replaced\n default: True\n - compression (str): type of compression to use when saving h5 \n file (e.g., "gzip")\n default: None\n '
if (len(data) != len(roi_names)):
raise ValueError("'roi_names' must be as long as the first dimension of 'data'.")
save_path = Path(save_path)
if (save_path.is_file() and (not replace)):
logger.info('ROI traces already exist.')
return
file_util.createdir(save_path.parent, log_dir=False)
with h5py.File(save_path, 'w') as hf:
hf.create_dataset(data_name, data=data, compression=compression)
hf.create_dataset('roi_names', data=np.asarray(roi_names, dtype='S'))
if (excl_dict is not None):
for (key, item) in excl_dict.items():
hf.create_dataset(key, data=np.asarray(item, dtype='u1')) | save_roi_dataset(save_path, roi_names)
Saves ROI dataset.
Required args:
- data (nd array) : ROI data, where first dimension are ROIs
- save_path (Path) : path for saving the dataset
- roi_names (array-like): list of names for each ROI
Optional args:
- data_name (str) : main dataset name
default: "data"
- excl_dict (dict) : dictionary of exclusion masks for different
criteria
default: None
- replace (bool) : if True, an existing file is replaced
default: True
- compression (str): type of compression to use when saving h5
file (e.g., "gzip")
default: None | sess_util/sess_trace_util.py | save_roi_dataset | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def save_roi_dataset(data, save_path, roi_names, data_name='data', excl_dict=None, replace=True, compression=None):
'\n save_roi_dataset(save_path, roi_names)\n\n Saves ROI dataset.\n\n Required args:\n - data (nd array) : ROI data, where first dimension are ROIs\n - save_path (Path) : path for saving the dataset\n - roi_names (array-like): list of names for each ROI\n \n Optional args:\n - data_name (str) : main dataset name\n default: "data"\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n - replace (bool) : if True, an existing file is replaced\n default: True\n - compression (str): type of compression to use when saving h5 \n file (e.g., "gzip")\n default: None\n '
if (len(data) != len(roi_names)):
raise ValueError("'roi_names' must be as long as the first dimension of 'data'.")
save_path = Path(save_path)
if (save_path.is_file() and (not replace)):
logger.info('ROI traces already exist.')
return
file_util.createdir(save_path.parent, log_dir=False)
with h5py.File(save_path, 'w') as hf:
hf.create_dataset(data_name, data=data, compression=compression)
hf.create_dataset('roi_names', data=np.asarray(roi_names, dtype='S'))
if (excl_dict is not None):
for (key, item) in excl_dict.items():
hf.create_dataset(key, data=np.asarray(item, dtype='u1')) | def save_roi_dataset(data, save_path, roi_names, data_name='data', excl_dict=None, replace=True, compression=None):
'\n save_roi_dataset(save_path, roi_names)\n\n Saves ROI dataset.\n\n Required args:\n - data (nd array) : ROI data, where first dimension are ROIs\n - save_path (Path) : path for saving the dataset\n - roi_names (array-like): list of names for each ROI\n \n Optional args:\n - data_name (str) : main dataset name\n default: "data"\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n - replace (bool) : if True, an existing file is replaced\n default: True\n - compression (str): type of compression to use when saving h5 \n file (e.g., "gzip")\n default: None\n '
if (len(data) != len(roi_names)):
raise ValueError("'roi_names' must be as long as the first dimension of 'data'.")
save_path = Path(save_path)
if (save_path.is_file() and (not replace)):
logger.info('ROI traces already exist.')
return
file_util.createdir(save_path.parent, log_dir=False)
with h5py.File(save_path, 'w') as hf:
hf.create_dataset(data_name, data=data, compression=compression)
hf.create_dataset('roi_names', data=np.asarray(roi_names, dtype='S'))
if (excl_dict is not None):
for (key, item) in excl_dict.items():
hf.create_dataset(key, data=np.asarray(item, dtype='u1'))<|docstring|>save_roi_dataset(save_path, roi_names)
Saves ROI dataset.
Required args:
- data (nd array) : ROI data, where first dimension are ROIs
- save_path (Path) : path for saving the dataset
- roi_names (array-like): list of names for each ROI
Optional args:
- data_name (str) : main dataset name
default: "data"
- excl_dict (dict) : dictionary of exclusion masks for different
criteria
default: None
- replace (bool) : if True, an existing file is replaced
default: True
- compression (str): type of compression to use when saving h5
file (e.g., "gzip")
default: None<|endoftext|> |
c1632101b19836ad579cce27ce59adf72f0ee79fb46a832c818c3d9e9d3a4979 | def demix_rois(raw_traces, h5path, masks, excl_dict, verbose=False):
'\n demix_rois(raw_traces, h5path, masks, excl_dict)\n Returns time-dependent demixed traces (modified from allensdk, demixer.py, \n demix_time_dep_masks to allow partial loading of the stack).\n\n Required args:\n - raw_traces (2D array): extracted traces, structured as ROI x frames\n - h5path (Path) : path to full movie, structured as \n time x height x width\n - masks (3D array) : ROI mask, structured as ROI x height x width\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n \n Optional args:\n - verbose (bool): if True, singular matrix warning is printed\n default: False\n\n Returns:\n - demixed_traces (2D array): demixed traces, with excluded ROIs set to \n np.nan, structured as ROI x frames \n - drop_frames (list) : list of boolean values for each frame, \n recording whether it is dropped\n '
exclusion_labels = EXCLUSION_LABELS
valid_mask = np.ones(len(masks)).astype(bool)
for lab in exclusion_labels:
if (lab not in excl_dict.keys()):
if (lab == 'empty_neuropil'):
logger.warning('ROIs with empty neuropil not checked for before demixing.')
else:
raise KeyError(f'{lab} missing from excl_dict keys.')
valid_mask *= (~ excl_dict[lab].astype(bool))
if (len(valid_mask) != len(raw_traces)):
raise ValueError("'valid_mask' must be as long as the first dimension of 'raw_traces'.")
raw_traces_valid = raw_traces[valid_mask.astype(bool)]
masks_valid = masks[valid_mask.astype(bool)]
with h5py.File(h5path, 'r') as f:
stack = f['data']
(N, T) = raw_traces_valid.shape
(_, x, y) = masks_valid.shape
P = (x * y)
num_pixels_in_mask = np.sum(masks_valid, axis=(1, 2))
F = (raw_traces_valid.T * num_pixels_in_mask)
F = F.T
flat_masks = masks_valid.reshape(N, P)
flat_masks = sparse.csr_matrix(flat_masks)
drop_frames = []
demix_traces = np.zeros((N, T))
for t in range(T):
weighted_mask_sum = F[(:, t)]
drop_test = (weighted_mask_sum == 0)
if np.sum((drop_test == 0)):
norm_mat = sparse.diags((num_pixels_in_mask / weighted_mask_sum), offsets=0)
stack_t = sparse.diags(stack[t].reshape((- 1)), offsets=0)
flat_weighted_masks = norm_mat.dot(flat_masks.dot(stack_t))
overlap = flat_masks.dot(flat_weighted_masks.T).toarray()
try:
demix_traces[(:, t)] = linalg.solve(overlap, F[(:, t)])
except linalg.LinAlgError:
if verbose:
logger.warning(f'Frame {t}: singular matrix, using least squares')
(x, _, _, _) = linalg.lstsq(overlap, F[(:, t)])
demix_traces[(:, t)] = x
drop_frames.append(False)
else:
drop_frames.append(True)
demix_traces_all = np.full(raw_traces.shape, np.nan)
demix_traces_all[valid_mask.astype(bool)] = demix_traces
return (demix_traces_all, drop_frames) | demix_rois(raw_traces, h5path, masks, excl_dict)
Returns time-dependent demixed traces (modified from allensdk, demixer.py,
demix_time_dep_masks to allow partial loading of the stack).
Required args:
- raw_traces (2D array): extracted traces, structured as ROI x frames
- h5path (Path) : path to full movie, structured as
time x height x width
- masks (3D array) : ROI mask, structured as ROI x height x width
- excl_dict (dict) : dictionary of exclusion masks for different
criteria
default: None
Optional args:
- verbose (bool): if True, singular matrix warning is printed
default: False
Returns:
- demixed_traces (2D array): demixed traces, with excluded ROIs set to
np.nan, structured as ROI x frames
- drop_frames (list) : list of boolean values for each frame,
recording whether it is dropped | sess_util/sess_trace_util.py | demix_rois | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def demix_rois(raw_traces, h5path, masks, excl_dict, verbose=False):
'\n demix_rois(raw_traces, h5path, masks, excl_dict)\n Returns time-dependent demixed traces (modified from allensdk, demixer.py, \n demix_time_dep_masks to allow partial loading of the stack).\n\n Required args:\n - raw_traces (2D array): extracted traces, structured as ROI x frames\n - h5path (Path) : path to full movie, structured as \n time x height x width\n - masks (3D array) : ROI mask, structured as ROI x height x width\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n \n Optional args:\n - verbose (bool): if True, singular matrix warning is printed\n default: False\n\n Returns:\n - demixed_traces (2D array): demixed traces, with excluded ROIs set to \n np.nan, structured as ROI x frames \n - drop_frames (list) : list of boolean values for each frame, \n recording whether it is dropped\n '
exclusion_labels = EXCLUSION_LABELS
valid_mask = np.ones(len(masks)).astype(bool)
for lab in exclusion_labels:
if (lab not in excl_dict.keys()):
if (lab == 'empty_neuropil'):
logger.warning('ROIs with empty neuropil not checked for before demixing.')
else:
raise KeyError(f'{lab} missing from excl_dict keys.')
valid_mask *= (~ excl_dict[lab].astype(bool))
if (len(valid_mask) != len(raw_traces)):
raise ValueError("'valid_mask' must be as long as the first dimension of 'raw_traces'.")
raw_traces_valid = raw_traces[valid_mask.astype(bool)]
masks_valid = masks[valid_mask.astype(bool)]
with h5py.File(h5path, 'r') as f:
stack = f['data']
(N, T) = raw_traces_valid.shape
(_, x, y) = masks_valid.shape
P = (x * y)
num_pixels_in_mask = np.sum(masks_valid, axis=(1, 2))
F = (raw_traces_valid.T * num_pixels_in_mask)
F = F.T
flat_masks = masks_valid.reshape(N, P)
flat_masks = sparse.csr_matrix(flat_masks)
drop_frames = []
demix_traces = np.zeros((N, T))
for t in range(T):
weighted_mask_sum = F[(:, t)]
drop_test = (weighted_mask_sum == 0)
if np.sum((drop_test == 0)):
norm_mat = sparse.diags((num_pixels_in_mask / weighted_mask_sum), offsets=0)
stack_t = sparse.diags(stack[t].reshape((- 1)), offsets=0)
flat_weighted_masks = norm_mat.dot(flat_masks.dot(stack_t))
overlap = flat_masks.dot(flat_weighted_masks.T).toarray()
try:
demix_traces[(:, t)] = linalg.solve(overlap, F[(:, t)])
except linalg.LinAlgError:
if verbose:
logger.warning(f'Frame {t}: singular matrix, using least squares')
(x, _, _, _) = linalg.lstsq(overlap, F[(:, t)])
demix_traces[(:, t)] = x
drop_frames.append(False)
else:
drop_frames.append(True)
demix_traces_all = np.full(raw_traces.shape, np.nan)
demix_traces_all[valid_mask.astype(bool)] = demix_traces
return (demix_traces_all, drop_frames) | def demix_rois(raw_traces, h5path, masks, excl_dict, verbose=False):
'\n demix_rois(raw_traces, h5path, masks, excl_dict)\n Returns time-dependent demixed traces (modified from allensdk, demixer.py, \n demix_time_dep_masks to allow partial loading of the stack).\n\n Required args:\n - raw_traces (2D array): extracted traces, structured as ROI x frames\n - h5path (Path) : path to full movie, structured as \n time x height x width\n - masks (3D array) : ROI mask, structured as ROI x height x width\n - excl_dict (dict) : dictionary of exclusion masks for different \n criteria\n default: None\n \n Optional args:\n - verbose (bool): if True, singular matrix warning is printed\n default: False\n\n Returns:\n - demixed_traces (2D array): demixed traces, with excluded ROIs set to \n np.nan, structured as ROI x frames \n - drop_frames (list) : list of boolean values for each frame, \n recording whether it is dropped\n '
exclusion_labels = EXCLUSION_LABELS
valid_mask = np.ones(len(masks)).astype(bool)
for lab in exclusion_labels:
if (lab not in excl_dict.keys()):
if (lab == 'empty_neuropil'):
logger.warning('ROIs with empty neuropil not checked for before demixing.')
else:
raise KeyError(f'{lab} missing from excl_dict keys.')
valid_mask *= (~ excl_dict[lab].astype(bool))
if (len(valid_mask) != len(raw_traces)):
raise ValueError("'valid_mask' must be as long as the first dimension of 'raw_traces'.")
raw_traces_valid = raw_traces[valid_mask.astype(bool)]
masks_valid = masks[valid_mask.astype(bool)]
with h5py.File(h5path, 'r') as f:
stack = f['data']
(N, T) = raw_traces_valid.shape
(_, x, y) = masks_valid.shape
P = (x * y)
num_pixels_in_mask = np.sum(masks_valid, axis=(1, 2))
F = (raw_traces_valid.T * num_pixels_in_mask)
F = F.T
flat_masks = masks_valid.reshape(N, P)
flat_masks = sparse.csr_matrix(flat_masks)
drop_frames = []
demix_traces = np.zeros((N, T))
for t in range(T):
weighted_mask_sum = F[(:, t)]
drop_test = (weighted_mask_sum == 0)
if np.sum((drop_test == 0)):
norm_mat = sparse.diags((num_pixels_in_mask / weighted_mask_sum), offsets=0)
stack_t = sparse.diags(stack[t].reshape((- 1)), offsets=0)
flat_weighted_masks = norm_mat.dot(flat_masks.dot(stack_t))
overlap = flat_masks.dot(flat_weighted_masks.T).toarray()
try:
demix_traces[(:, t)] = linalg.solve(overlap, F[(:, t)])
except linalg.LinAlgError:
if verbose:
logger.warning(f'Frame {t}: singular matrix, using least squares')
(x, _, _, _) = linalg.lstsq(overlap, F[(:, t)])
demix_traces[(:, t)] = x
drop_frames.append(False)
else:
drop_frames.append(True)
demix_traces_all = np.full(raw_traces.shape, np.nan)
demix_traces_all[valid_mask.astype(bool)] = demix_traces
return (demix_traces_all, drop_frames)<|docstring|>demix_rois(raw_traces, h5path, masks, excl_dict)
Returns time-dependent demixed traces (modified from allensdk, demixer.py,
demix_time_dep_masks to allow partial loading of the stack).
Required args:
- raw_traces (2D array): extracted traces, structured as ROI x frames
- h5path (Path) : path to full movie, structured as
time x height x width
- masks (3D array) : ROI mask, structured as ROI x height x width
- excl_dict (dict) : dictionary of exclusion masks for different
criteria
default: None
Optional args:
- verbose (bool): if True, singular matrix warning is printed
default: False
Returns:
- demixed_traces (2D array): demixed traces, with excluded ROIs set to
np.nan, structured as ROI x frames
- drop_frames (list) : list of boolean values for each frame,
recording whether it is dropped<|endoftext|> |
02f220288d731c52e5870697a1c3bd516399bc45378574513341df5b54cd0af9 | def get_neuropil_subtracted_traces(roi_traces, neuropil_traces):
'\n get_neuropil_subtracted_traces(roi_traces, neuropil_traces)\n\n Returns ROI traces with neuropil subtracted, as well as the contamination \n ratio for each ROI.\n\n Required args:\n - roi_traces (2D array) : ROI traces, structured as ROI x frame\n - neuropil_traces (2D array): neuropil traces, structured as ROI x frame\n\n Returns:\n - neuropilsub_traces (2D array): ROI traces with neuropil subtracted, \n structured as ROI x frame\n - r (1D array) : contamination ratio (0-1) for each ROI\n '
r = np.full(len(roi_traces), 0.0)
for (i, (roi_trace, neuropil_trace)) in enumerate(zip(roi_traces, neuropil_traces)):
if np.isfinite(roi_trace).all():
r[i] = r_neuropil.estimate_contamination_ratios(roi_trace, neuropil_trace, iterations=3)['r']
neuropilsub_traces = (roi_traces - (neuropil_traces * r[(:, np.newaxis)]))
return (neuropilsub_traces, r) | get_neuropil_subtracted_traces(roi_traces, neuropil_traces)
Returns ROI traces with neuropil subtracted, as well as the contamination
ratio for each ROI.
Required args:
- roi_traces (2D array) : ROI traces, structured as ROI x frame
- neuropil_traces (2D array): neuropil traces, structured as ROI x frame
Returns:
- neuropilsub_traces (2D array): ROI traces with neuropil subtracted,
structured as ROI x frame
- r (1D array) : contamination ratio (0-1) for each ROI | sess_util/sess_trace_util.py | get_neuropil_subtracted_traces | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def get_neuropil_subtracted_traces(roi_traces, neuropil_traces):
'\n get_neuropil_subtracted_traces(roi_traces, neuropil_traces)\n\n Returns ROI traces with neuropil subtracted, as well as the contamination \n ratio for each ROI.\n\n Required args:\n - roi_traces (2D array) : ROI traces, structured as ROI x frame\n - neuropil_traces (2D array): neuropil traces, structured as ROI x frame\n\n Returns:\n - neuropilsub_traces (2D array): ROI traces with neuropil subtracted, \n structured as ROI x frame\n - r (1D array) : contamination ratio (0-1) for each ROI\n '
r = np.full(len(roi_traces), 0.0)
for (i, (roi_trace, neuropil_trace)) in enumerate(zip(roi_traces, neuropil_traces)):
if np.isfinite(roi_trace).all():
r[i] = r_neuropil.estimate_contamination_ratios(roi_trace, neuropil_trace, iterations=3)['r']
neuropilsub_traces = (roi_traces - (neuropil_traces * r[(:, np.newaxis)]))
return (neuropilsub_traces, r) | def get_neuropil_subtracted_traces(roi_traces, neuropil_traces):
'\n get_neuropil_subtracted_traces(roi_traces, neuropil_traces)\n\n Returns ROI traces with neuropil subtracted, as well as the contamination \n ratio for each ROI.\n\n Required args:\n - roi_traces (2D array) : ROI traces, structured as ROI x frame\n - neuropil_traces (2D array): neuropil traces, structured as ROI x frame\n\n Returns:\n - neuropilsub_traces (2D array): ROI traces with neuropil subtracted, \n structured as ROI x frame\n - r (1D array) : contamination ratio (0-1) for each ROI\n '
r = np.full(len(roi_traces), 0.0)
for (i, (roi_trace, neuropil_trace)) in enumerate(zip(roi_traces, neuropil_traces)):
if np.isfinite(roi_trace).all():
r[i] = r_neuropil.estimate_contamination_ratios(roi_trace, neuropil_trace, iterations=3)['r']
neuropilsub_traces = (roi_traces - (neuropil_traces * r[(:, np.newaxis)]))
return (neuropilsub_traces, r)<|docstring|>get_neuropil_subtracted_traces(roi_traces, neuropil_traces)
Returns ROI traces with neuropil subtracted, as well as the contamination
ratio for each ROI.
Required args:
- roi_traces (2D array) : ROI traces, structured as ROI x frame
- neuropil_traces (2D array): neuropil traces, structured as ROI x frame
Returns:
- neuropilsub_traces (2D array): ROI traces with neuropil subtracted,
structured as ROI x frame
- r (1D array) : contamination ratio (0-1) for each ROI<|endoftext|> |
ac56faaa027a28d8af7bf6ba40031caccd5d811c3448bdea4f7411546fa5b775 | def create_traces_from_masks(datadir, sessid, runtype='prod', h5dir=None, savedir='trace_proc_dir', dendritic=False, mask_threshold=0.1, min_n_pix=3, compression=None):
'\n create_traces_from_masks(datadir, sessid)\n\n Extracts traces from masks, applies correction (neuropil traces, demixed \n traces, corrected traces, dF/F traces) and saves them. \n \n WARNING: Will replace any existing files.\n\n Required args:\n - datadir (Path): name of the data directory\n - sessid (int) : session ID (9 digits)\n\n Optional args:\n - runtype (str) : "prod" (production) or "pilot" data\n default: "prod"\n - h5dir (Path) : path of the h5 data directory. If None, \n datadir is used.\n default: None\n - savedir (Path) : path of the directory in which to save new \n files. If None, datadir is used.\n default: "trace_proc_dir"\n - dendritic (bool) : if True, paths are changed to EXTRACT \n version dendritic\n default: False\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: 0.1 \n - min_n_pix (int) : minimum number of pixels in an ROI\n default: 3\n - compression (str) : type of compression to use when saving data \n to h5 files (e.g., "gzip")\n default: None\n '
file_dict = sess_file_util.get_file_names_from_sessid(datadir, sessid, runtype, check=False)[1]
roi_extract_json = file_dict['roi_extract_json']
objectlist_path = file_dict['roi_objectlist_txt']
h5path = file_dict['correct_data_h5']
dirnames = [datadir, h5dir, savedir]
(datadir, h5dir, savedir) = [str(Path(dirname)) for dirname in dirnames]
if (h5dir is not None):
h5path = h5path.replace(datadir, h5dir)
mask_path = None
if dendritic:
mask_path = sess_file_util.get_dendritic_mask_path_from_sessid(Path(datadir), sessid, runtype, check=True)
roi_trace_dict = sess_file_util.get_roi_trace_paths_from_sessid(Path(datadir), sessid, runtype, dendritic=dendritic, check=False)
if (savedir is not None):
for (key, item) in roi_trace_dict.items():
roi_trace_dict[key] = Path(str(item).replace(datadir, savedir))
logger.info('Extracting ROI masks.')
(masks_bool, roi_ids) = get_roi_masks(mask_path, roi_extract_json, objectlist_path, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=True)
motion_border = get_motion_border(roi_extract_json)
all_mask_objs = create_mask_objects(masks_bool, motion_border, roi_ids, union_threshold=0.7)
logger.info('Creating ROI and neuropil traces.')
[roi_traces, neuropil_traces, _] = roi_masks.calculate_roi_and_neuropil_traces(str(h5path), all_mask_objs, motion_border=motion_border)
excl_dict = validate_masks(all_mask_objs, neuropil_traces=neuropil_traces)
logger.info('Saving raw ROI traces.')
save_roi_dataset(roi_traces, roi_trace_dict['unproc_roi_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Saving neuropil traces.')
save_roi_dataset(neuropil_traces, roi_trace_dict['neuropil_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Demixing ROI traces.')
(demixed_traces, _) = demix_rois(roi_traces, h5path, masks_bool, excl_dict, verbose=False)
logger.info('Saving demixed traces.')
save_roi_dataset(demixed_traces, roi_trace_dict['demixed_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Subtracting neuropil from demixed ROI traces.')
(raw_processed_traces, r) = get_neuropil_subtracted_traces(demixed_traces, neuropil_traces)
logger.info('Saving processed traces')
save_roi_dataset(raw_processed_traces, roi_trace_dict['roi_trace_h5'], roi_ids, data_name='FC', excl_dict=excl_dict, replace=True, compression=compression)
with h5py.File(roi_trace_dict['roi_trace_h5'], 'r+') as hf:
hf.create_dataset('r', data=r, compression=compression)
logger.info('Calculating dF/F')
dff_traces = dff.calculate_dff(raw_processed_traces)
logger.info('Saving dF/F traces.')
save_roi_dataset(dff_traces, roi_trace_dict['roi_trace_dff_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
return | create_traces_from_masks(datadir, sessid)
Extracts traces from masks, applies correction (neuropil traces, demixed
traces, corrected traces, dF/F traces) and saves them.
WARNING: Will replace any existing files.
Required args:
- datadir (Path): name of the data directory
- sessid (int) : session ID (9 digits)
Optional args:
- runtype (str) : "prod" (production) or "pilot" data
default: "prod"
- h5dir (Path) : path of the h5 data directory. If None,
datadir is used.
default: None
- savedir (Path) : path of the directory in which to save new
files. If None, datadir is used.
default: "trace_proc_dir"
- dendritic (bool) : if True, paths are changed to EXTRACT
version dendritic
default: False
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: 0.1
- min_n_pix (int) : minimum number of pixels in an ROI
default: 3
- compression (str) : type of compression to use when saving data
to h5 files (e.g., "gzip")
default: None | sess_util/sess_trace_util.py | create_traces_from_masks | AllenInstitute/OpenScope_CA_Analysis | 0 | python | def create_traces_from_masks(datadir, sessid, runtype='prod', h5dir=None, savedir='trace_proc_dir', dendritic=False, mask_threshold=0.1, min_n_pix=3, compression=None):
'\n create_traces_from_masks(datadir, sessid)\n\n Extracts traces from masks, applies correction (neuropil traces, demixed \n traces, corrected traces, dF/F traces) and saves them. \n \n WARNING: Will replace any existing files.\n\n Required args:\n - datadir (Path): name of the data directory\n - sessid (int) : session ID (9 digits)\n\n Optional args:\n - runtype (str) : "prod" (production) or "pilot" data\n default: "prod"\n - h5dir (Path) : path of the h5 data directory. If None, \n datadir is used.\n default: None\n - savedir (Path) : path of the directory in which to save new \n files. If None, datadir is used.\n default: "trace_proc_dir"\n - dendritic (bool) : if True, paths are changed to EXTRACT \n version dendritic\n default: False\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: 0.1 \n - min_n_pix (int) : minimum number of pixels in an ROI\n default: 3\n - compression (str) : type of compression to use when saving data \n to h5 files (e.g., "gzip")\n default: None\n '
file_dict = sess_file_util.get_file_names_from_sessid(datadir, sessid, runtype, check=False)[1]
roi_extract_json = file_dict['roi_extract_json']
objectlist_path = file_dict['roi_objectlist_txt']
h5path = file_dict['correct_data_h5']
dirnames = [datadir, h5dir, savedir]
(datadir, h5dir, savedir) = [str(Path(dirname)) for dirname in dirnames]
if (h5dir is not None):
h5path = h5path.replace(datadir, h5dir)
mask_path = None
if dendritic:
mask_path = sess_file_util.get_dendritic_mask_path_from_sessid(Path(datadir), sessid, runtype, check=True)
roi_trace_dict = sess_file_util.get_roi_trace_paths_from_sessid(Path(datadir), sessid, runtype, dendritic=dendritic, check=False)
if (savedir is not None):
for (key, item) in roi_trace_dict.items():
roi_trace_dict[key] = Path(str(item).replace(datadir, savedir))
logger.info('Extracting ROI masks.')
(masks_bool, roi_ids) = get_roi_masks(mask_path, roi_extract_json, objectlist_path, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=True)
motion_border = get_motion_border(roi_extract_json)
all_mask_objs = create_mask_objects(masks_bool, motion_border, roi_ids, union_threshold=0.7)
logger.info('Creating ROI and neuropil traces.')
[roi_traces, neuropil_traces, _] = roi_masks.calculate_roi_and_neuropil_traces(str(h5path), all_mask_objs, motion_border=motion_border)
excl_dict = validate_masks(all_mask_objs, neuropil_traces=neuropil_traces)
logger.info('Saving raw ROI traces.')
save_roi_dataset(roi_traces, roi_trace_dict['unproc_roi_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Saving neuropil traces.')
save_roi_dataset(neuropil_traces, roi_trace_dict['neuropil_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Demixing ROI traces.')
(demixed_traces, _) = demix_rois(roi_traces, h5path, masks_bool, excl_dict, verbose=False)
logger.info('Saving demixed traces.')
save_roi_dataset(demixed_traces, roi_trace_dict['demixed_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Subtracting neuropil from demixed ROI traces.')
(raw_processed_traces, r) = get_neuropil_subtracted_traces(demixed_traces, neuropil_traces)
logger.info('Saving processed traces')
save_roi_dataset(raw_processed_traces, roi_trace_dict['roi_trace_h5'], roi_ids, data_name='FC', excl_dict=excl_dict, replace=True, compression=compression)
with h5py.File(roi_trace_dict['roi_trace_h5'], 'r+') as hf:
hf.create_dataset('r', data=r, compression=compression)
logger.info('Calculating dF/F')
dff_traces = dff.calculate_dff(raw_processed_traces)
logger.info('Saving dF/F traces.')
save_roi_dataset(dff_traces, roi_trace_dict['roi_trace_dff_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
return | def create_traces_from_masks(datadir, sessid, runtype='prod', h5dir=None, savedir='trace_proc_dir', dendritic=False, mask_threshold=0.1, min_n_pix=3, compression=None):
'\n create_traces_from_masks(datadir, sessid)\n\n Extracts traces from masks, applies correction (neuropil traces, demixed \n traces, corrected traces, dF/F traces) and saves them. \n \n WARNING: Will replace any existing files.\n\n Required args:\n - datadir (Path): name of the data directory\n - sessid (int) : session ID (9 digits)\n\n Optional args:\n - runtype (str) : "prod" (production) or "pilot" data\n default: "prod"\n - h5dir (Path) : path of the h5 data directory. If None, \n datadir is used.\n default: None\n - savedir (Path) : path of the directory in which to save new \n files. If None, datadir is used.\n default: "trace_proc_dir"\n - dendritic (bool) : if True, paths are changed to EXTRACT \n version dendritic\n default: False\n - mask_threshold (float): minimum value in non-boolean mask to\n retain a pixel in an ROI mask\n default: 0.1 \n - min_n_pix (int) : minimum number of pixels in an ROI\n default: 3\n - compression (str) : type of compression to use when saving data \n to h5 files (e.g., "gzip")\n default: None\n '
file_dict = sess_file_util.get_file_names_from_sessid(datadir, sessid, runtype, check=False)[1]
roi_extract_json = file_dict['roi_extract_json']
objectlist_path = file_dict['roi_objectlist_txt']
h5path = file_dict['correct_data_h5']
dirnames = [datadir, h5dir, savedir]
(datadir, h5dir, savedir) = [str(Path(dirname)) for dirname in dirnames]
if (h5dir is not None):
h5path = h5path.replace(datadir, h5dir)
mask_path = None
if dendritic:
mask_path = sess_file_util.get_dendritic_mask_path_from_sessid(Path(datadir), sessid, runtype, check=True)
roi_trace_dict = sess_file_util.get_roi_trace_paths_from_sessid(Path(datadir), sessid, runtype, dendritic=dendritic, check=False)
if (savedir is not None):
for (key, item) in roi_trace_dict.items():
roi_trace_dict[key] = Path(str(item).replace(datadir, savedir))
logger.info('Extracting ROI masks.')
(masks_bool, roi_ids) = get_roi_masks(mask_path, roi_extract_json, objectlist_path, mask_threshold=mask_threshold, min_n_pix=min_n_pix, make_bool=True)
motion_border = get_motion_border(roi_extract_json)
all_mask_objs = create_mask_objects(masks_bool, motion_border, roi_ids, union_threshold=0.7)
logger.info('Creating ROI and neuropil traces.')
[roi_traces, neuropil_traces, _] = roi_masks.calculate_roi_and_neuropil_traces(str(h5path), all_mask_objs, motion_border=motion_border)
excl_dict = validate_masks(all_mask_objs, neuropil_traces=neuropil_traces)
logger.info('Saving raw ROI traces.')
save_roi_dataset(roi_traces, roi_trace_dict['unproc_roi_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Saving neuropil traces.')
save_roi_dataset(neuropil_traces, roi_trace_dict['neuropil_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Demixing ROI traces.')
(demixed_traces, _) = demix_rois(roi_traces, h5path, masks_bool, excl_dict, verbose=False)
logger.info('Saving demixed traces.')
save_roi_dataset(demixed_traces, roi_trace_dict['demixed_trace_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
logger.info('Subtracting neuropil from demixed ROI traces.')
(raw_processed_traces, r) = get_neuropil_subtracted_traces(demixed_traces, neuropil_traces)
logger.info('Saving processed traces')
save_roi_dataset(raw_processed_traces, roi_trace_dict['roi_trace_h5'], roi_ids, data_name='FC', excl_dict=excl_dict, replace=True, compression=compression)
with h5py.File(roi_trace_dict['roi_trace_h5'], 'r+') as hf:
hf.create_dataset('r', data=r, compression=compression)
logger.info('Calculating dF/F')
dff_traces = dff.calculate_dff(raw_processed_traces)
logger.info('Saving dF/F traces.')
save_roi_dataset(dff_traces, roi_trace_dict['roi_trace_dff_h5'], roi_ids, excl_dict=excl_dict, replace=True, compression=compression)
return<|docstring|>create_traces_from_masks(datadir, sessid)
Extracts traces from masks, applies correction (neuropil traces, demixed
traces, corrected traces, dF/F traces) and saves them.
WARNING: Will replace any existing files.
Required args:
- datadir (Path): name of the data directory
- sessid (int) : session ID (9 digits)
Optional args:
- runtype (str) : "prod" (production) or "pilot" data
default: "prod"
- h5dir (Path) : path of the h5 data directory. If None,
datadir is used.
default: None
- savedir (Path) : path of the directory in which to save new
files. If None, datadir is used.
default: "trace_proc_dir"
- dendritic (bool) : if True, paths are changed to EXTRACT
version dendritic
default: False
- mask_threshold (float): minimum value in non-boolean mask to
retain a pixel in an ROI mask
default: 0.1
- min_n_pix (int) : minimum number of pixels in an ROI
default: 3
- compression (str) : type of compression to use when saving data
to h5 files (e.g., "gzip")
default: None<|endoftext|> |
2eef3f2fe998868ce47fd63709789d965d6be67ccaedc0989bf9968f75e843db | def differential_to_unicycle(left_motor_velocity: Real, right_motor_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert differential steering commands into unicycle steering commands.\n\n :param left_motor_velocity: [cm / s]\n :param right_motor_velocity: [cm / s]\n :return: A tuple containing (linear_velocity [cm / s], angular_velocity [deg / s])\n '
linear_velocity = ((left_motor_velocity + right_motor_velocity) / 2)
angular_velocity = ((180 / (pi * WHEEL_TRACK_CM)) * (right_motor_velocity - left_motor_velocity))
return (linear_velocity, angular_velocity) | Convert differential steering commands into unicycle steering commands.
:param left_motor_velocity: [cm / s]
:param right_motor_velocity: [cm / s]
:return: A tuple containing (linear_velocity [cm / s], angular_velocity [deg / s]) | src/python/drive_motor_control.py | differential_to_unicycle | SaltyHash/BWO | 2 | python | def differential_to_unicycle(left_motor_velocity: Real, right_motor_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert differential steering commands into unicycle steering commands.\n\n :param left_motor_velocity: [cm / s]\n :param right_motor_velocity: [cm / s]\n :return: A tuple containing (linear_velocity [cm / s], angular_velocity [deg / s])\n '
linear_velocity = ((left_motor_velocity + right_motor_velocity) / 2)
angular_velocity = ((180 / (pi * WHEEL_TRACK_CM)) * (right_motor_velocity - left_motor_velocity))
return (linear_velocity, angular_velocity) | def differential_to_unicycle(left_motor_velocity: Real, right_motor_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert differential steering commands into unicycle steering commands.\n\n :param left_motor_velocity: [cm / s]\n :param right_motor_velocity: [cm / s]\n :return: A tuple containing (linear_velocity [cm / s], angular_velocity [deg / s])\n '
linear_velocity = ((left_motor_velocity + right_motor_velocity) / 2)
angular_velocity = ((180 / (pi * WHEEL_TRACK_CM)) * (right_motor_velocity - left_motor_velocity))
return (linear_velocity, angular_velocity)<|docstring|>Convert differential steering commands into unicycle steering commands.
:param left_motor_velocity: [cm / s]
:param right_motor_velocity: [cm / s]
:return: A tuple containing (linear_velocity [cm / s], angular_velocity [deg / s])<|endoftext|> |
f85c5b8ab2a4426d89334d220f54e78b4f4bc1d2e9a3c259e4f2d7fd9605bcca | def unicycle_to_differential(linear_velocity: Real, angular_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert unicycle steering commands into differential steering commands.\n\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n :return: A tuple containing (left_motor_velocity, right_motor_velocity) [cm / s]\n '
angular_velocity = ((pi * WHEEL_TRACK_CM) * (angular_velocity / 360))
left_motor_velocity = (linear_velocity - angular_velocity)
right_motor_velocity = (linear_velocity + angular_velocity)
return (left_motor_velocity, right_motor_velocity) | Convert unicycle steering commands into differential steering commands.
:param linear_velocity: How fast the robot should travel [cm / s]
:param angular_velocity: How fast the robot should rotate [deg / s]
:return: A tuple containing (left_motor_velocity, right_motor_velocity) [cm / s] | src/python/drive_motor_control.py | unicycle_to_differential | SaltyHash/BWO | 2 | python | def unicycle_to_differential(linear_velocity: Real, angular_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert unicycle steering commands into differential steering commands.\n\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n :return: A tuple containing (left_motor_velocity, right_motor_velocity) [cm / s]\n '
angular_velocity = ((pi * WHEEL_TRACK_CM) * (angular_velocity / 360))
left_motor_velocity = (linear_velocity - angular_velocity)
right_motor_velocity = (linear_velocity + angular_velocity)
return (left_motor_velocity, right_motor_velocity) | def unicycle_to_differential(linear_velocity: Real, angular_velocity: Real) -> Tuple[(Real, Real)]:
'\n Convert unicycle steering commands into differential steering commands.\n\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n :return: A tuple containing (left_motor_velocity, right_motor_velocity) [cm / s]\n '
angular_velocity = ((pi * WHEEL_TRACK_CM) * (angular_velocity / 360))
left_motor_velocity = (linear_velocity - angular_velocity)
right_motor_velocity = (linear_velocity + angular_velocity)
return (left_motor_velocity, right_motor_velocity)<|docstring|>Convert unicycle steering commands into differential steering commands.
:param linear_velocity: How fast the robot should travel [cm / s]
:param angular_velocity: How fast the robot should rotate [deg / s]
:return: A tuple containing (left_motor_velocity, right_motor_velocity) [cm / s]<|endoftext|> |
0815e55d27f331a30ab6180af0513a6c627e073033672d11a849b2d5caecf1e2 | def ticks_to_distance(ticks: int) -> Real:
'\n Convert encoder ticks into distance [cm].\n\n :param ticks: Number of encoder ticks.\n :return: Distance that number of ticks represents [cm].\n '
return (ticks * WHEEL_CM_PER_TICK) | Convert encoder ticks into distance [cm].
:param ticks: Number of encoder ticks.
:return: Distance that number of ticks represents [cm]. | src/python/drive_motor_control.py | ticks_to_distance | SaltyHash/BWO | 2 | python | def ticks_to_distance(ticks: int) -> Real:
'\n Convert encoder ticks into distance [cm].\n\n :param ticks: Number of encoder ticks.\n :return: Distance that number of ticks represents [cm].\n '
return (ticks * WHEEL_CM_PER_TICK) | def ticks_to_distance(ticks: int) -> Real:
'\n Convert encoder ticks into distance [cm].\n\n :param ticks: Number of encoder ticks.\n :return: Distance that number of ticks represents [cm].\n '
return (ticks * WHEEL_CM_PER_TICK)<|docstring|>Convert encoder ticks into distance [cm].
:param ticks: Number of encoder ticks.
:return: Distance that number of ticks represents [cm].<|endoftext|> |
78bcf9c0a206e7e608e920b41edcc5d0357a76b2eb623549f1e9dc62fc5edd05 | def distance_to_ticks(distance: Real) -> int:
'\n Convert distance [cm] into encoder ticks.\n\n :param distance: [cm]\n :return: Number of encoder ticks (rounded) that distance represents.\n '
return int(round((distance * WHEEL_TICK_PER_CM))) | Convert distance [cm] into encoder ticks.
:param distance: [cm]
:return: Number of encoder ticks (rounded) that distance represents. | src/python/drive_motor_control.py | distance_to_ticks | SaltyHash/BWO | 2 | python | def distance_to_ticks(distance: Real) -> int:
'\n Convert distance [cm] into encoder ticks.\n\n :param distance: [cm]\n :return: Number of encoder ticks (rounded) that distance represents.\n '
return int(round((distance * WHEEL_TICK_PER_CM))) | def distance_to_ticks(distance: Real) -> int:
'\n Convert distance [cm] into encoder ticks.\n\n :param distance: [cm]\n :return: Number of encoder ticks (rounded) that distance represents.\n '
return int(round((distance * WHEEL_TICK_PER_CM)))<|docstring|>Convert distance [cm] into encoder ticks.
:param distance: [cm]
:return: Number of encoder ticks (rounded) that distance represents.<|endoftext|> |
53cb09bc40c94822bd5d0d1bbdcaed76275daae609eae5ba209ea24075d4a1e8 | def set_acceleration(self, acceleration: int=8000) -> None:
'\n Sets the controller acceleration.\n\n :param acceleration: How quickly the controller should accelerate to a new velocity [ticks / s^2].\n If set to 0, acceleration is instant.\n '
if (acceleration < 0):
raise ValueError(f'Acceleration must be >= 0. Given acceleration: {acceleration}')
self._send_command(self._SET_ACCELERATION_SEND_STRUCT.pack(self._SET_ACCELERATION_COMMAND, acceleration)) | Sets the controller acceleration.
:param acceleration: How quickly the controller should accelerate to a new velocity [ticks / s^2].
If set to 0, acceleration is instant. | src/python/drive_motor_control.py | set_acceleration | SaltyHash/BWO | 2 | python | def set_acceleration(self, acceleration: int=8000) -> None:
'\n Sets the controller acceleration.\n\n :param acceleration: How quickly the controller should accelerate to a new velocity [ticks / s^2].\n If set to 0, acceleration is instant.\n '
if (acceleration < 0):
raise ValueError(f'Acceleration must be >= 0. Given acceleration: {acceleration}')
self._send_command(self._SET_ACCELERATION_SEND_STRUCT.pack(self._SET_ACCELERATION_COMMAND, acceleration)) | def set_acceleration(self, acceleration: int=8000) -> None:
'\n Sets the controller acceleration.\n\n :param acceleration: How quickly the controller should accelerate to a new velocity [ticks / s^2].\n If set to 0, acceleration is instant.\n '
if (acceleration < 0):
raise ValueError(f'Acceleration must be >= 0. Given acceleration: {acceleration}')
self._send_command(self._SET_ACCELERATION_SEND_STRUCT.pack(self._SET_ACCELERATION_COMMAND, acceleration))<|docstring|>Sets the controller acceleration.
:param acceleration: How quickly the controller should accelerate to a new velocity [ticks / s^2].
If set to 0, acceleration is instant.<|endoftext|> |
311431f668b2568b558829ff480f9b1e85a15d913e7f4eeba69e5e0548db4abe | def set_pid_tunings(self, p: float=0.05, i: float=0.5, d: float=0.0) -> None:
'\n Good default tunings: ``(0.05, 0.5, 0)``\n '
if ((p < 0) or (i < 0) or (d < 0)):
raise ValueError(f'All tunings must be non-negative. Given tunings: p={p}, i={i}, d={d}')
self._send_command(self._SET_PID_TUNINGS_SEND_STRUCT.pack(self._SET_PID_TUNINGS_COMMAND, p, i, d)) | Good default tunings: ``(0.05, 0.5, 0)`` | src/python/drive_motor_control.py | set_pid_tunings | SaltyHash/BWO | 2 | python | def set_pid_tunings(self, p: float=0.05, i: float=0.5, d: float=0.0) -> None:
'\n \n '
if ((p < 0) or (i < 0) or (d < 0)):
raise ValueError(f'All tunings must be non-negative. Given tunings: p={p}, i={i}, d={d}')
self._send_command(self._SET_PID_TUNINGS_SEND_STRUCT.pack(self._SET_PID_TUNINGS_COMMAND, p, i, d)) | def set_pid_tunings(self, p: float=0.05, i: float=0.5, d: float=0.0) -> None:
'\n \n '
if ((p < 0) or (i < 0) or (d < 0)):
raise ValueError(f'All tunings must be non-negative. Given tunings: p={p}, i={i}, d={d}')
self._send_command(self._SET_PID_TUNINGS_SEND_STRUCT.pack(self._SET_PID_TUNINGS_COMMAND, p, i, d))<|docstring|>Good default tunings: ``(0.05, 0.5, 0)``<|endoftext|> |
7e0e5c88882827297879596eab4734386c099ce262d1a13268748346b2999e95 | def set_velocity_unicycle(self, linear_velocity: Real, angular_velocity: Real) -> DriveMotorState:
'\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n '
return self.set_velocity_differential(*unicycle_to_differential(linear_velocity, angular_velocity), distance_unit='cm') | :param linear_velocity: How fast the robot should travel [cm / s]
:param angular_velocity: How fast the robot should rotate [deg / s] | src/python/drive_motor_control.py | set_velocity_unicycle | SaltyHash/BWO | 2 | python | def set_velocity_unicycle(self, linear_velocity: Real, angular_velocity: Real) -> DriveMotorState:
'\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n '
return self.set_velocity_differential(*unicycle_to_differential(linear_velocity, angular_velocity), distance_unit='cm') | def set_velocity_unicycle(self, linear_velocity: Real, angular_velocity: Real) -> DriveMotorState:
'\n :param linear_velocity: How fast the robot should travel [cm / s]\n :param angular_velocity: How fast the robot should rotate [deg / s]\n '
return self.set_velocity_differential(*unicycle_to_differential(linear_velocity, angular_velocity), distance_unit='cm')<|docstring|>:param linear_velocity: How fast the robot should travel [cm / s]
:param angular_velocity: How fast the robot should rotate [deg / s]<|endoftext|> |
8b1d35c7398d0f0a5210eee469fd08b76b277e80be9e0c67dceb27a07f368e3e | def _send_command(self, data: bytes) -> bytes:
'\n Sends the command data, receives a response packet, makes sure the 0th byte of the response is an ACK (i.e.\n that it matches the 0th byte of the data, which is the command byte), and then returns the part of the response\n that comes after the ACK (0th) byte.\n :param data: The command data to send.\n :return: The response bytes, after the ACK (0th) byte.\n :raises DriveMotorException: if timed out waiting to receive an ACK from the controller, or received ACK was not\n the expected value.\n '
if (not data):
raise ValueError('data must be given')
response = self._packets.write_then_read(data)
expected_ack = data[0:1]
if (response is None):
raise DriveMotorException('Timed out waiting to receive ACK from the controller.')
received_ack = response[0:1]
if (received_ack != expected_ack):
raise DriveMotorException(f'Did not receive expected ACK from the controller; expected: {expected_ack}; received: {received_ack}.')
return response[1:] | Sends the command data, receives a response packet, makes sure the 0th byte of the response is an ACK (i.e.
that it matches the 0th byte of the data, which is the command byte), and then returns the part of the response
that comes after the ACK (0th) byte.
:param data: The command data to send.
:return: The response bytes, after the ACK (0th) byte.
:raises DriveMotorException: if timed out waiting to receive an ACK from the controller, or received ACK was not
the expected value. | src/python/drive_motor_control.py | _send_command | SaltyHash/BWO | 2 | python | def _send_command(self, data: bytes) -> bytes:
'\n Sends the command data, receives a response packet, makes sure the 0th byte of the response is an ACK (i.e.\n that it matches the 0th byte of the data, which is the command byte), and then returns the part of the response\n that comes after the ACK (0th) byte.\n :param data: The command data to send.\n :return: The response bytes, after the ACK (0th) byte.\n :raises DriveMotorException: if timed out waiting to receive an ACK from the controller, or received ACK was not\n the expected value.\n '
if (not data):
raise ValueError('data must be given')
response = self._packets.write_then_read(data)
expected_ack = data[0:1]
if (response is None):
raise DriveMotorException('Timed out waiting to receive ACK from the controller.')
received_ack = response[0:1]
if (received_ack != expected_ack):
raise DriveMotorException(f'Did not receive expected ACK from the controller; expected: {expected_ack}; received: {received_ack}.')
return response[1:] | def _send_command(self, data: bytes) -> bytes:
'\n Sends the command data, receives a response packet, makes sure the 0th byte of the response is an ACK (i.e.\n that it matches the 0th byte of the data, which is the command byte), and then returns the part of the response\n that comes after the ACK (0th) byte.\n :param data: The command data to send.\n :return: The response bytes, after the ACK (0th) byte.\n :raises DriveMotorException: if timed out waiting to receive an ACK from the controller, or received ACK was not\n the expected value.\n '
if (not data):
raise ValueError('data must be given')
response = self._packets.write_then_read(data)
expected_ack = data[0:1]
if (response is None):
raise DriveMotorException('Timed out waiting to receive ACK from the controller.')
received_ack = response[0:1]
if (received_ack != expected_ack):
raise DriveMotorException(f'Did not receive expected ACK from the controller; expected: {expected_ack}; received: {received_ack}.')
return response[1:]<|docstring|>Sends the command data, receives a response packet, makes sure the 0th byte of the response is an ACK (i.e.
that it matches the 0th byte of the data, which is the command byte), and then returns the part of the response
that comes after the ACK (0th) byte.
:param data: The command data to send.
:return: The response bytes, after the ACK (0th) byte.
:raises DriveMotorException: if timed out waiting to receive an ACK from the controller, or received ACK was not
the expected value.<|endoftext|> |
515632bcd3e3496e68a672451acd6dc09c715628d360a5f1abfd13549fa4e6f1 | def _get_task_config(product, task):
'Get the effective telstate config for a task.\n\n This also looks for nodes whose name indicates that they are parents\n (and hence whose telstate config will be picked up by\n katsdpservices.argparse).\n '
by_name = {t.logical_node.name: t for t in product.physical_graph}
conf = {}
name_parts = task.logical_node.name.split('.')
for i in range(1, (len(name_parts) + 1)):
name = '.'.join(name_parts[:i])
try:
sub_conf = by_name[name].task_config
except (KeyError, AttributeError):
pass
else:
conf.update(sub_conf)
return conf | Get the effective telstate config for a task.
This also looks for nodes whose name indicates that they are parents
(and hence whose telstate config will be picked up by
katsdpservices.argparse). | katsdpcontroller/dashboard.py | _get_task_config | ska-sa/katsdpcontroller | 0 | python | def _get_task_config(product, task):
'Get the effective telstate config for a task.\n\n This also looks for nodes whose name indicates that they are parents\n (and hence whose telstate config will be picked up by\n katsdpservices.argparse).\n '
by_name = {t.logical_node.name: t for t in product.physical_graph}
conf = {}
name_parts = task.logical_node.name.split('.')
for i in range(1, (len(name_parts) + 1)):
name = '.'.join(name_parts[:i])
try:
sub_conf = by_name[name].task_config
except (KeyError, AttributeError):
pass
else:
conf.update(sub_conf)
return conf | def _get_task_config(product, task):
'Get the effective telstate config for a task.\n\n This also looks for nodes whose name indicates that they are parents\n (and hence whose telstate config will be picked up by\n katsdpservices.argparse).\n '
by_name = {t.logical_node.name: t for t in product.physical_graph}
conf = {}
name_parts = task.logical_node.name.split('.')
for i in range(1, (len(name_parts) + 1)):
name = '.'.join(name_parts[:i])
try:
sub_conf = by_name[name].task_config
except (KeyError, AttributeError):
pass
else:
conf.update(sub_conf)
return conf<|docstring|>Get the effective telstate config for a task.
This also looks for nodes whose name indicates that they are parents
(and hence whose telstate config will be picked up by
katsdpservices.argparse).<|endoftext|> |
433b430cdafe1749f18a608da6987db91b9a3da9be0152cb47e631f9961cc34b | @property
def instance(self) -> int:
'Return Instance.'
return self.data.get('Instance') | Return Instance. | openzwavemqtt/models/node_instance.py | instance | quinnhosler/python-openzwave-mqtt | 0 | python | @property
def instance(self) -> int:
return self.data.get('Instance') | @property
def instance(self) -> int:
return self.data.get('Instance')<|docstring|>Return Instance.<|endoftext|> |
6c39e8e4e5bf5aed107e403cd4610ad64cf70ac8e132e79e1cfef9bbb1a8c29c | @property
def time_stamp(self) -> int:
'Return TimeStamp.'
return self.data.get('TimeStamp') | Return TimeStamp. | openzwavemqtt/models/node_instance.py | time_stamp | quinnhosler/python-openzwave-mqtt | 0 | python | @property
def time_stamp(self) -> int:
return self.data.get('TimeStamp') | @property
def time_stamp(self) -> int:
return self.data.get('TimeStamp')<|docstring|>Return TimeStamp.<|endoftext|> |
375a1d7f6f34ea7d7745d50730c2f655a37a087fd9c1e163147391ac44c20b2f | def create_collections(self):
'Create collections that Node supports.'
return {'commandclass': ItemCollection(OZWCommandClass)} | Create collections that Node supports. | openzwavemqtt/models/node_instance.py | create_collections | quinnhosler/python-openzwave-mqtt | 0 | python | def create_collections(self):
return {'commandclass': ItemCollection(OZWCommandClass)} | def create_collections(self):
return {'commandclass': ItemCollection(OZWCommandClass)}<|docstring|>Create collections that Node supports.<|endoftext|> |
3b08a8b8fab04cf37e3c6c3b3444e1b439d6705b0b6814a7a12528789cf38beb | def fpicker(artist, event):
'\n an artist picker that works for clicks outside the axes. ie. artist\n that are not clipped\n '
logger.debug('fpicker: {}', artist)
if (event.button != 1):
logger.debug('wrong button!')
return (False, {})
tf = artist.contains(event)
logger.debug('fpicker: artist.contains(event) {}', tf)
return tf | an artist picker that works for clicks outside the axes. ie. artist
that are not clipped | src/scrawl/moves/machinery.py | fpicker | astromancer/graphical | 0 | python | def fpicker(artist, event):
'\n an artist picker that works for clicks outside the axes. ie. artist\n that are not clipped\n '
logger.debug('fpicker: {}', artist)
if (event.button != 1):
logger.debug('wrong button!')
return (False, {})
tf = artist.contains(event)
logger.debug('fpicker: artist.contains(event) {}', tf)
return tf | def fpicker(artist, event):
'\n an artist picker that works for clicks outside the axes. ie. artist\n that are not clipped\n '
logger.debug('fpicker: {}', artist)
if (event.button != 1):
logger.debug('wrong button!')
return (False, {})
tf = artist.contains(event)
logger.debug('fpicker: artist.contains(event) {}', tf)
return tf<|docstring|>an artist picker that works for clicks outside the axes. ie. artist
that are not clipped<|endoftext|> |
4b22b48a36010a994befd5ad8b21d3ea96776920e8d6855b0965cd9f5949bfe4 | def add(self, func, *args, **kws):
'\n Add an observer function.\n\n When the artist is moved / picked, *func* will be called with the new\n coordinate position as arguments. *func* should return any artists\n that it changes. These will be drawn if blitting is enabled.\n The signature of *func* is therefor:\n\n draw_list = func(x, y, *args, **kws)`\n\n Parameters\n ----------\n func\n args\n kws\n\n Returns\n -------\n A connection id is returned which can be used to remove the method\n '
if (not callable(func)):
raise TypeError('`func` should be callable')
id_ = next(self.counter)
self.funcs[id_] = (func, args, kws)
self.active[func] = True
return id_ | Add an observer function.
When the artist is moved / picked, *func* will be called with the new
coordinate position as arguments. *func* should return any artists
that it changes. These will be drawn if blitting is enabled.
The signature of *func* is therefor:
draw_list = func(x, y, *args, **kws)`
Parameters
----------
func
args
kws
Returns
-------
A connection id is returned which can be used to remove the method | src/scrawl/moves/machinery.py | add | astromancer/graphical | 0 | python | def add(self, func, *args, **kws):
'\n Add an observer function.\n\n When the artist is moved / picked, *func* will be called with the new\n coordinate position as arguments. *func* should return any artists\n that it changes. These will be drawn if blitting is enabled.\n The signature of *func* is therefor:\n\n draw_list = func(x, y, *args, **kws)`\n\n Parameters\n ----------\n func\n args\n kws\n\n Returns\n -------\n A connection id is returned which can be used to remove the method\n '
if (not callable(func)):
raise TypeError('`func` should be callable')
id_ = next(self.counter)
self.funcs[id_] = (func, args, kws)
self.active[func] = True
return id_ | def add(self, func, *args, **kws):
'\n Add an observer function.\n\n When the artist is moved / picked, *func* will be called with the new\n coordinate position as arguments. *func* should return any artists\n that it changes. These will be drawn if blitting is enabled.\n The signature of *func* is therefor:\n\n draw_list = func(x, y, *args, **kws)`\n\n Parameters\n ----------\n func\n args\n kws\n\n Returns\n -------\n A connection id is returned which can be used to remove the method\n '
if (not callable(func)):
raise TypeError('`func` should be callable')
id_ = next(self.counter)
self.funcs[id_] = (func, args, kws)
self.active[func] = True
return id_<|docstring|>Add an observer function.
When the artist is moved / picked, *func* will be called with the new
coordinate position as arguments. *func* should return any artists
that it changes. These will be drawn if blitting is enabled.
The signature of *func* is therefor:
draw_list = func(x, y, *args, **kws)`
Parameters
----------
func
args
kws
Returns
-------
A connection id is returned which can be used to remove the method<|endoftext|> |
e116d120975ef21e7da7e0684a97adc59997f713fbcf4107fe5fa3ef5cc37726 | def activate(self, fun_or_id):
"\n Reactivate a non-active observer. This method is useful for toggling\n the active state of an observer function without removing and re-adding\n it (and it's parameters) to the dict of functions. The function will use\n parameters and keywords (if any) that were initially passed when it was\n added.\n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n "
self._set_active(fun_or_id, True) | Reactivate a non-active observer. This method is useful for toggling
the active state of an observer function without removing and re-adding
it (and it's parameters) to the dict of functions. The function will use
parameters and keywords (if any) that were initially passed when it was
added.
Parameters
----------
fun_or_id: callable, int
The function (or its identifier) that will be activated | src/scrawl/moves/machinery.py | activate | astromancer/graphical | 0 | python | def activate(self, fun_or_id):
"\n Reactivate a non-active observer. This method is useful for toggling\n the active state of an observer function without removing and re-adding\n it (and it's parameters) to the dict of functions. The function will use\n parameters and keywords (if any) that were initially passed when it was\n added.\n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n "
self._set_active(fun_or_id, True) | def activate(self, fun_or_id):
"\n Reactivate a non-active observer. This method is useful for toggling\n the active state of an observer function without removing and re-adding\n it (and it's parameters) to the dict of functions. The function will use\n parameters and keywords (if any) that were initially passed when it was\n added.\n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n "
self._set_active(fun_or_id, True)<|docstring|>Reactivate a non-active observer. This method is useful for toggling
the active state of an observer function without removing and re-adding
it (and it's parameters) to the dict of functions. The function will use
parameters and keywords (if any) that were initially passed when it was
added.
Parameters
----------
fun_or_id: callable, int
The function (or its identifier) that will be activated<|endoftext|> |
6ccfb9e9fe5bbb70d78f7cfb2eba305d7fe5dc0defde98022355ee6b665e8e0f | def deactivate(self, fun_or_id):
'\n Deactivate an active observer. \n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n '
self._set_active(fun_or_id, False) | Deactivate an active observer.
Parameters
----------
fun_or_id: callable, int
The function (or its identifier) that will be activated | src/scrawl/moves/machinery.py | deactivate | astromancer/graphical | 0 | python | def deactivate(self, fun_or_id):
'\n Deactivate an active observer. \n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n '
self._set_active(fun_or_id, False) | def deactivate(self, fun_or_id):
'\n Deactivate an active observer. \n\n Parameters\n ----------\n fun_or_id: callable, int\n The function (or its identifier) that will be activated \n '
self._set_active(fun_or_id, False)<|docstring|>Deactivate an active observer.
Parameters
----------
fun_or_id: callable, int
The function (or its identifier) that will be activated<|endoftext|> |
0d057793d0891883843d54ffb8669cc177552cdb1a157463242a92c85c609bff | def __call__(self, x, y):
'\n Run all active observers for current data point\n\n Parameters\n ----------\n x, y\n\n Returns\n -------\n Artists that need to be drawn\n '
artists = []
for (_, (func, args, kws)) in self.funcs.items():
if (not self.active[func]):
continue
try:
art = func(x, y, *args, **kws)
self.logger.opt(lazy=True).debug('observer: {0[0]:}({0[1]:.3f}, {0[2]:.3f}): {0[3]:}', (lambda : (func.__name__, x, y, art_summary(art))))
if isinstance(art, (list, tuple)):
artists.extend(art)
elif (art is not None):
artists.append(art)
except Exception:
self.logger.exception('Observers error.')
return artists | Run all active observers for current data point
Parameters
----------
x, y
Returns
-------
Artists that need to be drawn | src/scrawl/moves/machinery.py | __call__ | astromancer/graphical | 0 | python | def __call__(self, x, y):
'\n Run all active observers for current data point\n\n Parameters\n ----------\n x, y\n\n Returns\n -------\n Artists that need to be drawn\n '
artists = []
for (_, (func, args, kws)) in self.funcs.items():
if (not self.active[func]):
continue
try:
art = func(x, y, *args, **kws)
self.logger.opt(lazy=True).debug('observer: {0[0]:}({0[1]:.3f}, {0[2]:.3f}): {0[3]:}', (lambda : (func.__name__, x, y, art_summary(art))))
if isinstance(art, (list, tuple)):
artists.extend(art)
elif (art is not None):
artists.append(art)
except Exception:
self.logger.exception('Observers error.')
return artists | def __call__(self, x, y):
'\n Run all active observers for current data point\n\n Parameters\n ----------\n x, y\n\n Returns\n -------\n Artists that need to be drawn\n '
artists = []
for (_, (func, args, kws)) in self.funcs.items():
if (not self.active[func]):
continue
try:
art = func(x, y, *args, **kws)
self.logger.opt(lazy=True).debug('observer: {0[0]:}({0[1]:.3f}, {0[2]:.3f}): {0[3]:}', (lambda : (func.__name__, x, y, art_summary(art))))
if isinstance(art, (list, tuple)):
artists.extend(art)
elif (art is not None):
artists.append(art)
except Exception:
self.logger.exception('Observers error.')
return artists<|docstring|>Run all active observers for current data point
Parameters
----------
x, y
Returns
-------
Artists that need to be drawn<|endoftext|> |
178ea54b772e37c97b3c0b1fd6a072ebdb7704d17a149919c57aa86f0b64959f | def __init__(self, artist, offset=(0.0, 0.0), annotate=False, haunted=False, trapped=False, **kws):
'\n\n Parameters\n ----------\n artist\n offset\n annotate\n haunted\n trapped\n kws\n '
self.artist = artist
self._original_transform = artist.get_transform()
self.clipped = False
self.trapped = trapped
(self._xmin, self._xmax) = (np.nan, np.nan)
(self._ymin, self._ymax) = (np.nan, np.nan)
self._offset = np.array(offset)
self.ref_point = np.array([artist.get_xdata()[0], artist.get_ydata()[0]])
self.annotated = annotate
self.ghost = None
if (not artist.get_picker()):
artist.set_pickradius(10)
artist.set_picker(True)
self.linked = []
self.on_picked = Observers()
self.on_move = Observers()
self.on_release = Observers()
self.on_move.add(self.move_to)
self.on_release.add(self.update)
ax = artist.axes
if self.annotated:
self.text_trans = btf(ax.transAxes, ax.transData)
self.ytxt = np.mean(artist.get_ydata())
self.annotation = ax.text(1.005, self.ytxt, '')
if haunted:
self.haunt()
self._locked_at = np.full(2, np.nan) | Parameters
----------
artist
offset
annotate
haunted
trapped
kws | src/scrawl/moves/machinery.py | __init__ | astromancer/graphical | 0 | python | def __init__(self, artist, offset=(0.0, 0.0), annotate=False, haunted=False, trapped=False, **kws):
'\n\n Parameters\n ----------\n artist\n offset\n annotate\n haunted\n trapped\n kws\n '
self.artist = artist
self._original_transform = artist.get_transform()
self.clipped = False
self.trapped = trapped
(self._xmin, self._xmax) = (np.nan, np.nan)
(self._ymin, self._ymax) = (np.nan, np.nan)
self._offset = np.array(offset)
self.ref_point = np.array([artist.get_xdata()[0], artist.get_ydata()[0]])
self.annotated = annotate
self.ghost = None
if (not artist.get_picker()):
artist.set_pickradius(10)
artist.set_picker(True)
self.linked = []
self.on_picked = Observers()
self.on_move = Observers()
self.on_release = Observers()
self.on_move.add(self.move_to)
self.on_release.add(self.update)
ax = artist.axes
if self.annotated:
self.text_trans = btf(ax.transAxes, ax.transData)
self.ytxt = np.mean(artist.get_ydata())
self.annotation = ax.text(1.005, self.ytxt, )
if haunted:
self.haunt()
self._locked_at = np.full(2, np.nan) | def __init__(self, artist, offset=(0.0, 0.0), annotate=False, haunted=False, trapped=False, **kws):
'\n\n Parameters\n ----------\n artist\n offset\n annotate\n haunted\n trapped\n kws\n '
self.artist = artist
self._original_transform = artist.get_transform()
self.clipped = False
self.trapped = trapped
(self._xmin, self._xmax) = (np.nan, np.nan)
(self._ymin, self._ymax) = (np.nan, np.nan)
self._offset = np.array(offset)
self.ref_point = np.array([artist.get_xdata()[0], artist.get_ydata()[0]])
self.annotated = annotate
self.ghost = None
if (not artist.get_picker()):
artist.set_pickradius(10)
artist.set_picker(True)
self.linked = []
self.on_picked = Observers()
self.on_move = Observers()
self.on_release = Observers()
self.on_move.add(self.move_to)
self.on_release.add(self.update)
ax = artist.axes
if self.annotated:
self.text_trans = btf(ax.transAxes, ax.transData)
self.ytxt = np.mean(artist.get_ydata())
self.annotation = ax.text(1.005, self.ytxt, )
if haunted:
self.haunt()
self._locked_at = np.full(2, np.nan)<|docstring|>Parameters
----------
artist
offset
annotate
haunted
trapped
kws<|endoftext|> |
b422ce6a024ccf778aaf4b4cafebfade9a96dcf8eb9b84c81da8d778102d96fc | def lock(self, which):
'Lock movement for x or y coordinate'
ix = 'xy'.index(which.lower())
self._locked_at[ix] = self.offset[ix] | Lock movement for x or y coordinate | src/scrawl/moves/machinery.py | lock | astromancer/graphical | 0 | python | def lock(self, which):
ix = 'xy'.index(which.lower())
self._locked_at[ix] = self.offset[ix] | def lock(self, which):
ix = 'xy'.index(which.lower())
self._locked_at[ix] = self.offset[ix]<|docstring|>Lock movement for x or y coordinate<|endoftext|> |
4e8cde462ed20e10b654d0bcc4068670ea3b442021a9803e3c33bb91a46c350b | def free(self, which):
'Release movement lock for x or y coordinate'
ix = 'xy'.index(which.lower())
self._locked_at[ix] = None | Release movement lock for x or y coordinate | src/scrawl/moves/machinery.py | free | astromancer/graphical | 0 | python | def free(self, which):
ix = 'xy'.index(which.lower())
self._locked_at[ix] = None | def free(self, which):
ix = 'xy'.index(which.lower())
self._locked_at[ix] = None<|docstring|>Release movement lock for x or y coordinate<|endoftext|> |
2c73bcb4dbe30877c6f87bdd8064c309948fcc6820da8979f9fc3cbeadc44f14 | def lock_x(self):
'Lock x coordinate at current position'
self.lock('x') | Lock x coordinate at current position | src/scrawl/moves/machinery.py | lock_x | astromancer/graphical | 0 | python | def lock_x(self):
self.lock('x') | def lock_x(self):
self.lock('x')<|docstring|>Lock x coordinate at current position<|endoftext|> |
7a247ee9882bba03003306ec8a86912f3b6a60f1214c13038758a046f191f72e | def free_x(self):
'Release x coordinate lock'
self.free('x') | Release x coordinate lock | src/scrawl/moves/machinery.py | free_x | astromancer/graphical | 0 | python | def free_x(self):
self.free('x') | def free_x(self):
self.free('x')<|docstring|>Release x coordinate lock<|endoftext|> |
fd16957a1253447eed5b6d78bc8bb6dd40032c96332712ffcb9e59e79d8b359c | def lock_y(self):
'Lock y coordinate at current position'
self.lock('y') | Lock y coordinate at current position | src/scrawl/moves/machinery.py | lock_y | astromancer/graphical | 0 | python | def lock_y(self):
self.lock('y') | def lock_y(self):
self.lock('y')<|docstring|>Lock y coordinate at current position<|endoftext|> |
83852913dcf20b5f16512673a0d4bade61b77527de1db9df5a23cd72de81af45 | def free_y(self):
'Release y coordinate lock'
self.free('y') | Release y coordinate lock | src/scrawl/moves/machinery.py | free_y | astromancer/graphical | 0 | python | def free_y(self):
self.free('y') | def free_y(self):
self.free('y')<|docstring|>Release y coordinate lock<|endoftext|> |
d038a84908b912d67cb42b6d468f05d45767bfda9582338f90a8fd9c653d9a9e | def limit(self, xb=None, yb=None):
'\n Restrict movement of the artist to a particular interval / box\n\n Parameters\n ----------\n xb\n yb\n\n Returns\n -------\n\n '
if ((xb is None) and (yb is None)):
raise ValueError('Need either x, or y limits (or both)')
if (xb is not None):
(self._xmin, self._xmax) = np.sort(xb)
if (yb is not None):
(self._ymin, self._ymax) = np.sort(yb) | Restrict movement of the artist to a particular interval / box
Parameters
----------
xb
yb
Returns
------- | src/scrawl/moves/machinery.py | limit | astromancer/graphical | 0 | python | def limit(self, xb=None, yb=None):
'\n Restrict movement of the artist to a particular interval / box\n\n Parameters\n ----------\n xb\n yb\n\n Returns\n -------\n\n '
if ((xb is None) and (yb is None)):
raise ValueError('Need either x, or y limits (or both)')
if (xb is not None):
(self._xmin, self._xmax) = np.sort(xb)
if (yb is not None):
(self._ymin, self._ymax) = np.sort(yb) | def limit(self, xb=None, yb=None):
'\n Restrict movement of the artist to a particular interval / box\n\n Parameters\n ----------\n xb\n yb\n\n Returns\n -------\n\n '
if ((xb is None) and (yb is None)):
raise ValueError('Need either x, or y limits (or both)')
if (xb is not None):
(self._xmin, self._xmax) = np.sort(xb)
if (yb is not None):
(self._ymin, self._ymax) = np.sort(yb)<|docstring|>Restrict movement of the artist to a particular interval / box
Parameters
----------
xb
yb
Returns
-------<|endoftext|> |
866fcd7d8ca9e491212d0c22bda3653ce11fb159f2f7900313f6d9b3dab6ada3 | def link(self, *artists):
'\n Link another artist or artist to this one to make them co-moving\n\n Parameters\n ----------\n artists: a sequence of artists that will be linked to this one\n\n Returns\n -------\n\n '
linked = []
for drg in artists:
if (not isinstance(drg, MotionInterface)):
drg = MotionInterface(drg)
linked.append(drg)
self.linked.extend(linked)
return linked | Link another artist or artist to this one to make them co-moving
Parameters
----------
artists: a sequence of artists that will be linked to this one
Returns
------- | src/scrawl/moves/machinery.py | link | astromancer/graphical | 0 | python | def link(self, *artists):
'\n Link another artist or artist to this one to make them co-moving\n\n Parameters\n ----------\n artists: a sequence of artists that will be linked to this one\n\n Returns\n -------\n\n '
linked = []
for drg in artists:
if (not isinstance(drg, MotionInterface)):
drg = MotionInterface(drg)
linked.append(drg)
self.linked.extend(linked)
return linked | def link(self, *artists):
'\n Link another artist or artist to this one to make them co-moving\n\n Parameters\n ----------\n artists: a sequence of artists that will be linked to this one\n\n Returns\n -------\n\n '
linked = []
for drg in artists:
if (not isinstance(drg, MotionInterface)):
drg = MotionInterface(drg)
linked.append(drg)
self.linked.extend(linked)
return linked<|docstring|>Link another artist or artist to this one to make them co-moving
Parameters
----------
artists: a sequence of artists that will be linked to this one
Returns
-------<|endoftext|> |
f9ba109333b569a2c64cd769267913e1e71585cb093b872cda0c90a30cb50414 | def move_to(self, x, y):
'\n Shift the artist to the position (x, y) in data coordinates. Note\n the input position will be changed before applying the shift if the\n draggable is restricted\n\n Parameters\n ----------\n x\n y\n\n Returns\n -------\n\n '
(x, y) = self.clip(x, y)
offset = np.subtract((x, y), self.ref_point)
self.logger.debug('shifting {} to ({:.3f}, {:.3f})', self, x, y)
self.move_by(offset)
self.logger.debug('offset {} is ({:.3f}, {:.3f})', self, *self.offset)
return self.artist | Shift the artist to the position (x, y) in data coordinates. Note
the input position will be changed before applying the shift if the
draggable is restricted
Parameters
----------
x
y
Returns
------- | src/scrawl/moves/machinery.py | move_to | astromancer/graphical | 0 | python | def move_to(self, x, y):
'\n Shift the artist to the position (x, y) in data coordinates. Note\n the input position will be changed before applying the shift if the\n draggable is restricted\n\n Parameters\n ----------\n x\n y\n\n Returns\n -------\n\n '
(x, y) = self.clip(x, y)
offset = np.subtract((x, y), self.ref_point)
self.logger.debug('shifting {} to ({:.3f}, {:.3f})', self, x, y)
self.move_by(offset)
self.logger.debug('offset {} is ({:.3f}, {:.3f})', self, *self.offset)
return self.artist | def move_to(self, x, y):
'\n Shift the artist to the position (x, y) in data coordinates. Note\n the input position will be changed before applying the shift if the\n draggable is restricted\n\n Parameters\n ----------\n x\n y\n\n Returns\n -------\n\n '
(x, y) = self.clip(x, y)
offset = np.subtract((x, y), self.ref_point)
self.logger.debug('shifting {} to ({:.3f}, {:.3f})', self, x, y)
self.move_by(offset)
self.logger.debug('offset {} is ({:.3f}, {:.3f})', self, *self.offset)
return self.artist<|docstring|>Shift the artist to the position (x, y) in data coordinates. Note
the input position will be changed before applying the shift if the
draggable is restricted
Parameters
----------
x
y
Returns
-------<|endoftext|> |
9cf12c01d4ad9f7b1e73701584d09a5270bf51b7fed96ffbb2247b10661948ff | def move_by(self, offset):
'\n move the artist by offsetting from initial position\n\n Parameters\n ----------\n offset\n\n Returns\n -------\n\n '
self.offset = offset
self.logger.debug('moving: {} {}', self, offset)
offset_trans = Affine2D().translate(*self.offset)
trans = (offset_trans + self._original_transform)
self.artist.set_transform(trans) | move the artist by offsetting from initial position
Parameters
----------
offset
Returns
------- | src/scrawl/moves/machinery.py | move_by | astromancer/graphical | 0 | python | def move_by(self, offset):
'\n move the artist by offsetting from initial position\n\n Parameters\n ----------\n offset\n\n Returns\n -------\n\n '
self.offset = offset
self.logger.debug('moving: {} {}', self, offset)
offset_trans = Affine2D().translate(*self.offset)
trans = (offset_trans + self._original_transform)
self.artist.set_transform(trans) | def move_by(self, offset):
'\n move the artist by offsetting from initial position\n\n Parameters\n ----------\n offset\n\n Returns\n -------\n\n '
self.offset = offset
self.logger.debug('moving: {} {}', self, offset)
offset_trans = Affine2D().translate(*self.offset)
trans = (offset_trans + self._original_transform)
self.artist.set_transform(trans)<|docstring|>move the artist by offsetting from initial position
Parameters
----------
offset
Returns
-------<|endoftext|> |
71d07b4208bf5d11f8a076f39e215c5c3d89609fe2a264ee910a7406f233c3ba | def set_animated(self, b=None):
'set animation state for all linked artists'
if (b is None):
b = (not self.artist.get_animated())
self.artist.set_animated(b)
for drg in self.linked:
drg.set_animated(b) | set animation state for all linked artists | src/scrawl/moves/machinery.py | set_animated | astromancer/graphical | 0 | python | def set_animated(self, b=None):
if (b is None):
b = (not self.artist.get_animated())
self.artist.set_animated(b)
for drg in self.linked:
drg.set_animated(b) | def set_animated(self, b=None):
if (b is None):
b = (not self.artist.get_animated())
self.artist.set_animated(b)
for drg in self.linked:
drg.set_animated(b)<|docstring|>set animation state for all linked artists<|endoftext|> |
91b811665ea2e78218c127deebdd37f3b616923ea3c186672987330cecf39112 | def __init__(self, artists=None, offsets=None, annotate=True, haunted=False, auto_legend=True, use_blit=True, **legendkw):
'\n\n\n Parameters\n ----------\n artists\n offsets\n annotate\n linked\n haunted\n auto_legend\n use_blit\n legendkw\n '
self._ax = None
if (artists is None):
artists = []
self.selection = None
self.ref_point = None
self.up = None
if (offsets is None):
offsets = np.zeros((len(artists), 2))
else:
offsets = np.asarray(offsets)
if (offsets.ndim < 2):
raise ValueError
self._original_offsets = offsets
self.delta = np.zeros(2)
self.draggable = IndexableOrderedDict()
ConnectionMixin.__init__(self)
self._use_blit = use_blit
for (art, offset) in zip(artists, offsets):
self.add_artist(art, offset, annotate, haunted)
self._draw_count = 0
self.background = None | Parameters
----------
artists
offsets
annotate
linked
haunted
auto_legend
use_blit
legendkw | src/scrawl/moves/machinery.py | __init__ | astromancer/graphical | 0 | python | def __init__(self, artists=None, offsets=None, annotate=True, haunted=False, auto_legend=True, use_blit=True, **legendkw):
'\n\n\n Parameters\n ----------\n artists\n offsets\n annotate\n linked\n haunted\n auto_legend\n use_blit\n legendkw\n '
self._ax = None
if (artists is None):
artists = []
self.selection = None
self.ref_point = None
self.up = None
if (offsets is None):
offsets = np.zeros((len(artists), 2))
else:
offsets = np.asarray(offsets)
if (offsets.ndim < 2):
raise ValueError
self._original_offsets = offsets
self.delta = np.zeros(2)
self.draggable = IndexableOrderedDict()
ConnectionMixin.__init__(self)
self._use_blit = use_blit
for (art, offset) in zip(artists, offsets):
self.add_artist(art, offset, annotate, haunted)
self._draw_count = 0
self.background = None | def __init__(self, artists=None, offsets=None, annotate=True, haunted=False, auto_legend=True, use_blit=True, **legendkw):
'\n\n\n Parameters\n ----------\n artists\n offsets\n annotate\n linked\n haunted\n auto_legend\n use_blit\n legendkw\n '
self._ax = None
if (artists is None):
artists = []
self.selection = None
self.ref_point = None
self.up = None
if (offsets is None):
offsets = np.zeros((len(artists), 2))
else:
offsets = np.asarray(offsets)
if (offsets.ndim < 2):
raise ValueError
self._original_offsets = offsets
self.delta = np.zeros(2)
self.draggable = IndexableOrderedDict()
ConnectionMixin.__init__(self)
self._use_blit = use_blit
for (art, offset) in zip(artists, offsets):
self.add_artist(art, offset, annotate, haunted)
self._draw_count = 0
self.background = None<|docstring|>Parameters
----------
artists
offsets
annotate
linked
haunted
auto_legend
use_blit
legendkw<|endoftext|> |
13af0efe347c46900c2cb945b8e6b5ed84f378054a368a6de0c5f67367ac09d7 | def __getitem__(self, key):
'hack for quick indexing'
return self.draggable[key] | hack for quick indexing | src/scrawl/moves/machinery.py | __getitem__ | astromancer/graphical | 0 | python | def __getitem__(self, key):
return self.draggable[key] | def __getitem__(self, key):
return self.draggable[key]<|docstring|>hack for quick indexing<|endoftext|> |
f95660cf19b78a6b9d420a25f45eea07c2e46d194d3f584d9056137a7628698b | def add_artist(self, artist, offset=(0, 0), annotate=True, haunted=False, **kws):
'add a draggable artist'
(key, drg) = self.artist_factory(artist, offset=offset, annotate=annotate, haunted=haunted, **kws)
self.draggable[key] = drg
self._original_offsets = np.r_[('0,2', self._original_offsets, offset)]
return drg | add a draggable artist | src/scrawl/moves/machinery.py | add_artist | astromancer/graphical | 0 | python | def add_artist(self, artist, offset=(0, 0), annotate=True, haunted=False, **kws):
(key, drg) = self.artist_factory(artist, offset=offset, annotate=annotate, haunted=haunted, **kws)
self.draggable[key] = drg
self._original_offsets = np.r_[('0,2', self._original_offsets, offset)]
return drg | def add_artist(self, artist, offset=(0, 0), annotate=True, haunted=False, **kws):
(key, drg) = self.artist_factory(artist, offset=offset, annotate=annotate, haunted=haunted, **kws)
self.draggable[key] = drg
self._original_offsets = np.r_[('0,2', self._original_offsets, offset)]
return drg<|docstring|>add a draggable artist<|endoftext|> |
bd055a2b78392a50949cdce7b488eac3b494d66e2c66f3766f2cb55b2d58f380 | def lock(self, which):
'\n Lock movement along a certain axis so the artist will online move in\n a line.\n '
for (art, drg) in self.draggable.items():
drg.lock(which) | Lock movement along a certain axis so the artist will online move in
a line. | src/scrawl/moves/machinery.py | lock | astromancer/graphical | 0 | python | def lock(self, which):
'\n Lock movement along a certain axis so the artist will online move in\n a line.\n '
for (art, drg) in self.draggable.items():
drg.lock(which) | def lock(self, which):
'\n Lock movement along a certain axis so the artist will online move in\n a line.\n '
for (art, drg) in self.draggable.items():
drg.lock(which)<|docstring|>Lock movement along a certain axis so the artist will online move in
a line.<|endoftext|> |
969d984d0c5839d8ab947c5f515cf0fd16cdbba5f561fa0ed7124854265856de | def free(self, which):
'\n Free motion along an axis for all artists.\n '
for (art, drg) in self.draggable.items():
drg.free(which) | Free motion along an axis for all artists. | src/scrawl/moves/machinery.py | free | astromancer/graphical | 0 | python | def free(self, which):
'\n \n '
for (art, drg) in self.draggable.items():
drg.free(which) | def free(self, which):
'\n \n '
for (art, drg) in self.draggable.items():
drg.free(which)<|docstring|>Free motion along an axis for all artists.<|endoftext|> |
da0d81d813c45a586475e5b2b548e350bfdaa4b5ff8b7622b00c83e798c1e47f | def lock_x(self):
'Lock x position'
self.lock('x') | Lock x position | src/scrawl/moves/machinery.py | lock_x | astromancer/graphical | 0 | python | def lock_x(self):
self.lock('x') | def lock_x(self):
self.lock('x')<|docstring|>Lock x position<|endoftext|> |
22f4837f83bfb89616f6b70ae6a7fa84aa05d917bee954001d8e53c23cf0ca94 | def free_x(self):
'Free x motion'
self.free('x') | Free x motion | src/scrawl/moves/machinery.py | free_x | astromancer/graphical | 0 | python | def free_x(self):
self.free('x') | def free_x(self):
self.free('x')<|docstring|>Free x motion<|endoftext|> |
cc8d248b3b9294cf1abf096ac892888cb0ae413dc61ca0405c8e6d550057424a | def lock_y(self):
'Lock y position'
self.lock('y') | Lock y position | src/scrawl/moves/machinery.py | lock_y | astromancer/graphical | 0 | python | def lock_y(self):
self.lock('y') | def lock_y(self):
self.lock('y')<|docstring|>Lock y position<|endoftext|> |
dc26784011bae672bf21b9644cca8d09b6a968a634e5342b635ff9919d71a60c | def free_y(self):
'Free y motion'
self.free('y') | Free y motion | src/scrawl/moves/machinery.py | free_y | astromancer/graphical | 0 | python | def free_y(self):
self.free('y') | def free_y(self):
self.free('y')<|docstring|>Free y motion<|endoftext|> |
e994ce10a52b74d0ea3f64faa4dda69de1ddced6f82047f34f320645865830d6 | def limit(self, x=None, y=None):
'\n Set x and/or y limits for all draggable artists.\n\n Parameters\n ----------\n x\n y\n\n '
self.logger.debug('limit {}, {}', x, y)
for (art, drg) in self.draggable.items():
drg.limit(x, y) | Set x and/or y limits for all draggable artists.
Parameters
----------
x
y | src/scrawl/moves/machinery.py | limit | astromancer/graphical | 0 | python | def limit(self, x=None, y=None):
'\n Set x and/or y limits for all draggable artists.\n\n Parameters\n ----------\n x\n y\n\n '
self.logger.debug('limit {}, {}', x, y)
for (art, drg) in self.draggable.items():
drg.limit(x, y) | def limit(self, x=None, y=None):
'\n Set x and/or y limits for all draggable artists.\n\n Parameters\n ----------\n x\n y\n\n '
self.logger.debug('limit {}, {}', x, y)
for (art, drg) in self.draggable.items():
drg.limit(x, y)<|docstring|>Set x and/or y limits for all draggable artists.
Parameters
----------
x
y<|endoftext|> |
5f361e6d4094e18670c2a5e5da3dc4ce03a86568fd64e9746ed95928c9d0bb4b | def reset(self):
'reset the plot positions to original'
self.logger.debug('resetting!')
for (draggable, off) in zip(self.draggable.values(), self._original_offsets):
self.update(draggable, draggable.ref_point) | reset the plot positions to original | src/scrawl/moves/machinery.py | reset | astromancer/graphical | 0 | python | def reset(self):
self.logger.debug('resetting!')
for (draggable, off) in zip(self.draggable.values(), self._original_offsets):
self.update(draggable, draggable.ref_point) | def reset(self):
self.logger.debug('resetting!')
for (draggable, off) in zip(self.draggable.values(), self._original_offsets):
self.update(draggable, draggable.ref_point)<|docstring|>reset the plot positions to original<|endoftext|> |
2766914ee7daa432b09a219250be9f54389876da32da5f0115296857f8d5ef76 | @mpl_connect('button_press_event')
def on_click(self, event):
'reset plot on middle mouse'
if (event.button == 2):
self.reset()
else:
return | reset plot on middle mouse | src/scrawl/moves/machinery.py | on_click | astromancer/graphical | 0 | python | @mpl_connect('button_press_event')
def on_click(self, event):
if (event.button == 2):
self.reset()
else:
return | @mpl_connect('button_press_event')
def on_click(self, event):
if (event.button == 2):
self.reset()
else:
return<|docstring|>reset plot on middle mouse<|endoftext|> |
c1dcaed197ea2f3985ac2d338ad745948d3b338eb55a49d58a36884283c27c53 | def _ignore_pick(self, event):
'Filter pick events'
if (event.mouseevent.button != 1):
return True
if (event.artist not in self.draggable):
return True
if self.selection:
self.logger.debug('Multiple picks! ignoring: {}', event.artist)
return True
return False | Filter pick events | src/scrawl/moves/machinery.py | _ignore_pick | astromancer/graphical | 0 | python | def _ignore_pick(self, event):
if (event.mouseevent.button != 1):
return True
if (event.artist not in self.draggable):
return True
if self.selection:
self.logger.debug('Multiple picks! ignoring: {}', event.artist)
return True
return False | def _ignore_pick(self, event):
if (event.mouseevent.button != 1):
return True
if (event.artist not in self.draggable):
return True
if self.selection:
self.logger.debug('Multiple picks! ignoring: {}', event.artist)
return True
return False<|docstring|>Filter pick events<|endoftext|> |
8c02f61da01850c503656a809588e8e20cc22927cd809b605063040f546a165e | @mpl_connect('pick_event')
def on_pick(self, event):
'Pick event handler.'
if self._ignore_pick(event):
return
self.logger.debug('picked: {!r}: {}', event.artist, vars(event))
self.selection = event.artist
draggable = self.draggable[self.selection]
xy_disp = (event.mouseevent.x, event.mouseevent.y)
xy_data = self.ax.transData.inverted().transform(xy_disp)
self.ref_point = np.subtract(xy_data, draggable.offset)
draggable.on_picked(*xy_data)
self.add_connection('motion_notify_event', self.on_motion)
if self.use_blit:
draggable.set_animated(True)
draw_list = draggable.update_offset((0, 0))
for art in filter_non_artist(draw_list):
art.set_animated(True) | Pick event handler. | src/scrawl/moves/machinery.py | on_pick | astromancer/graphical | 0 | python | @mpl_connect('pick_event')
def on_pick(self, event):
if self._ignore_pick(event):
return
self.logger.debug('picked: {!r}: {}', event.artist, vars(event))
self.selection = event.artist
draggable = self.draggable[self.selection]
xy_disp = (event.mouseevent.x, event.mouseevent.y)
xy_data = self.ax.transData.inverted().transform(xy_disp)
self.ref_point = np.subtract(xy_data, draggable.offset)
draggable.on_picked(*xy_data)
self.add_connection('motion_notify_event', self.on_motion)
if self.use_blit:
draggable.set_animated(True)
draw_list = draggable.update_offset((0, 0))
for art in filter_non_artist(draw_list):
art.set_animated(True) | @mpl_connect('pick_event')
def on_pick(self, event):
if self._ignore_pick(event):
return
self.logger.debug('picked: {!r}: {}', event.artist, vars(event))
self.selection = event.artist
draggable = self.draggable[self.selection]
xy_disp = (event.mouseevent.x, event.mouseevent.y)
xy_data = self.ax.transData.inverted().transform(xy_disp)
self.ref_point = np.subtract(xy_data, draggable.offset)
draggable.on_picked(*xy_data)
self.add_connection('motion_notify_event', self.on_motion)
if self.use_blit:
draggable.set_animated(True)
draw_list = draggable.update_offset((0, 0))
for art in filter_non_artist(draw_list):
art.set_animated(True)<|docstring|>Pick event handler.<|endoftext|> |
e3a88597832719b598bf3f7cd41f3c3d85964e5bb409ad34669391136aab2f2c | def on_motion(self, event):
'\n Handle movement of the selected artist by the mouse.\n '
if (event.button != 1):
return
if self.selection:
self.logger.debug('dragging: {}', self.selection)
draggable = self.draggable[self.selection]
xy_disp = (event.x, event.y)
xy_data = (x, y) = self.ax.transData.inverted().transform(xy_disp)
self.delta = delta = (xy_data - self.ref_point)
self.logger.debug('on_motion: delta {}; ref {}', delta, self.ref_point)
self.update(draggable, xy_data) | Handle movement of the selected artist by the mouse. | src/scrawl/moves/machinery.py | on_motion | astromancer/graphical | 0 | python | def on_motion(self, event):
'\n \n '
if (event.button != 1):
return
if self.selection:
self.logger.debug('dragging: {}', self.selection)
draggable = self.draggable[self.selection]
xy_disp = (event.x, event.y)
xy_data = (x, y) = self.ax.transData.inverted().transform(xy_disp)
self.delta = delta = (xy_data - self.ref_point)
self.logger.debug('on_motion: delta {}; ref {}', delta, self.ref_point)
self.update(draggable, xy_data) | def on_motion(self, event):
'\n \n '
if (event.button != 1):
return
if self.selection:
self.logger.debug('dragging: {}', self.selection)
draggable = self.draggable[self.selection]
xy_disp = (event.x, event.y)
xy_data = (x, y) = self.ax.transData.inverted().transform(xy_disp)
self.delta = delta = (xy_data - self.ref_point)
self.logger.debug('on_motion: delta {}; ref {}', delta, self.ref_point)
self.update(draggable, xy_data)<|docstring|>Handle movement of the selected artist by the mouse.<|endoftext|> |
bb5a5f37836f4bbee822db3458d5eeaaca3ca1124645a93570ce630b2df84c2a | @mpl_connect('resize_event')
def on_resize(self, event):
'Save the background for blit after canvas resize'
self.save_background() | Save the background for blit after canvas resize | src/scrawl/moves/machinery.py | on_resize | astromancer/graphical | 0 | python | @mpl_connect('resize_event')
def on_resize(self, event):
self.save_background() | @mpl_connect('resize_event')
def on_resize(self, event):
self.save_background()<|docstring|>Save the background for blit after canvas resize<|endoftext|> |
cbd4947322ea2913de2d75536d43fc93864f641d6b2d088c27d927899a38bf6b | def update(self, draggable, xy_data, draw_on=True):
'\n Draw all artists that where changed by the motion\n\n Parameters\n ----------\n draggable\n xy_data\n draw_on\n\n Returns\n -------\n list of artists\n '
draw_list = draggable.update(*xy_data)
if draw_on:
self.draw(draw_list)
return draw_list | Draw all artists that where changed by the motion
Parameters
----------
draggable
xy_data
draw_on
Returns
-------
list of artists | src/scrawl/moves/machinery.py | update | astromancer/graphical | 0 | python | def update(self, draggable, xy_data, draw_on=True):
'\n Draw all artists that where changed by the motion\n\n Parameters\n ----------\n draggable\n xy_data\n draw_on\n\n Returns\n -------\n list of artists\n '
draw_list = draggable.update(*xy_data)
if draw_on:
self.draw(draw_list)
return draw_list | def update(self, draggable, xy_data, draw_on=True):
'\n Draw all artists that where changed by the motion\n\n Parameters\n ----------\n draggable\n xy_data\n draw_on\n\n Returns\n -------\n list of artists\n '
draw_list = draggable.update(*xy_data)
if draw_on:
self.draw(draw_list)
return draw_list<|docstring|>Draw all artists that where changed by the motion
Parameters
----------
draggable
xy_data
draw_on
Returns
-------
list of artists<|endoftext|> |
f39c9c1ac12829cc6af4cebd85f24b7f5b1aa6ab62a984d380a2d2129c18baad | def blit_setup(self, artists=()):
'\n Setup canvas for blitting. First make all the artists in the list\n invisible, then redraw the canvas and save, then redraw all the artists.\n '
fig = self.figure
artists = list(filter_non_artist(artists))
for art in artists:
art.set_animated(True)
art.set_visible(False)
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(fig.bbox)
for art in artists:
art.draw(fig.canvas.renderer)
art.set_animated(False)
art.set_visible(True)
fig.canvas.blit(fig.bbox)
return background | Setup canvas for blitting. First make all the artists in the list
invisible, then redraw the canvas and save, then redraw all the artists. | src/scrawl/moves/machinery.py | blit_setup | astromancer/graphical | 0 | python | def blit_setup(self, artists=()):
'\n Setup canvas for blitting. First make all the artists in the list\n invisible, then redraw the canvas and save, then redraw all the artists.\n '
fig = self.figure
artists = list(filter_non_artist(artists))
for art in artists:
art.set_animated(True)
art.set_visible(False)
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(fig.bbox)
for art in artists:
art.draw(fig.canvas.renderer)
art.set_animated(False)
art.set_visible(True)
fig.canvas.blit(fig.bbox)
return background | def blit_setup(self, artists=()):
'\n Setup canvas for blitting. First make all the artists in the list\n invisible, then redraw the canvas and save, then redraw all the artists.\n '
fig = self.figure
artists = list(filter_non_artist(artists))
for art in artists:
art.set_animated(True)
art.set_visible(False)
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(fig.bbox)
for art in artists:
art.draw(fig.canvas.renderer)
art.set_animated(False)
art.set_visible(True)
fig.canvas.blit(fig.bbox)
return background<|docstring|>Setup canvas for blitting. First make all the artists in the list
invisible, then redraw the canvas and save, then redraw all the artists.<|endoftext|> |
6636859b46ce149f57cf75be0e67ee80a3c7de8519a002eb564fc995f4f3cfda | def finalize_children(self):
'\n Sort the children (if any), and set properties for easy checking\n # they are at the beginning or end of the line.\n '
self.children = {k: v for (k, v) in sorted(self._children.items(), key=self._sorting)}
if self.children:
keys = list(self.children.keys())
self.children[keys[0]].first = True
self.children[keys[(- 1)]].last = True
for child in self.children.values():
child.finalize_children() | Sort the children (if any), and set properties for easy checking
# they are at the beginning or end of the line. | sanic_routing/tree.py | finalize_children | wochinge/sanic-routing | 8 | python | def finalize_children(self):
'\n Sort the children (if any), and set properties for easy checking\n # they are at the beginning or end of the line.\n '
self.children = {k: v for (k, v) in sorted(self._children.items(), key=self._sorting)}
if self.children:
keys = list(self.children.keys())
self.children[keys[0]].first = True
self.children[keys[(- 1)]].last = True
for child in self.children.values():
child.finalize_children() | def finalize_children(self):
'\n Sort the children (if any), and set properties for easy checking\n # they are at the beginning or end of the line.\n '
self.children = {k: v for (k, v) in sorted(self._children.items(), key=self._sorting)}
if self.children:
keys = list(self.children.keys())
self.children[keys[0]].first = True
self.children[keys[(- 1)]].last = True
for child in self.children.values():
child.finalize_children()<|docstring|>Sort the children (if any), and set properties for easy checking
# they are at the beginning or end of the line.<|endoftext|> |
0c5e93216dc2bbcfb6ecbdc460ef1b1228e88e022702929d7f305bb454af7512 | def display(self) -> None:
'\n Visual display of the tree of nodes\n '
logger.info((((' ' * 4) * self.level) + str(self)))
for child in self.children.values():
child.display() | Visual display of the tree of nodes | sanic_routing/tree.py | display | wochinge/sanic-routing | 8 | python | def display(self) -> None:
'\n \n '
logger.info((((' ' * 4) * self.level) + str(self)))
for child in self.children.values():
child.display() | def display(self) -> None:
'\n \n '
logger.info((((' ' * 4) * self.level) + str(self)))
for child in self.children.values():
child.display()<|docstring|>Visual display of the tree of nodes<|endoftext|> |
5718551a9e9e91c44ffa9c39f94bd078b362b460d96fa2fe35e7c68a7f8d5362 | def _inject_param_check(self, location, indent, idx):
'\n Try and cast relevant path segments.\n '
lines = [Line('try:', indent), Line(f"basket['__matches__'][{idx}] = {self.param.cast.__name__}(parts[{idx}])", (indent + 1)), Line('except ValueError:', indent), Line('pass', (indent + 1)), Line('else:', indent)]
if self.unquote:
lines.append(Line(f"basket['__matches__'][{idx}] = unquote(basket['__matches__'][{idx}])", (indent + 1)))
self.base_indent += 1
location.extend(lines) | Try and cast relevant path segments. | sanic_routing/tree.py | _inject_param_check | wochinge/sanic-routing | 8 | python | def _inject_param_check(self, location, indent, idx):
'\n \n '
lines = [Line('try:', indent), Line(f"basket['__matches__'][{idx}] = {self.param.cast.__name__}(parts[{idx}])", (indent + 1)), Line('except ValueError:', indent), Line('pass', (indent + 1)), Line('else:', indent)]
if self.unquote:
lines.append(Line(f"basket['__matches__'][{idx}] = unquote(basket['__matches__'][{idx}])", (indent + 1)))
self.base_indent += 1
location.extend(lines) | def _inject_param_check(self, location, indent, idx):
'\n \n '
lines = [Line('try:', indent), Line(f"basket['__matches__'][{idx}] = {self.param.cast.__name__}(parts[{idx}])", (indent + 1)), Line('except ValueError:', indent), Line('pass', (indent + 1)), Line('else:', indent)]
if self.unquote:
lines.append(Line(f"basket['__matches__'][{idx}] = unquote(basket['__matches__'][{idx}])", (indent + 1)))
self.base_indent += 1
location.extend(lines)<|docstring|>Try and cast relevant path segments.<|endoftext|> |
c8c8634d07f963ab3992f1d42645d891b8e515ab6dc0613bfaccb35cf49578f8 | @staticmethod
def _inject_method_check(location, indent, group):
'\n Sometimes we need to check the routing methods inside the generated src\n '
for (i, route) in enumerate(group.routes):
if_stmt = ('if' if (i == 0) else 'elif')
location.extend([Line(f'{if_stmt} method in {route.methods}:', indent), Line(f'route_idx = {i}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NoMethod', (indent + 1))]) | Sometimes we need to check the routing methods inside the generated src | sanic_routing/tree.py | _inject_method_check | wochinge/sanic-routing | 8 | python | @staticmethod
def _inject_method_check(location, indent, group):
'\n \n '
for (i, route) in enumerate(group.routes):
if_stmt = ('if' if (i == 0) else 'elif')
location.extend([Line(f'{if_stmt} method in {route.methods}:', indent), Line(f'route_idx = {i}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NoMethod', (indent + 1))]) | @staticmethod
def _inject_method_check(location, indent, group):
'\n \n '
for (i, route) in enumerate(group.routes):
if_stmt = ('if' if (i == 0) else 'elif')
location.extend([Line(f'{if_stmt} method in {route.methods}:', indent), Line(f'route_idx = {i}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NoMethod', (indent + 1))])<|docstring|>Sometimes we need to check the routing methods inside the generated src<|endoftext|> |
425d740d36b9b6fcc7799f7a22762558ba8c4c4b077aa27e7c6b8b40d9cc57ee | def _inject_return(self, location, indent, route_idx, group):
'\n The return statement for the node if needed\n '
routes = ('regex_routes' if group.regex else 'dynamic_routes')
route_return = ('' if group.router.stacking else f'[{route_idx}]')
location.extend([Line(f'# Return {self.ident}', indent), Line(f'return router.{routes}[{group.segments}]{route_return}, basket', indent)]) | The return statement for the node if needed | sanic_routing/tree.py | _inject_return | wochinge/sanic-routing | 8 | python | def _inject_return(self, location, indent, route_idx, group):
'\n \n '
routes = ('regex_routes' if group.regex else 'dynamic_routes')
route_return = ( if group.router.stacking else f'[{route_idx}]')
location.extend([Line(f'# Return {self.ident}', indent), Line(f'return router.{routes}[{group.segments}]{route_return}, basket', indent)]) | def _inject_return(self, location, indent, route_idx, group):
'\n \n '
routes = ('regex_routes' if group.regex else 'dynamic_routes')
route_return = ( if group.router.stacking else f'[{route_idx}]')
location.extend([Line(f'# Return {self.ident}', indent), Line(f'return router.{routes}[{group.segments}]{route_return}, basket', indent)])<|docstring|>The return statement for the node if needed<|endoftext|> |
ba95f5f6870ae8edd9878c3c93e750d2f271e893cf058c10b59abf901f3937ea | def _inject_requirements(self, location, indent, group):
'\n Check any extra checks needed for a route. In path routing, for exampe,\n this is used for matching vhosts.\n '
for (k, route) in enumerate(group):
conditional = ('if' if (k == 0) else 'elif')
location.extend([Line(f'{conditional} extra == {route.requirements} and method in {route.methods}:', indent), Line(f'route_idx = {k}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NotFound', (indent + 1))]) | Check any extra checks needed for a route. In path routing, for exampe,
this is used for matching vhosts. | sanic_routing/tree.py | _inject_requirements | wochinge/sanic-routing | 8 | python | def _inject_requirements(self, location, indent, group):
'\n Check any extra checks needed for a route. In path routing, for exampe,\n this is used for matching vhosts.\n '
for (k, route) in enumerate(group):
conditional = ('if' if (k == 0) else 'elif')
location.extend([Line(f'{conditional} extra == {route.requirements} and method in {route.methods}:', indent), Line(f'route_idx = {k}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NotFound', (indent + 1))]) | def _inject_requirements(self, location, indent, group):
'\n Check any extra checks needed for a route. In path routing, for exampe,\n this is used for matching vhosts.\n '
for (k, route) in enumerate(group):
conditional = ('if' if (k == 0) else 'elif')
location.extend([Line(f'{conditional} extra == {route.requirements} and method in {route.methods}:', indent), Line(f'route_idx = {k}', (indent + 1))])
location.extend([Line('else:', indent), Line('raise NotFound', (indent + 1))])<|docstring|>Check any extra checks needed for a route. In path routing, for exampe,
this is used for matching vhosts.<|endoftext|> |
ea61de95fb9b24af9e72444ee9ce0bd8008ad61040bc57a03b659f939e18f924 | def _inject_regex(self, location, indent, group):
'\n For any path matching that happens in the course of the tree (anything\n that has a path matching--<path:path>--or similar matching with regex\n delimiter)\n '
location.extend([Line(f'match = router.matchers[{group.pattern_idx}].match(path)', indent), Line('if match:', indent), Line("basket['__params__'] = match.groupdict()", (indent + 1))]) | For any path matching that happens in the course of the tree (anything
that has a path matching--<path:path>--or similar matching with regex
delimiter) | sanic_routing/tree.py | _inject_regex | wochinge/sanic-routing | 8 | python | def _inject_regex(self, location, indent, group):
'\n For any path matching that happens in the course of the tree (anything\n that has a path matching--<path:path>--or similar matching with regex\n delimiter)\n '
location.extend([Line(f'match = router.matchers[{group.pattern_idx}].match(path)', indent), Line('if match:', indent), Line("basket['__params__'] = match.groupdict()", (indent + 1))]) | def _inject_regex(self, location, indent, group):
'\n For any path matching that happens in the course of the tree (anything\n that has a path matching--<path:path>--or similar matching with regex\n delimiter)\n '
location.extend([Line(f'match = router.matchers[{group.pattern_idx}].match(path)', indent), Line('if match:', indent), Line("basket['__params__'] = match.groupdict()", (indent + 1))])<|docstring|>For any path matching that happens in the course of the tree (anything
that has a path matching--<path:path>--or similar matching with regex
delimiter)<|endoftext|> |
438343ba202e5d289d91cd4e4b3ab111a8a9ca88df96c52043dc239538fe5f4a | def _sorting(self, item) -> t.Tuple[(bool, bool, int, int, int, bool, str)]:
'\n Primarily use to sort nodes to determine the order of the nested tree\n '
(key, child) = item
type_ = 0
if child.dynamic:
type_ = child.param.priority
return (bool(child.groups), child.dynamic, (type_ * (- 1)), (child.depth * (- 1)), len(child._children), (not bool((child.groups and any((group.regex for group in child.groups))))), key) | Primarily use to sort nodes to determine the order of the nested tree | sanic_routing/tree.py | _sorting | wochinge/sanic-routing | 8 | python | def _sorting(self, item) -> t.Tuple[(bool, bool, int, int, int, bool, str)]:
'\n \n '
(key, child) = item
type_ = 0
if child.dynamic:
type_ = child.param.priority
return (bool(child.groups), child.dynamic, (type_ * (- 1)), (child.depth * (- 1)), len(child._children), (not bool((child.groups and any((group.regex for group in child.groups))))), key) | def _sorting(self, item) -> t.Tuple[(bool, bool, int, int, int, bool, str)]:
'\n \n '
(key, child) = item
type_ = 0
if child.dynamic:
type_ = child.param.priority
return (bool(child.groups), child.dynamic, (type_ * (- 1)), (child.depth * (- 1)), len(child._children), (not bool((child.groups and any((group.regex for group in child.groups))))), key)<|docstring|>Primarily use to sort nodes to determine the order of the nested tree<|endoftext|> |
9bd18b25892b462040b7998911e16006225ceda573e2c5e6ad618cdc24525dc8 | def _group_sorting(self, item) -> t.Tuple[(int, ...)]:
'\n When multiple RouteGroups terminate on the same node, we want to\n evaluate them based upon the priority of the param matching types\n '
def get_type(segment):
type_ = 0
if segment.startswith('<'):
key = segment[1:(- 1)]
if (':' in key):
(key, param_type) = key.split(':', 1)
try:
type_ = list(self.router.regex_types.keys()).index(param_type)
except ValueError:
type_ = len(list(self.router.regex_types.keys()))
return (type_ * (- 1))
segments = tuple(map(get_type, item.parts))
return segments | When multiple RouteGroups terminate on the same node, we want to
evaluate them based upon the priority of the param matching types | sanic_routing/tree.py | _group_sorting | wochinge/sanic-routing | 8 | python | def _group_sorting(self, item) -> t.Tuple[(int, ...)]:
'\n When multiple RouteGroups terminate on the same node, we want to\n evaluate them based upon the priority of the param matching types\n '
def get_type(segment):
type_ = 0
if segment.startswith('<'):
key = segment[1:(- 1)]
if (':' in key):
(key, param_type) = key.split(':', 1)
try:
type_ = list(self.router.regex_types.keys()).index(param_type)
except ValueError:
type_ = len(list(self.router.regex_types.keys()))
return (type_ * (- 1))
segments = tuple(map(get_type, item.parts))
return segments | def _group_sorting(self, item) -> t.Tuple[(int, ...)]:
'\n When multiple RouteGroups terminate on the same node, we want to\n evaluate them based upon the priority of the param matching types\n '
def get_type(segment):
type_ = 0
if segment.startswith('<'):
key = segment[1:(- 1)]
if (':' in key):
(key, param_type) = key.split(':', 1)
try:
type_ = list(self.router.regex_types.keys()).index(param_type)
except ValueError:
type_ = len(list(self.router.regex_types.keys()))
return (type_ * (- 1))
segments = tuple(map(get_type, item.parts))
return segments<|docstring|>When multiple RouteGroups terminate on the same node, we want to
evaluate them based upon the priority of the param matching types<|endoftext|> |
090ad79231c5db1504d2677adfe44f5a08c956c4de230ab3d9b21f586b4ad30c | def generate(self, groups: t.Iterable[RouteGroup]) -> None:
'\n Arrange RouteGroups into hierarchical nodes and arrange them into\n a tree\n '
for group in groups:
current = self.root
for (level, part) in enumerate(group.parts):
param = None
dynamic = part.startswith('<')
if dynamic:
if (not REGEX_PARAM_NAME.match(part)):
raise ValueError(f'Invalid declaration: {part}')
part = f'__dynamic__:{group.params[level].label}'
param = group.params[level]
if (part not in current._children):
child = Node(part=part, parent=current, router=self.router, param=param)
child.dynamic = dynamic
current.add_child(child)
current = current._children[part]
current.level = (level + 1)
current.groups.append(group)
current.unquote = (current.unquote or group.unquote) | Arrange RouteGroups into hierarchical nodes and arrange them into
a tree | sanic_routing/tree.py | generate | wochinge/sanic-routing | 8 | python | def generate(self, groups: t.Iterable[RouteGroup]) -> None:
'\n Arrange RouteGroups into hierarchical nodes and arrange them into\n a tree\n '
for group in groups:
current = self.root
for (level, part) in enumerate(group.parts):
param = None
dynamic = part.startswith('<')
if dynamic:
if (not REGEX_PARAM_NAME.match(part)):
raise ValueError(f'Invalid declaration: {part}')
part = f'__dynamic__:{group.params[level].label}'
param = group.params[level]
if (part not in current._children):
child = Node(part=part, parent=current, router=self.router, param=param)
child.dynamic = dynamic
current.add_child(child)
current = current._children[part]
current.level = (level + 1)
current.groups.append(group)
current.unquote = (current.unquote or group.unquote) | def generate(self, groups: t.Iterable[RouteGroup]) -> None:
'\n Arrange RouteGroups into hierarchical nodes and arrange them into\n a tree\n '
for group in groups:
current = self.root
for (level, part) in enumerate(group.parts):
param = None
dynamic = part.startswith('<')
if dynamic:
if (not REGEX_PARAM_NAME.match(part)):
raise ValueError(f'Invalid declaration: {part}')
part = f'__dynamic__:{group.params[level].label}'
param = group.params[level]
if (part not in current._children):
child = Node(part=part, parent=current, router=self.router, param=param)
child.dynamic = dynamic
current.add_child(child)
current = current._children[part]
current.level = (level + 1)
current.groups.append(group)
current.unquote = (current.unquote or group.unquote)<|docstring|>Arrange RouteGroups into hierarchical nodes and arrange them into
a tree<|endoftext|> |
eb12e1a307aa17dfdd1086928786b458f75c1b9af8e32f3d6d39eaebc5c44e7a | def display(self) -> None:
'\n Debug tool to output visual of the tree\n '
self.root.display() | Debug tool to output visual of the tree | sanic_routing/tree.py | display | wochinge/sanic-routing | 8 | python | def display(self) -> None:
'\n \n '
self.root.display() | def display(self) -> None:
'\n \n '
self.root.display()<|docstring|>Debug tool to output visual of the tree<|endoftext|> |
1555e8df4c6a0c00436ad76741db6a2d5c5431a0a7126d7b43dce29492b36136 | def summon_blocks(board):
'Place 1-8 circles in random places on the speed board'
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while (board[x][y] != 'g'):
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board | Place 1-8 circles in random places on the speed board | src/main.py | summon_blocks | andrewthederp/Documatic-Hackathon | 1 | python | def summon_blocks(board):
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while (board[x][y] != 'g'):
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board | def summon_blocks(board):
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while (board[x][y] != 'g'):
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board<|docstring|>Place 1-8 circles in random places on the speed board<|endoftext|> |
1cab39249bdcbbc794b17a55fb3dd80c1bf256dfd0194835e8e777e7496d93ac | def convert(coordinates):
'Convert the speed coordinates into x, y coordinates, this way you could do both "a1" or "1a'
for coor in coordinates.split(' '):
if (len(coor) != 2):
continue
coor = coor.lower()
if coor[0].isalpha():
digit = coor[1:]
letter = coor[0]
else:
digit = coor[:(- 1)]
letter = coor[(- 1)]
if (not digit.isdecimal()):
continue
x = (int(digit) - 1)
y = (ord(letter) - ord('a'))
if ((not (x in range(5))) or (not (y in range(5)))):
continue
(yield (x, y)) | Convert the speed coordinates into x, y coordinates, this way you could do both "a1" or "1a | src/main.py | convert | andrewthederp/Documatic-Hackathon | 1 | python | def convert(coordinates):
for coor in coordinates.split(' '):
if (len(coor) != 2):
continue
coor = coor.lower()
if coor[0].isalpha():
digit = coor[1:]
letter = coor[0]
else:
digit = coor[:(- 1)]
letter = coor[(- 1)]
if (not digit.isdecimal()):
continue
x = (int(digit) - 1)
y = (ord(letter) - ord('a'))
if ((not (x in range(5))) or (not (y in range(5)))):
continue
(yield (x, y)) | def convert(coordinates):
for coor in coordinates.split(' '):
if (len(coor) != 2):
continue
coor = coor.lower()
if coor[0].isalpha():
digit = coor[1:]
letter = coor[0]
else:
digit = coor[:(- 1)]
letter = coor[(- 1)]
if (not digit.isdecimal()):
continue
x = (int(digit) - 1)
y = (ord(letter) - ord('a'))
if ((not (x in range(5))) or (not (y in range(5)))):
continue
(yield (x, y))<|docstring|>Convert the speed coordinates into x, y coordinates, this way you could do both "a1" or "1a<|endoftext|> |
3088f4669f1596894bf1a77ded1311b44b7d524a684f119a2602740048ed49d6 | def format_board(board):
'A nested list formater, uses a dict to turn letters into emojis'
lst = []
dct = {'g': 'β¬', 'G': 'π©', 'q': 'π¦', 'p': 'π³', 'L': 'π', 'z': 'π§', 'e': random.choice(['π', 'π', 'π']), 'B': 'π₯', 's': 'π', 'a': 'πΎ', 'o': 'π£', 'w': 'π₯', 'x': 'β', ' ': 'β¬', 'u': 'β«', 'l': 'βͺ', 'r': 'β©', 'd': 'β¬', 'b': 'π²'}
for row in board:
lst.append(''.join([dct[i] for i in row]))
return '\n'.join(lst) | A nested list formater, uses a dict to turn letters into emojis | src/main.py | format_board | andrewthederp/Documatic-Hackathon | 1 | python | def format_board(board):
lst = []
dct = {'g': 'β¬', 'G': 'π©', 'q': 'π¦', 'p': 'π³', 'L': 'π', 'z': 'π§', 'e': random.choice(['π', 'π', 'π']), 'B': 'π₯', 's': 'π', 'a': 'πΎ', 'o': 'π£', 'w': 'π₯', 'x': 'β', ' ': 'β¬', 'u': 'β«', 'l': 'βͺ', 'r': 'β©', 'd': 'β¬', 'b': 'π²'}
for row in board:
lst.append(.join([dct[i] for i in row]))
return '\n'.join(lst) | def format_board(board):
lst = []
dct = {'g': 'β¬', 'G': 'π©', 'q': 'π¦', 'p': 'π³', 'L': 'π', 'z': 'π§', 'e': random.choice(['π', 'π', 'π']), 'B': 'π₯', 's': 'π', 'a': 'πΎ', 'o': 'π£', 'w': 'π₯', 'x': 'β', ' ': 'β¬', 'u': 'β«', 'l': 'βͺ', 'r': 'β©', 'd': 'β¬', 'b': 'π²'}
for row in board:
lst.append(.join([dct[i] for i in row]))
return '\n'.join(lst)<|docstring|>A nested list formater, uses a dict to turn letters into emojis<|endoftext|> |
a3ad8a7d9d34f698f61e6a1e65522e9a5be73bcd6ad8f776d09cfc8485b0ed9f | def format_speed_board(board):
'Speed board requires coordinates a boarder so i made a different function for it'
dct = {'g': 'β¬', 'b': 'b'}
for i in range(1, 6):
dct[i] = f'{i}οΈβ£'
lst = [f':stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d::regional_indicator_e:']
for (num, row) in enumerate(board, start=1):
lst.append((dct[num] + ''.join([(dct[column] if (column != 'b') else random.choice(['π΄', 'π ', 'π‘', 'π’', 'π΅', 'π£', 'π€'])) for column in row])))
return '\n'.join(lst) | Speed board requires coordinates a boarder so i made a different function for it | src/main.py | format_speed_board | andrewthederp/Documatic-Hackathon | 1 | python | def format_speed_board(board):
dct = {'g': 'β¬', 'b': 'b'}
for i in range(1, 6):
dct[i] = f'{i}οΈβ£'
lst = [f':stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d::regional_indicator_e:']
for (num, row) in enumerate(board, start=1):
lst.append((dct[num] + .join([(dct[column] if (column != 'b') else random.choice(['π΄', 'π ', 'π‘', 'π’', 'π΅', 'π£', 'π€'])) for column in row])))
return '\n'.join(lst) | def format_speed_board(board):
dct = {'g': 'β¬', 'b': 'b'}
for i in range(1, 6):
dct[i] = f'{i}οΈβ£'
lst = [f':stop_button::regional_indicator_a::regional_indicator_b::regional_indicator_c::regional_indicator_d::regional_indicator_e:']
for (num, row) in enumerate(board, start=1):
lst.append((dct[num] + .join([(dct[column] if (column != 'b') else random.choice(['π΄', 'π ', 'π‘', 'π’', 'π΅', 'π£', 'π€'])) for column in row])))
return '\n'.join(lst)<|docstring|>Speed board requires coordinates a boarder so i made a different function for it<|endoftext|> |
1e9f510237a3f5ea9a35bacfeee7983bae5c2fc323484efac564335d927e6398 | def check_zombie_collides(board, bullets, enemies, score):
'Check if a zombie collided with a bullet'
for enemy in enemies:
for bullet in bullets:
collide = False
try:
if (bullet.index == enemy.index):
board[bullet.index[0]][bullet.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] + 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] + 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] - 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] - 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] + 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] + 1)] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] - 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] - 1)] = 'G'
collide = True
except IndexError:
collide = True
if collide:
try:
bullets.remove(bullet)
except ValueError:
pass
try:
enemies.remove(enemy)
except ValueError:
pass
score += 1
return (board, bullets, enemies, score) | Check if a zombie collided with a bullet | src/main.py | check_zombie_collides | andrewthederp/Documatic-Hackathon | 1 | python | def check_zombie_collides(board, bullets, enemies, score):
for enemy in enemies:
for bullet in bullets:
collide = False
try:
if (bullet.index == enemy.index):
board[bullet.index[0]][bullet.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] + 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] + 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] - 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] - 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] + 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] + 1)] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] - 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] - 1)] = 'G'
collide = True
except IndexError:
collide = True
if collide:
try:
bullets.remove(bullet)
except ValueError:
pass
try:
enemies.remove(enemy)
except ValueError:
pass
score += 1
return (board, bullets, enemies, score) | def check_zombie_collides(board, bullets, enemies, score):
for enemy in enemies:
for bullet in bullets:
collide = False
try:
if (bullet.index == enemy.index):
board[bullet.index[0]][bullet.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] + 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] + 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [(enemy.index[0] - 1), enemy.index[1]]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[(enemy.index[0] - 1)][enemy.index[1]] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] + 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] + 1)] = 'G'
collide = True
elif (bullet.index == [enemy.index[0], (enemy.index[1] - 1)]):
board[enemy.index[0]][enemy.index[1]] = 'G'
board[enemy.index[0]][(enemy.index[1] - 1)] = 'G'
collide = True
except IndexError:
collide = True
if collide:
try:
bullets.remove(bullet)
except ValueError:
pass
try:
enemies.remove(enemy)
except ValueError:
pass
score += 1
return (board, bullets, enemies, score)<|docstring|>Check if a zombie collided with a bullet<|endoftext|> |
faa05081c46625772a60a7f7f29ef16d9b3847225536704e07d904872c101ddc | async def scene_1(ctx, msg):
'Scene 1, played when you use the zombie command'
embed = discord.Embed(title='Chapter 1: What happened', description=f'**???:** *WAKE UP KID*', color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += f'''
**{ctx.author.display_name}:** *what's happening... wait Raphael? what happened?*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += '\n**Raphael:** *ZOMBIES ARE SURROINDING US, TAKE THIS GUN*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *AAAAAAAAAA, THE ZOMBIES ARE EVERYWHERE!*'''
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: π³\nThese are bullets: π\nThese are zombies: π§\n\n**How to play:** wait till all the reactions have been added, then react to reactions pointing in the direction you want to shoot a bullet in, make sure the zombies don't touch you and goodluck!"))
(await asyncio.sleep(0.5)) | Scene 1, played when you use the zombie command | src/main.py | scene_1 | andrewthederp/Documatic-Hackathon | 1 | python | async def scene_1(ctx, msg):
embed = discord.Embed(title='Chapter 1: What happened', description=f'**???:** *WAKE UP KID*', color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += f'
**{ctx.author.display_name}:** *what's happening... wait Raphael? what happened?*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += '\n**Raphael:** *ZOMBIES ARE SURROINDING US, TAKE THIS GUN*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *AAAAAAAAAA, THE ZOMBIES ARE EVERYWHERE!*'
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: π³\nThese are bullets: π\nThese are zombies: π§\n\n**How to play:** wait till all the reactions have been added, then react to reactions pointing in the direction you want to shoot a bullet in, make sure the zombies don't touch you and goodluck!"))
(await asyncio.sleep(0.5)) | async def scene_1(ctx, msg):
embed = discord.Embed(title='Chapter 1: What happened', description=f'**???:** *WAKE UP KID*', color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += f'
**{ctx.author.display_name}:** *what's happening... wait Raphael? what happened?*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += '\n**Raphael:** *ZOMBIES ARE SURROINDING US, TAKE THIS GUN*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *AAAAAAAAAA, THE ZOMBIES ARE EVERYWHERE!*'
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: π³\nThese are bullets: π\nThese are zombies: π§\n\n**How to play:** wait till all the reactions have been added, then react to reactions pointing in the direction you want to shoot a bullet in, make sure the zombies don't touch you and goodluck!"))
(await asyncio.sleep(0.5))<|docstring|>Scene 1, played when you use the zombie command<|endoftext|> |
17eb199e9b26c8c715410e05f3c7695f15b3b809f04191cf936a12145fd991df | async def scene_2(ctx, msg):
'Scene 2, played when you use the spaceshooter command'
embed = discord.Embed(title='Chapter 2: The spaceship', description='', color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(0.5))
embed.description = '**John:** *THERE ARE SO MANY ZOMBIES, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Raphael:** *CMON, LET'S GO, ADAM PROBABLY FINISHED WORKING ON THE SPACESHIP*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *??? WHAT SPACESHIP, CAN ANYONE PLEASE EXPLAIN TO ME WHAT'S HAPPENING*'''
(await msg.edit(embed=embed))
for i in range(1, 7):
(await msg.edit(embed=discord.Embed(title='Chapter 2: The spaceship', description=((embed.description + '\n') + ('.' * (i if (i < 4) else (i - 3)))), color=discord.Color.dark_theme())))
(await asyncio.sleep(0.3))
embed.description += "\n**Raphael:** *okay, we are safe **for now**, how's the ship's status Adam?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += '\n**Adam:** *I was able to fix the spaceship for the most part but the spaceship could only have 4 people onboard, someone has to be left behind...*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**John:** *I will do it, it was a great run guys but this is where my story ends, goodluck!*'
(await msg.edit(embed=embed))
(await asyncio.sleep(3))
bord = [(['g'] * 7) for i in range(7)]
bord[3][0] = 'e'
index = [3, 1]
bord[index[0]][index[1]] = 's'
for i in range(5):
embed = discord.Embed(title='Chapter 2: The spaceship', description=format_board(bord), color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
bord[index[0]][index[1]] = 'g'
index[1] += 1
if (i == 2):
bord[3][0] = 'B'
bord[index[0]][index[1]] = 's'
(await asyncio.sleep(0.5))
(await ctx.send("__**Part 2:**__ you and the rest of the group were able to leave earth just in time before it (for some reason) dramatically exploded, now that you're in space a new threat arises **aliens**\n**How to play:** The goal is to get the highest score possible, move right or left then press βΉ to shoot a laser, the higher your score the higher you'll be on the leaderboard\n\nif you get hit by get hit by an alien you'll loose a life (you have 3 lifes), goodluck!\n\nThis is you: π\nThese are your bullets: π\nThese are aliens: πΎ")) | Scene 2, played when you use the spaceshooter command | src/main.py | scene_2 | andrewthederp/Documatic-Hackathon | 1 | python | async def scene_2(ctx, msg):
embed = discord.Embed(title='Chapter 2: The spaceship', description=, color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(0.5))
embed.description = '**John:** *THERE ARE SO MANY ZOMBIES, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Raphael:** *CMON, LET'S GO, ADAM PROBABLY FINISHED WORKING ON THE SPACESHIP*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *??? WHAT SPACESHIP, CAN ANYONE PLEASE EXPLAIN TO ME WHAT'S HAPPENING*'
(await msg.edit(embed=embed))
for i in range(1, 7):
(await msg.edit(embed=discord.Embed(title='Chapter 2: The spaceship', description=((embed.description + '\n') + ('.' * (i if (i < 4) else (i - 3)))), color=discord.Color.dark_theme())))
(await asyncio.sleep(0.3))
embed.description += "\n**Raphael:** *okay, we are safe **for now**, how's the ship's status Adam?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += '\n**Adam:** *I was able to fix the spaceship for the most part but the spaceship could only have 4 people onboard, someone has to be left behind...*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**John:** *I will do it, it was a great run guys but this is where my story ends, goodluck!*'
(await msg.edit(embed=embed))
(await asyncio.sleep(3))
bord = [(['g'] * 7) for i in range(7)]
bord[3][0] = 'e'
index = [3, 1]
bord[index[0]][index[1]] = 's'
for i in range(5):
embed = discord.Embed(title='Chapter 2: The spaceship', description=format_board(bord), color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
bord[index[0]][index[1]] = 'g'
index[1] += 1
if (i == 2):
bord[3][0] = 'B'
bord[index[0]][index[1]] = 's'
(await asyncio.sleep(0.5))
(await ctx.send("__**Part 2:**__ you and the rest of the group were able to leave earth just in time before it (for some reason) dramatically exploded, now that you're in space a new threat arises **aliens**\n**How to play:** The goal is to get the highest score possible, move right or left then press βΉ to shoot a laser, the higher your score the higher you'll be on the leaderboard\n\nif you get hit by get hit by an alien you'll loose a life (you have 3 lifes), goodluck!\n\nThis is you: π\nThese are your bullets: π\nThese are aliens: πΎ")) | async def scene_2(ctx, msg):
embed = discord.Embed(title='Chapter 2: The spaceship', description=, color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
(await asyncio.sleep(0.5))
embed.description = '**John:** *THERE ARE SO MANY ZOMBIES, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Raphael:** *CMON, LET'S GO, ADAM PROBABLY FINISHED WORKING ON THE SPACESHIP*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *??? WHAT SPACESHIP, CAN ANYONE PLEASE EXPLAIN TO ME WHAT'S HAPPENING*'
(await msg.edit(embed=embed))
for i in range(1, 7):
(await msg.edit(embed=discord.Embed(title='Chapter 2: The spaceship', description=((embed.description + '\n') + ('.' * (i if (i < 4) else (i - 3)))), color=discord.Color.dark_theme())))
(await asyncio.sleep(0.3))
embed.description += "\n**Raphael:** *okay, we are safe **for now**, how's the ship's status Adam?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += '\n**Adam:** *I was able to fix the spaceship for the most part but the spaceship could only have 4 people onboard, someone has to be left behind...*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**John:** *I will do it, it was a great run guys but this is where my story ends, goodluck!*'
(await msg.edit(embed=embed))
(await asyncio.sleep(3))
bord = [(['g'] * 7) for i in range(7)]
bord[3][0] = 'e'
index = [3, 1]
bord[index[0]][index[1]] = 's'
for i in range(5):
embed = discord.Embed(title='Chapter 2: The spaceship', description=format_board(bord), color=discord.Color.dark_theme())
(await msg.edit(embed=embed))
bord[index[0]][index[1]] = 'g'
index[1] += 1
if (i == 2):
bord[3][0] = 'B'
bord[index[0]][index[1]] = 's'
(await asyncio.sleep(0.5))
(await ctx.send("__**Part 2:**__ you and the rest of the group were able to leave earth just in time before it (for some reason) dramatically exploded, now that you're in space a new threat arises **aliens**\n**How to play:** The goal is to get the highest score possible, move right or left then press βΉ to shoot a laser, the higher your score the higher you'll be on the leaderboard\n\nif you get hit by get hit by an alien you'll loose a life (you have 3 lifes), goodluck!\n\nThis is you: π\nThese are your bullets: π\nThese are aliens: πΎ"))<|docstring|>Scene 2, played when you use the spaceshooter command<|endoftext|> |
386a457b944abe25ec9a65d1b7e536087d66df8c823aa056cbb5b393a43940da | async def scene_3(ctx):
'Scene 3, played when you hit 50 score in spaceshooter'
embed = discord.Embed(title='Chapter 3: The Crew', description='', color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += "**???**: *Hey, i didn't introduce myself*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Caroline:** *My name is Caroline! what's your name?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *Oh, hello. My name is {ctx.author.display_name}*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**Caroline:** *Very nice to meet you {ctx.author.name}*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *Nice to meet you too.*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
return msg | Scene 3, played when you hit 50 score in spaceshooter | src/main.py | scene_3 | andrewthederp/Documatic-Hackathon | 1 | python | async def scene_3(ctx):
embed = discord.Embed(title='Chapter 3: The Crew', description=, color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += "**???**: *Hey, i didn't introduce myself*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Caroline:** *My name is Caroline! what's your name?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *Oh, hello. My name is {ctx.author.display_name}*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**Caroline:** *Very nice to meet you {ctx.author.name}*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *Nice to meet you too.*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
return msg | async def scene_3(ctx):
embed = discord.Embed(title='Chapter 3: The Crew', description=, color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += "**???**: *Hey, i didn't introduce myself*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
embed.description += "\n**Caroline:** *My name is Caroline! what's your name?*"
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *Oh, hello. My name is {ctx.author.display_name}*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**Caroline:** *Very nice to meet you {ctx.author.name}*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *Nice to meet you too.*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
return msg<|docstring|>Scene 3, played when you hit 50 score in spaceshooter<|endoftext|> |
94c16e4047a54ab87c378c3852ce084c7f46493bed13f7da3337cb0670b0c0a5 | async def scene_4(ctx):
'Scene 4, played when you use the maze command on storyline mode'
embed = discord.Embed(title='Chapter 4: The Crash', description='', color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += '*Siren noises*\n**Raphael:** *EVERYBODY WAKE UP, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *WHAT'S HAPPENING NOW???*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'''
**Raphael:** *THE SHIP GOT BADLEY DAMAGED, HERE EVERYONE TAKE THESE SUITS*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += f'''
**Caroline:** *OH NO!!!*
**Adam:** *MY SHIP D:*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**Raphael:** *WE NEED TO GET ONTO THAT PLANET*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'''
**{ctx.author.display_name}:** *... okay we landed safely, what now*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'''
**Raphael:** *Be careful guys, this planet's gravity is really messed up*'''
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'''
**Adam:** *crying*'''
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: :flushed:\nThese are walls: π₯\nThis is an exit point: :x:\nThese are direction changer blocks: β«βͺβ©β¬ (changes the direction of the player to the direction it's pointing at)\nthis is a breaking block: π² (it stops the player and breaks when he player touches it)\n\n**Part 3:** Now that you landed on the planet your goal is to hit the :x:, react to the reaction pointing in the direction you want to move. You will keep moving until you hit a wall be careful to not fall of the planet and as always, *goodluck!*"))
(await asyncio.sleep(1.5))
return msg | Scene 4, played when you use the maze command on storyline mode | src/main.py | scene_4 | andrewthederp/Documatic-Hackathon | 1 | python | async def scene_4(ctx):
embed = discord.Embed(title='Chapter 4: The Crash', description=, color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += '*Siren noises*\n**Raphael:** *EVERYBODY WAKE UP, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *WHAT'S HAPPENING NOW???*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Raphael:** *THE SHIP GOT BADLEY DAMAGED, HERE EVERYONE TAKE THESE SUITS*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += f'
**Caroline:** *OH NO!!!*
**Adam:** *MY SHIP D:*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**Raphael:** *WE NEED TO GET ONTO THAT PLANET*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *... okay we landed safely, what now*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Raphael:** *Be careful guys, this planet's gravity is really messed up*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Adam:** *crying*'
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: :flushed:\nThese are walls: π₯\nThis is an exit point: :x:\nThese are direction changer blocks: β«βͺβ©β¬ (changes the direction of the player to the direction it's pointing at)\nthis is a breaking block: π² (it stops the player and breaks when he player touches it)\n\n**Part 3:** Now that you landed on the planet your goal is to hit the :x:, react to the reaction pointing in the direction you want to move. You will keep moving until you hit a wall be careful to not fall of the planet and as always, *goodluck!*"))
(await asyncio.sleep(1.5))
return msg | async def scene_4(ctx):
embed = discord.Embed(title='Chapter 4: The Crash', description=, color=discord.Color.dark_theme())
msg = (await ctx.send(embed=embed))
embed.description += '*Siren noises*\n**Raphael:** *EVERYBODY WAKE UP, WE NEED TO GO NOW*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *WHAT'S HAPPENING NOW???*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Raphael:** *THE SHIP GOT BADLEY DAMAGED, HERE EVERYONE TAKE THESE SUITS*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += f'
**Caroline:** *OH NO!!!*
**Adam:** *MY SHIP D:*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2.5))
embed.description += '\n**Raphael:** *WE NEED TO GET ONTO THAT PLANET*'
(await msg.edit(embed=embed))
(await asyncio.sleep(1.5))
embed.description += f'
**{ctx.author.display_name}:** *... okay we landed safely, what now*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Raphael:** *Be careful guys, this planet's gravity is really messed up*'
(await msg.edit(embed=embed))
(await asyncio.sleep(2))
embed.description += f'
**Adam:** *crying*'
(await msg.edit(embed=embed))
(await ctx.send("__**Instructions:**__\nThis is you: :flushed:\nThese are walls: π₯\nThis is an exit point: :x:\nThese are direction changer blocks: β«βͺβ©β¬ (changes the direction of the player to the direction it's pointing at)\nthis is a breaking block: π² (it stops the player and breaks when he player touches it)\n\n**Part 3:** Now that you landed on the planet your goal is to hit the :x:, react to the reaction pointing in the direction you want to move. You will keep moving until you hit a wall be careful to not fall of the planet and as always, *goodluck!*"))
(await asyncio.sleep(1.5))
return msg<|docstring|>Scene 4, played when you use the maze command on storyline mode<|endoftext|> |
e920848506739e14c35db573de1e0810611dc291e8fe0a1ad4e4e0624d48432b | def get_player(lst):
'Returns the x, y coordinates of the player on the board'
for (x, row) in enumerate(lst):
for (y, column) in enumerate(row):
if (column == 'p'):
return (x, y) | Returns the x, y coordinates of the player on the board | src/main.py | get_player | andrewthederp/Documatic-Hackathon | 1 | python | def get_player(lst):
for (x, row) in enumerate(lst):
for (y, column) in enumerate(row):
if (column == 'p'):
return (x, y) | def get_player(lst):
for (x, row) in enumerate(lst):
for (y, column) in enumerate(row):
if (column == 'p'):
return (x, y)<|docstring|>Returns the x, y coordinates of the player on the board<|endoftext|> |
d41c4aa9973a15228c8f80a34c7bc735885ee45be38d95a074a9a1065fc8c8aa | def go_direction(lst, direction, player_index):
"Moves the player into a direction and makes sure the player isn't in an infinite loop/off screen"
(x, y) = player_index
moves = 0
while True:
moves += 1
x += direction[0]
y += direction[1]
if ((x < 0) or (y < 0)):
return (None, 'Dead')
try:
if (lst[x][y] == 'w'):
x -= direction[0]
y -= direction[1]
break
elif (lst[x][y] == 'u'):
x -= direction[0]
y -= direction[1]
direction = UP
elif (lst[x][y] == 'd'):
x -= direction[0]
y -= direction[1]
direction = DOWN
elif (lst[x][y] == 'l'):
x -= direction[0]
y -= direction[1]
direction = LEFT
elif (lst[x][y] == 'r'):
x -= direction[0]
y -= direction[1]
direction = RIGHT
elif (lst[x][y] == 'b'):
lst[x][y] = 'g'
x -= direction[0]
y -= direction[1]
break
except IndexError:
return (None, 'Dead')
if (moves > 150):
return ('Infinite loop', 'Dead')
return (lst, x, y) | Moves the player into a direction and makes sure the player isn't in an infinite loop/off screen | src/main.py | go_direction | andrewthederp/Documatic-Hackathon | 1 | python | def go_direction(lst, direction, player_index):
(x, y) = player_index
moves = 0
while True:
moves += 1
x += direction[0]
y += direction[1]
if ((x < 0) or (y < 0)):
return (None, 'Dead')
try:
if (lst[x][y] == 'w'):
x -= direction[0]
y -= direction[1]
break
elif (lst[x][y] == 'u'):
x -= direction[0]
y -= direction[1]
direction = UP
elif (lst[x][y] == 'd'):
x -= direction[0]
y -= direction[1]
direction = DOWN
elif (lst[x][y] == 'l'):
x -= direction[0]
y -= direction[1]
direction = LEFT
elif (lst[x][y] == 'r'):
x -= direction[0]
y -= direction[1]
direction = RIGHT
elif (lst[x][y] == 'b'):
lst[x][y] = 'g'
x -= direction[0]
y -= direction[1]
break
except IndexError:
return (None, 'Dead')
if (moves > 150):
return ('Infinite loop', 'Dead')
return (lst, x, y) | def go_direction(lst, direction, player_index):
(x, y) = player_index
moves = 0
while True:
moves += 1
x += direction[0]
y += direction[1]
if ((x < 0) or (y < 0)):
return (None, 'Dead')
try:
if (lst[x][y] == 'w'):
x -= direction[0]
y -= direction[1]
break
elif (lst[x][y] == 'u'):
x -= direction[0]
y -= direction[1]
direction = UP
elif (lst[x][y] == 'd'):
x -= direction[0]
y -= direction[1]
direction = DOWN
elif (lst[x][y] == 'l'):
x -= direction[0]
y -= direction[1]
direction = LEFT
elif (lst[x][y] == 'r'):
x -= direction[0]
y -= direction[1]
direction = RIGHT
elif (lst[x][y] == 'b'):
lst[x][y] = 'g'
x -= direction[0]
y -= direction[1]
break
except IndexError:
return (None, 'Dead')
if (moves > 150):
return ('Infinite loop', 'Dead')
return (lst, x, y)<|docstring|>Moves the player into a direction and makes sure the player isn't in an infinite loop/off screen<|endoftext|> |
dd72e986d01bc3bb79e1567c8f514364e872b7793a38d7eb818009e57e819deb | def save_maze(maze):
'Saves the player made maze, only saves it if the player was able to beat it to prove that the maze was actually possible'
if (not ('levels.txt' in os.listdir())):
f = open('levels.txt', mode='x')
f.write((maze + '\n'))
else:
f = open('levels.txt', mode='a')
f.write((maze + '\n')) | Saves the player made maze, only saves it if the player was able to beat it to prove that the maze was actually possible | src/main.py | save_maze | andrewthederp/Documatic-Hackathon | 1 | python | def save_maze(maze):
if (not ('levels.txt' in os.listdir())):
f = open('levels.txt', mode='x')
f.write((maze + '\n'))
else:
f = open('levels.txt', mode='a')
f.write((maze + '\n')) | def save_maze(maze):
if (not ('levels.txt' in os.listdir())):
f = open('levels.txt', mode='x')
f.write((maze + '\n'))
else:
f = open('levels.txt', mode='a')
f.write((maze + '\n'))<|docstring|>Saves the player made maze, only saves it if the player was able to beat it to prove that the maze was actually possible<|endoftext|> |
0cc5dbd44e4f900110da7cd0396836d9aa15e2e24bfa75f59eed281a63e6cabf | async def score_db():
'Creates "scores.db" which saves the scores for the leaderboard command'
(await bot.wait_until_ready())
bot.db = (await aiosqlite.connect('scores.db'))
(await bot.db.execute('CREATE TABLE IF NOT EXISTS scores (author_id int, score int, command_name text)')) | Creates "scores.db" which saves the scores for the leaderboard command | src/main.py | score_db | andrewthederp/Documatic-Hackathon | 1 | python | async def score_db():
(await bot.wait_until_ready())
bot.db = (await aiosqlite.connect('scores.db'))
(await bot.db.execute('CREATE TABLE IF NOT EXISTS scores (author_id int, score int, command_name text)')) | async def score_db():
(await bot.wait_until_ready())
bot.db = (await aiosqlite.connect('scores.db'))
(await bot.db.execute('CREATE TABLE IF NOT EXISTS scores (author_id int, score int, command_name text)'))<|docstring|>Creates "scores.db" which saves the scores for the leaderboard command<|endoftext|> |
25a6411f56675c67c805cd4b9d4d9832c8fda8e659cd201ea9077b83763f3695 | async def save_score(ctx, score):
'Adds the player score into scores.db'
cursor = (await bot.db.execute('SELECT score from scores WHERE author_id = ? AND command_name = ?', (ctx.author.id, ctx.command.name)))
data = (await cursor.fetchone())
if data:
if (data[0] < score):
(await bot.db.execute(f'UPDATE scores SET score = ? WHERE author_id = ? AND command_name = ?', (score, ctx.author.id, ctx.command.name)))
else:
(await bot.db.execute('INSERT OR IGNORE INTO scores (author_id, score, command_name) VALUES (?,?,?)', (ctx.author.id, score, ctx.command.name)))
(await bot.db.commit()) | Adds the player score into scores.db | src/main.py | save_score | andrewthederp/Documatic-Hackathon | 1 | python | async def save_score(ctx, score):
cursor = (await bot.db.execute('SELECT score from scores WHERE author_id = ? AND command_name = ?', (ctx.author.id, ctx.command.name)))
data = (await cursor.fetchone())
if data:
if (data[0] < score):
(await bot.db.execute(f'UPDATE scores SET score = ? WHERE author_id = ? AND command_name = ?', (score, ctx.author.id, ctx.command.name)))
else:
(await bot.db.execute('INSERT OR IGNORE INTO scores (author_id, score, command_name) VALUES (?,?,?)', (ctx.author.id, score, ctx.command.name)))
(await bot.db.commit()) | async def save_score(ctx, score):
cursor = (await bot.db.execute('SELECT score from scores WHERE author_id = ? AND command_name = ?', (ctx.author.id, ctx.command.name)))
data = (await cursor.fetchone())
if data:
if (data[0] < score):
(await bot.db.execute(f'UPDATE scores SET score = ? WHERE author_id = ? AND command_name = ?', (score, ctx.author.id, ctx.command.name)))
else:
(await bot.db.execute('INSERT OR IGNORE INTO scores (author_id, score, command_name) VALUES (?,?,?)', (ctx.author.id, score, ctx.command.name)))
(await bot.db.commit())<|docstring|>Adds the player score into scores.db<|endoftext|> |
9c55bfea8e08b34d34bb394c23eb3db92d49fa09649da0f0035f59151433ad21 | @bot.event
async def on_ready():
'on_ready'
print('Online!') | on_ready | src/main.py | on_ready | andrewthederp/Documatic-Hackathon | 1 | python | @bot.event
async def ():
print('Online!') | @bot.event
async def ():
print('Online!')<|docstring|>on_ready<|endoftext|> |
8d1b29affe6e1ff83d7f75a6ad46d845f761a061076c4ffbcdab8f24708fc1b4 | @bot.command()
async def zombies(ctx):
"You're surrounded by zombies!!! don't worry tho, you have a gun. React to the reaction pointing in the direction you want *don't miss*"
board_copy = copy.deepcopy(board)
update_cache(ctx)
bullets = []
zombies = []
score = 0
alive = True
msg = (await ctx.send(embed=discord.Embed(title='Chapter 1: What happened', color=discord.Color.dark_theme())))
(await scene_1(ctx, msg))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(content=f'''Score: {score}
''', embed=discord.Embed(title='Zombies', description=format_board(board_copy), color=discord.Color.blurple())))
if (not (len(bullets) == 5)):
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=3.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'π³'):
(await save_score(ctx, score))
return (await ctx.send('Ended the game!'))
bullets.append(Bullet(conversion[str(inp)], [5, 5]))
except asyncio.TimeoutError:
pass
for bullet in bullets:
board_copy[bullet.index[0]][bullet.index[1]] = 'G'
try:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
board_copy[bullet.index[0]][bullet.index[1]] = 'L'
except IndexError:
bullets.remove(bullet)
(board_copy, bullets, zombies, score) = check_zombie_collides(board_copy, bullets, zombies, score)
for zombie in zombies:
try:
board_copy[zombie.index[0]][zombie.index[1]] = 'G'
except IndexError:
pass
zombie.move()
board_copy[zombie.index[0]][zombie.index[1]] = 'z'
if (zombie.index == [5, 5]):
(await save_score(ctx, score))
return (await ctx.send(f'''The zombie ate {ctx.author.display_name}'s brain!!!
Score: {score}'''))
board_copy[5][5] = 'p'
if (len(zombies) < 5):
zombie_number = random.choice([0, 0, 0, 0, 1, 1, 1, 2, 2, 3])
directions_copy = copy.copy(directions)
for i in range(zombie_number):
direction = random.choice(directions_copy)
zombies.append(Zombie(direction))
directions_copy.remove(direction) | You're surrounded by zombies!!! don't worry tho, you have a gun. React to the reaction pointing in the direction you want *don't miss* | src/main.py | zombies | andrewthederp/Documatic-Hackathon | 1 | python | @bot.command()
async def zombies(ctx):
board_copy = copy.deepcopy(board)
update_cache(ctx)
bullets = []
zombies = []
score = 0
alive = True
msg = (await ctx.send(embed=discord.Embed(title='Chapter 1: What happened', color=discord.Color.dark_theme())))
(await scene_1(ctx, msg))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(content=f'Score: {score}
', embed=discord.Embed(title='Zombies', description=format_board(board_copy), color=discord.Color.blurple())))
if (not (len(bullets) == 5)):
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=3.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'π³'):
(await save_score(ctx, score))
return (await ctx.send('Ended the game!'))
bullets.append(Bullet(conversion[str(inp)], [5, 5]))
except asyncio.TimeoutError:
pass
for bullet in bullets:
board_copy[bullet.index[0]][bullet.index[1]] = 'G'
try:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
board_copy[bullet.index[0]][bullet.index[1]] = 'L'
except IndexError:
bullets.remove(bullet)
(board_copy, bullets, zombies, score) = check_zombie_collides(board_copy, bullets, zombies, score)
for zombie in zombies:
try:
board_copy[zombie.index[0]][zombie.index[1]] = 'G'
except IndexError:
pass
zombie.move()
board_copy[zombie.index[0]][zombie.index[1]] = 'z'
if (zombie.index == [5, 5]):
(await save_score(ctx, score))
return (await ctx.send(f'The zombie ate {ctx.author.display_name}'s brain!!!
Score: {score}'))
board_copy[5][5] = 'p'
if (len(zombies) < 5):
zombie_number = random.choice([0, 0, 0, 0, 1, 1, 1, 2, 2, 3])
directions_copy = copy.copy(directions)
for i in range(zombie_number):
direction = random.choice(directions_copy)
zombies.append(Zombie(direction))
directions_copy.remove(direction) | @bot.command()
async def zombies(ctx):
board_copy = copy.deepcopy(board)
update_cache(ctx)
bullets = []
zombies = []
score = 0
alive = True
msg = (await ctx.send(embed=discord.Embed(title='Chapter 1: What happened', color=discord.Color.dark_theme())))
(await scene_1(ctx, msg))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(content=f'Score: {score}
', embed=discord.Embed(title='Zombies', description=format_board(board_copy), color=discord.Color.blurple())))
if (not (len(bullets) == 5)):
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=3.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'π³'):
(await save_score(ctx, score))
return (await ctx.send('Ended the game!'))
bullets.append(Bullet(conversion[str(inp)], [5, 5]))
except asyncio.TimeoutError:
pass
for bullet in bullets:
board_copy[bullet.index[0]][bullet.index[1]] = 'G'
try:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
board_copy[bullet.index[0]][bullet.index[1]] = 'L'
except IndexError:
bullets.remove(bullet)
(board_copy, bullets, zombies, score) = check_zombie_collides(board_copy, bullets, zombies, score)
for zombie in zombies:
try:
board_copy[zombie.index[0]][zombie.index[1]] = 'G'
except IndexError:
pass
zombie.move()
board_copy[zombie.index[0]][zombie.index[1]] = 'z'
if (zombie.index == [5, 5]):
(await save_score(ctx, score))
return (await ctx.send(f'The zombie ate {ctx.author.display_name}'s brain!!!
Score: {score}'))
board_copy[5][5] = 'p'
if (len(zombies) < 5):
zombie_number = random.choice([0, 0, 0, 0, 1, 1, 1, 2, 2, 3])
directions_copy = copy.copy(directions)
for i in range(zombie_number):
direction = random.choice(directions_copy)
zombies.append(Zombie(direction))
directions_copy.remove(direction)<|docstring|>You're surrounded by zombies!!! don't worry tho, you have a gun. React to the reaction pointing in the direction you want *don't miss*<|endoftext|> |
ce2434e5ac250f88865cf2dbd09c1ca894321acee1157195ece30f9e0191b5a4 | @bot.command()
async def spaceshooter(ctx):
"You're in a spaceship now. move the spaceship to avoid and shoot at the aliens for score and make sure to net get hit"
update_cache(ctx)
msg = (await ctx.send(embed=discord.Embed(title='Chapter 2: The spaceship', color=discord.Color.dark_theme())))
(await scene_2(ctx, msg))
bord = [(['g'] * 5) for i in range(7)]
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
index = 2
bullets = []
aliens = []
lifes = 3
bullet_limit = 5
score = 0
bord_copy = copy.deepcopy(bord)
bord_copy[6][index] = 's'
scene_3_done = False
while True:
bord_copy = copy.deepcopy(bord)
if ((score >= 30) and (not scene_3_done)):
msg = (await scene_3(ctx))
scene_3_done = True
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=2.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'β¬
'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index -= 1
if (index < 0):
index = (len(bord_copy[0]) - 1)
elif (str(inp) == 'β‘'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index += 1
if (index == len(bord_copy[0])):
index = 0
elif (str(inp) == 'π³'):
(await ctx.send('Ended the game!'))
(await save_score(ctx, score))
return
except asyncio.TimeoutError:
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
for bullet in bullets:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
bord_copy[bullet.index[0]][bullet.index[1]] = 'L'
if ((random.randint(1, 10) >= 5) and (len(aliens) <= 5)):
for _ in range(random.randrange(1, 3)):
alien = Alien()
while (alien.index in [a.index for a in aliens]):
alien = Alien()
aliens.append(alien)
for alien in aliens:
continue_ = False
for bullet in bullets:
if ((bullet.index == alien.index) or ([(bullet.index[0] + bullet.direction[0]), (bullet.index[1] + bullet.direction[1])] == alien.index)):
bord_copy[bullet.index[0]][bullet.index[1]] = 'g'
bullets.remove(bullet)
aliens.remove(alien)
continue_ = True
score += 1
break
if continue_:
continue
alien.move()
if (alien.index == [6, index]):
lifes -= 1
(await ctx.send(f'You have {lifes} lifes left'))
aliens.remove(alien)
if (lifes <= 0):
(await save_score(ctx, score))
return (await ctx.send(f'''You don't have any more lifes!!!
Score: {score}'''))
continue
elif (alien.index[0] == len(bord_copy)):
aliens.remove(alien)
continue
bord_copy[alien.index[0]][alien.index[1]] = 'a'
bord_copy[6][index] = 's'
embed = discord.Embed(title='Aliens', description=format_board(bord_copy), color=discord.Color.blurple())
(await msg.edit(content=f'Score: {score}', embed=embed)) | You're in a spaceship now. move the spaceship to avoid and shoot at the aliens for score and make sure to net get hit | src/main.py | spaceshooter | andrewthederp/Documatic-Hackathon | 1 | python | @bot.command()
async def spaceshooter(ctx):
update_cache(ctx)
msg = (await ctx.send(embed=discord.Embed(title='Chapter 2: The spaceship', color=discord.Color.dark_theme())))
(await scene_2(ctx, msg))
bord = [(['g'] * 5) for i in range(7)]
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
index = 2
bullets = []
aliens = []
lifes = 3
bullet_limit = 5
score = 0
bord_copy = copy.deepcopy(bord)
bord_copy[6][index] = 's'
scene_3_done = False
while True:
bord_copy = copy.deepcopy(bord)
if ((score >= 30) and (not scene_3_done)):
msg = (await scene_3(ctx))
scene_3_done = True
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=2.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'β¬
'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index -= 1
if (index < 0):
index = (len(bord_copy[0]) - 1)
elif (str(inp) == 'β‘'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index += 1
if (index == len(bord_copy[0])):
index = 0
elif (str(inp) == 'π³'):
(await ctx.send('Ended the game!'))
(await save_score(ctx, score))
return
except asyncio.TimeoutError:
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
for bullet in bullets:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
bord_copy[bullet.index[0]][bullet.index[1]] = 'L'
if ((random.randint(1, 10) >= 5) and (len(aliens) <= 5)):
for _ in range(random.randrange(1, 3)):
alien = Alien()
while (alien.index in [a.index for a in aliens]):
alien = Alien()
aliens.append(alien)
for alien in aliens:
continue_ = False
for bullet in bullets:
if ((bullet.index == alien.index) or ([(bullet.index[0] + bullet.direction[0]), (bullet.index[1] + bullet.direction[1])] == alien.index)):
bord_copy[bullet.index[0]][bullet.index[1]] = 'g'
bullets.remove(bullet)
aliens.remove(alien)
continue_ = True
score += 1
break
if continue_:
continue
alien.move()
if (alien.index == [6, index]):
lifes -= 1
(await ctx.send(f'You have {lifes} lifes left'))
aliens.remove(alien)
if (lifes <= 0):
(await save_score(ctx, score))
return (await ctx.send(f'You don't have any more lifes!!!
Score: {score}'))
continue
elif (alien.index[0] == len(bord_copy)):
aliens.remove(alien)
continue
bord_copy[alien.index[0]][alien.index[1]] = 'a'
bord_copy[6][index] = 's'
embed = discord.Embed(title='Aliens', description=format_board(bord_copy), color=discord.Color.blurple())
(await msg.edit(content=f'Score: {score}', embed=embed)) | @bot.command()
async def spaceshooter(ctx):
update_cache(ctx)
msg = (await ctx.send(embed=discord.Embed(title='Chapter 2: The spaceship', color=discord.Color.dark_theme())))
(await scene_2(ctx, msg))
bord = [(['g'] * 5) for i in range(7)]
emojis = ['β¬
', 'π³', 'β‘']
for emoji in emojis:
(await msg.add_reaction(emoji))
index = 2
bullets = []
aliens = []
lifes = 3
bullet_limit = 5
score = 0
bord_copy = copy.deepcopy(bord)
bord_copy[6][index] = 's'
scene_3_done = False
while True:
bord_copy = copy.deepcopy(bord)
if ((score >= 30) and (not scene_3_done)):
msg = (await scene_3(ctx))
scene_3_done = True
try:
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg))), timeout=2.5))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
if (str(inp) == 'β¬
'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index -= 1
if (index < 0):
index = (len(bord_copy[0]) - 1)
elif (str(inp) == 'β‘'):
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
index += 1
if (index == len(bord_copy[0])):
index = 0
elif (str(inp) == 'π³'):
(await ctx.send('Ended the game!'))
(await save_score(ctx, score))
return
except asyncio.TimeoutError:
if (not (len(bullets) == bullet_limit)):
bullets.append(Bullet(UP, [6, index]))
for bullet in bullets:
bullet.move()
if (bullet.index[0] < 0):
bullets.remove(bullet)
continue
bord_copy[bullet.index[0]][bullet.index[1]] = 'L'
if ((random.randint(1, 10) >= 5) and (len(aliens) <= 5)):
for _ in range(random.randrange(1, 3)):
alien = Alien()
while (alien.index in [a.index for a in aliens]):
alien = Alien()
aliens.append(alien)
for alien in aliens:
continue_ = False
for bullet in bullets:
if ((bullet.index == alien.index) or ([(bullet.index[0] + bullet.direction[0]), (bullet.index[1] + bullet.direction[1])] == alien.index)):
bord_copy[bullet.index[0]][bullet.index[1]] = 'g'
bullets.remove(bullet)
aliens.remove(alien)
continue_ = True
score += 1
break
if continue_:
continue
alien.move()
if (alien.index == [6, index]):
lifes -= 1
(await ctx.send(f'You have {lifes} lifes left'))
aliens.remove(alien)
if (lifes <= 0):
(await save_score(ctx, score))
return (await ctx.send(f'You don't have any more lifes!!!
Score: {score}'))
continue
elif (alien.index[0] == len(bord_copy)):
aliens.remove(alien)
continue
bord_copy[alien.index[0]][alien.index[1]] = 'a'
bord_copy[6][index] = 's'
embed = discord.Embed(title='Aliens', description=format_board(bord_copy), color=discord.Color.blurple())
(await msg.edit(content=f'Score: {score}', embed=embed))<|docstring|>You're in a spaceship now. move the spaceship to avoid and shoot at the aliens for score and make sure to net get hit<|endoftext|> |
8fbbcf478fdcd2e09f94a4c01cea220d5482b19eb658d1ad4e1060b0f6429fbe | @bot.group(invoke_without_command=True)
async def maze(ctx, mode='storyline'):
'good and bad news, the bad news are that the spaceship is now destroyed the good news you\'re all on a planet with your space suits, the planet\'s gravity is messed up tho. Try to get to the :x: in the storyline mode" or play user made mazes in the usermade mode'
msg = None
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
if (mode.lower() not in ['storyline', 'usermade']):
return (await ctx.send(f"""{mode} isn't a valid mode, available modes: "storyline"/"usermade""""))
elif (mode.lower() == 'storyline'):
mazes = ['wwwwwwwwww\nwp wx w\nw w\nwwwwwwwwww\n', 'wwwwwwwwww\nwp wx w\nw w\nw wwwwwwww\n', 'w wwwwwwww\nwpw w\nw w wwww w\nw w w w w\nw w wx w w\nw w ww w w\nw w w w\nw wwwwww w\nw w\nwwwwwwwwww\n', 'ww ww\nwp w\n \nww \n ww\n xw\n w ', 'ww www\nwp ww\n \n ww\nww wx w\nw w\nw \nw ww\nww www', 'wwwwwwww\nwp w w\nw w\nw w\nww w\nw x w\nw w w\n ', 'wwwwwww\nwp w\nw w\nwbwwwbw\nw w\nw xw\nwwwwwww', ' w \nwpw w\n wwww \n w \n \n wxw \nw www \n w ww', 'wwwwwlw\nwdd w\ndpdx w\nw www w\nw u\nwrwwwww', 'wpw wwwwwwwwwww\nw u ww \nw www ww ww w\nw ww ww w\nwwwwwwwww ww w\nww w ww w\nw lw \n www wwwwwww\nw wwx w\nwwwwwww w\n w\n wwwww w\nw \nww wwwwwwrw']
msg = (await scene_4(ctx))
for emoji in emojis:
(await msg.add_reaction(emoji))
else:
try:
f = open('levels.txt', mode='r')
except FileNotFoundError:
return (await ctx.send(f'No user made mazes :pensive:. You could be the first tho, use the `{ctx.prefix}maze add` command!'))
mazes = f.readlines()
mazes = [maze[:(- 1)] for maze in mazes]
random.shuffle(mazes)
usermade = (False if (mode.lower() == 'storyline') else True)
for maze in mazes:
lst = []
for line in maze.split(('\\n' if usermade else '\n')):
lst.append(list(line))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
if msg:
(await msg.edit(embed=embed))
else:
msg = (await ctx.send(embed=embed))
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(lst, x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if (x == None):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won!', delete_after=5))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p'
if (not usermade):
update_cache(ctx) | good and bad news, the bad news are that the spaceship is now destroyed the good news you're all on a planet with your space suits, the planet's gravity is messed up tho. Try to get to the :x: in the storyline mode" or play user made mazes in the usermade mode | src/main.py | maze | andrewthederp/Documatic-Hackathon | 1 | python | @bot.group(invoke_without_command=True)
async def maze(ctx, mode='storyline'):
'good and bad news, the bad news are that the spaceship is now destroyed the good news you\'re all on a planet with your space suits, the planet\'s gravity is messed up tho. Try to get to the :x: in the storyline mode" or play user made mazes in the usermade mode'
msg = None
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
if (mode.lower() not in ['storyline', 'usermade']):
return (await ctx.send(f"{mode} isn't a valid mode, available modes: "storyline"/"usermade))
elif (mode.lower() == 'storyline'):
mazes = ['wwwwwwwwww\nwp wx w\nw w\nwwwwwwwwww\n', 'wwwwwwwwww\nwp wx w\nw w\nw wwwwwwww\n', 'w wwwwwwww\nwpw w\nw w wwww w\nw w w w w\nw w wx w w\nw w ww w w\nw w w w\nw wwwwww w\nw w\nwwwwwwwwww\n', 'ww ww\nwp w\n \nww \n ww\n xw\n w ', 'ww www\nwp ww\n \n ww\nww wx w\nw w\nw \nw ww\nww www', 'wwwwwwww\nwp w w\nw w\nw w\nww w\nw x w\nw w w\n ', 'wwwwwww\nwp w\nw w\nwbwwwbw\nw w\nw xw\nwwwwwww', ' w \nwpw w\n wwww \n w \n \n wxw \nw www \n w ww', 'wwwwwlw\nwdd w\ndpdx w\nw www w\nw u\nwrwwwww', 'wpw wwwwwwwwwww\nw u ww \nw www ww ww w\nw ww ww w\nwwwwwwwww ww w\nww w ww w\nw lw \n www wwwwwww\nw wwx w\nwwwwwww w\n w\n wwwww w\nw \nww wwwwwwrw']
msg = (await scene_4(ctx))
for emoji in emojis:
(await msg.add_reaction(emoji))
else:
try:
f = open('levels.txt', mode='r')
except FileNotFoundError:
return (await ctx.send(f'No user made mazes :pensive:. You could be the first tho, use the `{ctx.prefix}maze add` command!'))
mazes = f.readlines()
mazes = [maze[:(- 1)] for maze in mazes]
random.shuffle(mazes)
usermade = (False if (mode.lower() == 'storyline') else True)
for maze in mazes:
lst = []
for line in maze.split(('\\n' if usermade else '\n')):
lst.append(list(line))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
if msg:
(await msg.edit(embed=embed))
else:
msg = (await ctx.send(embed=embed))
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(lst, x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if (x == None):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won!', delete_after=5))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p'
if (not usermade):
update_cache(ctx) | @bot.group(invoke_without_command=True)
async def maze(ctx, mode='storyline'):
'good and bad news, the bad news are that the spaceship is now destroyed the good news you\'re all on a planet with your space suits, the planet\'s gravity is messed up tho. Try to get to the :x: in the storyline mode" or play user made mazes in the usermade mode'
msg = None
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
if (mode.lower() not in ['storyline', 'usermade']):
return (await ctx.send(f"{mode} isn't a valid mode, available modes: "storyline"/"usermade))
elif (mode.lower() == 'storyline'):
mazes = ['wwwwwwwwww\nwp wx w\nw w\nwwwwwwwwww\n', 'wwwwwwwwww\nwp wx w\nw w\nw wwwwwwww\n', 'w wwwwwwww\nwpw w\nw w wwww w\nw w w w w\nw w wx w w\nw w ww w w\nw w w w\nw wwwwww w\nw w\nwwwwwwwwww\n', 'ww ww\nwp w\n \nww \n ww\n xw\n w ', 'ww www\nwp ww\n \n ww\nww wx w\nw w\nw \nw ww\nww www', 'wwwwwwww\nwp w w\nw w\nw w\nww w\nw x w\nw w w\n ', 'wwwwwww\nwp w\nw w\nwbwwwbw\nw w\nw xw\nwwwwwww', ' w \nwpw w\n wwww \n w \n \n wxw \nw www \n w ww', 'wwwwwlw\nwdd w\ndpdx w\nw www w\nw u\nwrwwwww', 'wpw wwwwwwwwwww\nw u ww \nw www ww ww w\nw ww ww w\nwwwwwwwww ww w\nww w ww w\nw lw \n www wwwwwww\nw wwx w\nwwwwwww w\n w\n wwwww w\nw \nww wwwwwwrw']
msg = (await scene_4(ctx))
for emoji in emojis:
(await msg.add_reaction(emoji))
else:
try:
f = open('levels.txt', mode='r')
except FileNotFoundError:
return (await ctx.send(f'No user made mazes :pensive:. You could be the first tho, use the `{ctx.prefix}maze add` command!'))
mazes = f.readlines()
mazes = [maze[:(- 1)] for maze in mazes]
random.shuffle(mazes)
usermade = (False if (mode.lower() == 'storyline') else True)
for maze in mazes:
lst = []
for line in maze.split(('\\n' if usermade else '\n')):
lst.append(list(line))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
if msg:
(await msg.edit(embed=embed))
else:
msg = (await ctx.send(embed=embed))
for emoji in emojis:
(await msg.add_reaction(emoji))
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(lst, x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if (x == None):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won!', delete_after=5))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p'
if (not usermade):
update_cache(ctx)<|docstring|>good and bad news, the bad news are that the spaceship is now destroyed the good news you're all on a planet with your space suits, the planet's gravity is messed up tho. Try to get to the :x: in the storyline mode" or play user made mazes in the usermade mode<|endoftext|> |
d575b53abc258efdebc0bad1e19c5d78e44c981ea2e443660de312c0bb98a8f9 | @maze.command()
async def add(ctx, *, maze):
'A way to add your very own maze'
maze = maze.lower()
if (maze.startswith('```') and maze.endswith('```')):
maze = '\n'.join(maze.split('\n')[1:])[:3]
if ('p' not in maze):
return (await ctx.send('There is no player'))
elif ('x' not in maze):
return (await ctx.send('There is no exit point'))
elif (maze.count('p') > 1):
return (await ctx.send("Can't have multiple players at the same time"))
elif (maze.count('x') > 1):
return (await ctx.send("Can't have multiple exit points at the same time"))
lst = []
biggest_length = sorted([len(i) for i in maze.split('\n')])[(- 1)]
for line in maze.split('\n'):
for char in line:
if (char not in ['w', ' ', 'p', 'x', 'u', 'd', 'r', 'l', 'b']):
return (await ctx.send(f'Invalid syntax: unrecognized item "{char}"'))
if (len(line) != biggest_length):
line += (' ' * (biggest_length - len(line)))
lst.append(list(line))
if ((len(lst) < 3) or (len(lst[0]) < 3)):
return (await ctx.send('The maze must be atleast 3x3 big'))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
try:
msg = (await ctx.send(embed=embed))
except discord.HTTPException:
return (await ctx.send(f'The maze is too big ({len(embed.description)}/4096)'))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
origin_lst = copy.deepcopy(lst)
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(lst, x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if ((x == None) or isinstance(x, str)):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died!'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won! *saving maze*'))
save_maze('\\n'.join([''.join(i) for i in origin_lst]))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p' | A way to add your very own maze | src/main.py | add | andrewthederp/Documatic-Hackathon | 1 | python | @maze.command()
async def add(ctx, *, maze):
maze = maze.lower()
if (maze.startswith('```') and maze.endswith('```')):
maze = '\n'.join(maze.split('\n')[1:])[:3]
if ('p' not in maze):
return (await ctx.send('There is no player'))
elif ('x' not in maze):
return (await ctx.send('There is no exit point'))
elif (maze.count('p') > 1):
return (await ctx.send("Can't have multiple players at the same time"))
elif (maze.count('x') > 1):
return (await ctx.send("Can't have multiple exit points at the same time"))
lst = []
biggest_length = sorted([len(i) for i in maze.split('\n')])[(- 1)]
for line in maze.split('\n'):
for char in line:
if (char not in ['w', ' ', 'p', 'x', 'u', 'd', 'r', 'l', 'b']):
return (await ctx.send(f'Invalid syntax: unrecognized item "{char}"'))
if (len(line) != biggest_length):
line += (' ' * (biggest_length - len(line)))
lst.append(list(line))
if ((len(lst) < 3) or (len(lst[0]) < 3)):
return (await ctx.send('The maze must be atleast 3x3 big'))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
try:
msg = (await ctx.send(embed=embed))
except discord.HTTPException:
return (await ctx.send(f'The maze is too big ({len(embed.description)}/4096)'))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
origin_lst = copy.deepcopy(lst)
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(lst, x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if ((x == None) or isinstance(x, str)):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died!'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won! *saving maze*'))
save_maze('\\n'.join([.join(i) for i in origin_lst]))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p' | @maze.command()
async def add(ctx, *, maze):
maze = maze.lower()
if (maze.startswith('```') and maze.endswith('```')):
maze = '\n'.join(maze.split('\n')[1:])[:3]
if ('p' not in maze):
return (await ctx.send('There is no player'))
elif ('x' not in maze):
return (await ctx.send('There is no exit point'))
elif (maze.count('p') > 1):
return (await ctx.send("Can't have multiple players at the same time"))
elif (maze.count('x') > 1):
return (await ctx.send("Can't have multiple exit points at the same time"))
lst = []
biggest_length = sorted([len(i) for i in maze.split('\n')])[(- 1)]
for line in maze.split('\n'):
for char in line:
if (char not in ['w', ' ', 'p', 'x', 'u', 'd', 'r', 'l', 'b']):
return (await ctx.send(f'Invalid syntax: unrecognized item "{char}"'))
if (len(line) != biggest_length):
line += (' ' * (biggest_length - len(line)))
lst.append(list(line))
if ((len(lst) < 3) or (len(lst[0]) < 3)):
return (await ctx.send('The maze must be atleast 3x3 big'))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
try:
msg = (await ctx.send(embed=embed))
except discord.HTTPException:
return (await ctx.send(f'The maze is too big ({len(embed.description)}/4096)'))
emojis = ['β¬', 'β¬
', 'β‘', 'β¬', 'π³']
for emoji in emojis:
(await msg.add_reaction(emoji))
origin_lst = copy.deepcopy(lst)
while True:
(await msg.edit(embed=discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())))
(inp, _) = (await bot.wait_for('reaction_add', check=(lambda r, u: ((str(r) in emojis) and (u == ctx.author) and (r.message == msg)))))
try:
(await msg.remove_reaction(str(inp), ctx.author))
except discord.Forbidden:
pass
(lst, x, y) = get_player(lst)
lst[x][y] = ' '
if (str(inp) == 'π³'):
return (await ctx.send('Ended the game!'))
(x, y) = go_direction(lst, conversion[str(inp)], (x, y))
if ((x == None) or isinstance(x, str)):
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
return (await ctx.send('You died!'))
if (lst[x][y] == 'x'):
lst[x][y] = 'p'
(await ctx.send('You won! *saving maze*'))
save_maze('\\n'.join([.join(i) for i in origin_lst]))
embed = discord.Embed(title='Maze', description=format_board(lst), color=discord.Color.blurple())
(await msg.edit(embed=embed))
(await asyncio.sleep(1))
break
lst[x][y] = 'p'<|docstring|>A way to add your very own maze<|endoftext|> |
700e67af1653aa06d77c56c5dc0b94d007a0435333615448c330756654c167cc | @bot.command()
async def speed(ctx, member: discord.Member=None):
'A simple game where you have 5 seconds to send the coordinates of the colored circles, if a member is selected it\'s a race to 30 points, otherwise it goes on until you send "end"/"stop"/"cancel"'
if member:
if (member.bot or (member == ctx.author)):
member = None
score = 0
else:
scores = {ctx.author: 0, member: 0}
else:
score = 0
board = [(['g'] * 5) for _ in range(5)]
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board)), color=discord.Color.blurple())
msg = (await ctx.send(embed=e))
while True:
board_copy = copy.deepcopy(board)
board_copy = summon_blocks(board_copy)
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board_copy)), color=discord.Color.blurple())
(await msg.edit(embed=e))
try:
inp = (await bot.wait_for('message', check=(lambda m: ((m.author in [ctx.author, member]) and (m.channel == ctx.channel))), timeout=5))
except asyncio.TimeoutError:
pass
else:
if (inp.content.lower() in ['end', 'stop', 'cancel']):
(await ctx.send('Stopped the game!'))
return (await save_score(ctx, score))
try:
(await inp.delete())
except discord.Forbidden:
pass
coors = convert(inp.content)
for coor in coors:
(x, y) = coor
if (board_copy[x][y] == 'b'):
if member:
scores[inp.author] += 1
if (scores[inp.author] >= 30):
return (await ctx.send(f'{inp.author.mention} won!!!'))
else:
score += 1
elif member:
if (scores[inp.author] > 0):
scores[inp.author] -= 1
elif (score > 0):
score -= 1 | A simple game where you have 5 seconds to send the coordinates of the colored circles, if a member is selected it's a race to 30 points, otherwise it goes on until you send "end"/"stop"/"cancel" | src/main.py | speed | andrewthederp/Documatic-Hackathon | 1 | python | @bot.command()
async def speed(ctx, member: discord.Member=None):
'A simple game where you have 5 seconds to send the coordinates of the colored circles, if a member is selected it\'s a race to 30 points, otherwise it goes on until you send "end"/"stop"/"cancel"'
if member:
if (member.bot or (member == ctx.author)):
member = None
score = 0
else:
scores = {ctx.author: 0, member: 0}
else:
score = 0
board = [(['g'] * 5) for _ in range(5)]
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board)), color=discord.Color.blurple())
msg = (await ctx.send(embed=e))
while True:
board_copy = copy.deepcopy(board)
board_copy = summon_blocks(board_copy)
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board_copy)), color=discord.Color.blurple())
(await msg.edit(embed=e))
try:
inp = (await bot.wait_for('message', check=(lambda m: ((m.author in [ctx.author, member]) and (m.channel == ctx.channel))), timeout=5))
except asyncio.TimeoutError:
pass
else:
if (inp.content.lower() in ['end', 'stop', 'cancel']):
(await ctx.send('Stopped the game!'))
return (await save_score(ctx, score))
try:
(await inp.delete())
except discord.Forbidden:
pass
coors = convert(inp.content)
for coor in coors:
(x, y) = coor
if (board_copy[x][y] == 'b'):
if member:
scores[inp.author] += 1
if (scores[inp.author] >= 30):
return (await ctx.send(f'{inp.author.mention} won!!!'))
else:
score += 1
elif member:
if (scores[inp.author] > 0):
scores[inp.author] -= 1
elif (score > 0):
score -= 1 | @bot.command()
async def speed(ctx, member: discord.Member=None):
'A simple game where you have 5 seconds to send the coordinates of the colored circles, if a member is selected it\'s a race to 30 points, otherwise it goes on until you send "end"/"stop"/"cancel"'
if member:
if (member.bot or (member == ctx.author)):
member = None
score = 0
else:
scores = {ctx.author: 0, member: 0}
else:
score = 0
board = [(['g'] * 5) for _ in range(5)]
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board)), color=discord.Color.blurple())
msg = (await ctx.send(embed=e))
while True:
board_copy = copy.deepcopy(board)
board_copy = summon_blocks(board_copy)
e = discord.Embed(title='Speed', description=(((f'{ctx.author.display_name} score: {scores[ctx.author]} | {member.display_name} score: {scores[member]}' if member else f'Score: {score}') + '\n') + format_speed_board(board_copy)), color=discord.Color.blurple())
(await msg.edit(embed=e))
try:
inp = (await bot.wait_for('message', check=(lambda m: ((m.author in [ctx.author, member]) and (m.channel == ctx.channel))), timeout=5))
except asyncio.TimeoutError:
pass
else:
if (inp.content.lower() in ['end', 'stop', 'cancel']):
(await ctx.send('Stopped the game!'))
return (await save_score(ctx, score))
try:
(await inp.delete())
except discord.Forbidden:
pass
coors = convert(inp.content)
for coor in coors:
(x, y) = coor
if (board_copy[x][y] == 'b'):
if member:
scores[inp.author] += 1
if (scores[inp.author] >= 30):
return (await ctx.send(f'{inp.author.mention} won!!!'))
else:
score += 1
elif member:
if (scores[inp.author] > 0):
scores[inp.author] -= 1
elif (score > 0):
score -= 1<|docstring|>A simple game where you have 5 seconds to send the coordinates of the colored circles, if a member is selected it's a race to 30 points, otherwise it goes on until you send "end"/"stop"/"cancel"<|endoftext|> |
569952ed8765faae8185a8296c16496d391f9519643c62e6bd6f0052a6ee15c2 | @bot.command(aliases=['botinfo', 'about'])
async def info(ctx):
'Some generic info'
embed = discord.Embed(title='Bot Info', description=f'I am a discord bot made by andreawthaderp#3031 for the documatic hackathon', color=discord.Color.dark_theme())
(await ctx.send(embed=embed)) | Some generic info | src/main.py | info | andrewthederp/Documatic-Hackathon | 1 | python | @bot.command(aliases=['botinfo', 'about'])
async def info(ctx):
embed = discord.Embed(title='Bot Info', description=f'I am a discord bot made by andreawthaderp#3031 for the documatic hackathon', color=discord.Color.dark_theme())
(await ctx.send(embed=embed)) | @bot.command(aliases=['botinfo', 'about'])
async def info(ctx):
embed = discord.Embed(title='Bot Info', description=f'I am a discord bot made by andreawthaderp#3031 for the documatic hackathon', color=discord.Color.dark_theme())
(await ctx.send(embed=embed))<|docstring|>Some generic info<|endoftext|> |
cdd524b725851a64178d227b4e02f2e2d29cb2ef8749ea2a323bfabd1f92cb9a | @bot.command(aliases=['lb'])
@commands.guild_only()
async def leaderboard(ctx, command_name, entries=5):
'a way to see the top x scores of a certain game'
cmd = bot.get_command(command_name)
if (not cmd):
return (await ctx.send(f'The command {command_name} does not exist'))
embed = discord.Embed(title=f'Leaderboard', description=f'''Top {entries} {command_name} scores
''', colour=2416859)
index = 0
async with bot.db.execute('SELECT author_id, score FROM scores WHERE command_name = ? ORDER BY score DESC LIMIT ?', (cmd.name, entries)) as cursor:
async for entry in cursor:
(member_id, score) = entry
member = (await bot.fetch_user(member_id))
index += 1
if (index == 1):
emoji = 'π₯'
elif (index == 2):
emoji = 'π₯'
elif (index == 3):
emoji = 'π₯'
else:
emoji = 'πΉ'
embed.description += f'''**{emoji} #{index} {member.mention}**
Score: `{score}`
'''
if (not index):
return (await ctx.send(f'No scores in the database for {command_name}'))
(await ctx.send(embed=embed)) | a way to see the top x scores of a certain game | src/main.py | leaderboard | andrewthederp/Documatic-Hackathon | 1 | python | @bot.command(aliases=['lb'])
@commands.guild_only()
async def leaderboard(ctx, command_name, entries=5):
cmd = bot.get_command(command_name)
if (not cmd):
return (await ctx.send(f'The command {command_name} does not exist'))
embed = discord.Embed(title=f'Leaderboard', description=f'Top {entries} {command_name} scores
', colour=2416859)
index = 0
async with bot.db.execute('SELECT author_id, score FROM scores WHERE command_name = ? ORDER BY score DESC LIMIT ?', (cmd.name, entries)) as cursor:
async for entry in cursor:
(member_id, score) = entry
member = (await bot.fetch_user(member_id))
index += 1
if (index == 1):
emoji = 'π₯'
elif (index == 2):
emoji = 'π₯'
elif (index == 3):
emoji = 'π₯'
else:
emoji = 'πΉ'
embed.description += f'**{emoji} #{index} {member.mention}**
Score: `{score}`
'
if (not index):
return (await ctx.send(f'No scores in the database for {command_name}'))
(await ctx.send(embed=embed)) | @bot.command(aliases=['lb'])
@commands.guild_only()
async def leaderboard(ctx, command_name, entries=5):
cmd = bot.get_command(command_name)
if (not cmd):
return (await ctx.send(f'The command {command_name} does not exist'))
embed = discord.Embed(title=f'Leaderboard', description=f'Top {entries} {command_name} scores
', colour=2416859)
index = 0
async with bot.db.execute('SELECT author_id, score FROM scores WHERE command_name = ? ORDER BY score DESC LIMIT ?', (cmd.name, entries)) as cursor:
async for entry in cursor:
(member_id, score) = entry
member = (await bot.fetch_user(member_id))
index += 1
if (index == 1):
emoji = 'π₯'
elif (index == 2):
emoji = 'π₯'
elif (index == 3):
emoji = 'π₯'
else:
emoji = 'πΉ'
embed.description += f'**{emoji} #{index} {member.mention}**
Score: `{score}`
'
if (not index):
return (await ctx.send(f'No scores in the database for {command_name}'))
(await ctx.send(embed=embed))<|docstring|>a way to see the top x scores of a certain game<|endoftext|> |
dff94f256d13ac00c01a28270eeed576d337dbedcb2a1880b1c46ae193a5ebc7 | @classmethod
def create_from_document(cls, document):
'Create a Relat from a document\n\n Arguments:\n document (dict): dict used for creating the document\n\n Returns:\n a Relat instance\n\n '
story = Story(**document)
instance = cls(story.title)
instance.story = story
return instance | Create a Relat from a document
Arguments:
document (dict): dict used for creating the document
Returns:
a Relat instance | relaty/relat.py | create_from_document | PaPablo/relaty | 0 | python | @classmethod
def create_from_document(cls, document):
'Create a Relat from a document\n\n Arguments:\n document (dict): dict used for creating the document\n\n Returns:\n a Relat instance\n\n '
story = Story(**document)
instance = cls(story.title)
instance.story = story
return instance | @classmethod
def create_from_document(cls, document):
'Create a Relat from a document\n\n Arguments:\n document (dict): dict used for creating the document\n\n Returns:\n a Relat instance\n\n '
story = Story(**document)
instance = cls(story.title)
instance.story = story
return instance<|docstring|>Create a Relat from a document
Arguments:
document (dict): dict used for creating the document
Returns:
a Relat instance<|endoftext|> |
2f3d0d0c5789d405498f552a1131a9b490de09b32227fa00487e8f01909270e7 | @property
def get_number_endings(self):
'Obtain the number of endings of the story\n\n Since any story in Relaty is represented in the shape\n of a tree, and ending is just a leaf.\n\n Returns:\n number of endings in the story\n '
return self.story.get_number_endings | Obtain the number of endings of the story
Since any story in Relaty is represented in the shape
of a tree, and ending is just a leaf.
Returns:
number of endings in the story | relaty/relat.py | get_number_endings | PaPablo/relaty | 0 | python | @property
def get_number_endings(self):
'Obtain the number of endings of the story\n\n Since any story in Relaty is represented in the shape\n of a tree, and ending is just a leaf.\n\n Returns:\n number of endings in the story\n '
return self.story.get_number_endings | @property
def get_number_endings(self):
'Obtain the number of endings of the story\n\n Since any story in Relaty is represented in the shape\n of a tree, and ending is just a leaf.\n\n Returns:\n number of endings in the story\n '
return self.story.get_number_endings<|docstring|>Obtain the number of endings of the story
Since any story in Relaty is represented in the shape
of a tree, and ending is just a leaf.
Returns:
number of endings in the story<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.