How to use _get_title method in pyatom

Best Python code snippet using pyatom_python

base.py

Source:base.py Github

copy

Full Screen

...54 save_vars = self._get_save_vars(exclude=['ch_info_'])55 write_hdf5(56 fname,57 save_vars,58 title=_get_title(self.__class__, self.comment),59 overwrite=overwrite, slash='replace')60 def _get_title(self):61 return _get_title(self.__class__, self.comment)62 @classmethod63 def _read(cls, fname, comment='default'):64 return _read_container(cls, fname, comment=comment)65class BaseMarker(BaseContainer):66 """Base class for M/EEG markers"""67 def __init__(self, tmin, tmax, comment):68 BaseContainer.__init__(self, comment=comment)69 self.tmin = tmin70 self.tmax = tmax71 @property72 def _axis_map(self):73 raise NotImplementedError('This should be in every marker')74 def fit(self, epochs):75 self._fit(epochs)76 self.ch_info_ = epochs.info77 return self78 def transform(self, epochs):79 self._transform(epochs)80 return self81 def _get_title(self):82 return _get_title(self.__class__, self.comment)83 def _get_preserve_axis(self, targets):84 to_preserve = []85 if not isinstance(targets, list):86 targets = [targets]87 for elem in targets:88 if 'topography' == elem or 'channels' == elem:89 to_preserve.append('channels')90 elif 'times' == elem:91 to_preserve.append('times')92 elif 'epochs' == elem:93 to_preserve.append('epochs')94 if any(x not in self._axis_map.keys() for x in to_preserve):95 raise ValueError('Cannot reduce {} to {}'.format(96 self._get_title(), targets))97 return to_preserve98 def _reduce_to(self, reduction_func, target, picks):99 if not hasattr(self, 'data_'):100 raise ValueError('You did not fit me. Do it again after fitting '101 'some data!')102 out, funcs = self._prepare_reduction(reduction_func, target, picks)103 for func in funcs:104 out = func(out, axis=0)105 return out106 def reduce_to_epochs(self, reduction_func, picks=None):107 """Reduce marker to a single value per epoch.108 Parameters109 ----------110 reduction_func : list of dictionaries.111 Each dictionary should have two keys: 'axis' and 'function'.112 The marker is going to be reduced following the order of the list.113 Selecting the corresponding axis and applying the corresponding114 function.115 picks : dictionary of axis to array.116 Before appling the reduction function, the corresponding axis will117 be subselected by picks. A value of None indicates all the118 elements.119 Example:120 reduction_func = [121 {'axis': 'frequency', 'function': np.sum},122 {'axis': 'channels', 'function': np.mean},123 {'axis': 'epochs', 'function': np.mean}]124 picks = {'epochs': None, 'channels': np.arange(224)}125 Returns126 -------127 out : np.ndarray of float, shape(n_epochs,)128 The value of the marker for each epoch.129 """130 return self._reduce_to(131 reduction_func, target='epochs', picks=picks)132 def reduce_to_topo(self, reduction_func, picks=None):133 return self._reduce_to(134 reduction_func, target='topography', picks=picks)135 def reduce_to_scalar(self, reduction_func, picks=None):136 return self._reduce_to(reduction_func, target='scalar', picks=picks)137 def compress(self, reduction_func):138 if not hasattr(self, 'data_'):139 raise ValueError('You did not fit me. Do it again after fitting '140 'some data!')141 if 'epochs' in self._axis_map:142 axis = self._axis_map['epochs']143 logger.info(144 'Compressing {} on axis {} (epochs)'.format(145 self._get_title(), axis)146 )147 data = reduction_func(self.data_, axis=axis)148 # Keep dimension149 self.data_ = np.expand_dims(data, axis=axis)150 def _prepare_data(self, picks, target):151 data = self.data_152 to_preserve = self._get_preserve_axis(target)153 if picks is not None:154 if any([x not in self._axis_map for x in picks.keys()]):155 raise ValueError('Picking is not compatible for {}'.format(156 self._get_title()))157 for axis, ax_picks in picks.items():158 if axis in to_preserve:159 continue160 if ax_picks is not None:161 this_axis = self._axis_map[axis]162 data = (data.swapaxes(this_axis, 0)[ax_picks, ...]163 .swapaxes(0, this_axis))164 return data165 def _prepare_reduction(self, reduction_func, target, picks,166 return_axis=False):167 data = self._prepare_data(picks, target)168 _axis_map = self._axis_map169 funcs = list()170 axis_to_preserve = self._get_preserve_axis(target)171 if len(axis_to_preserve) > 0:172 removed_axis = []173 for this_axis_to_preserve in axis_to_preserve:174 removed_axis.append(_axis_map.pop(this_axis_to_preserve))175 if reduction_func is not None:176 reduction_func = [i for i in reduction_func177 if i['axis'] not in axis_to_preserve]178 permutation_list = list()179 permutation_axes = list()180 if reduction_func is None:181 for ax_name, remaining_axis in _axis_map.items():182 permutation_list.append(remaining_axis)183 permutation_axes.append(ax_name)184 funcs.append(np.mean)185 elif len(reduction_func) == len(_axis_map):186 for rec in reduction_func:187 this_axis = _axis_map.pop(rec['axis'])188 permutation_axes.append(rec['axis'])189 permutation_list.append(this_axis)190 funcs.append(rec['function'])191 else:192 raise ValueError('Run `python -c "import this"` to see '193 'why we will not tolerate these things')194 if len(axis_to_preserve) > 0:195 permutation_list += removed_axis196 logger.info('Reduction order for {}: {}'.format(197 self._get_title(), permutation_axes))198 data = np.transpose(data, permutation_list)199 if return_axis is False:200 out = data, funcs201 else:202 out = data, funcs, permutation_axes203 return out204class BaseTimeLocked(BaseMarker):205 def __init__(self, tmin, tmax, comment):206 BaseMarker.__init__(self, tmin, tmax, comment)207 def fit(self, epochs):208 self.ch_info_ = epochs.info209 self.shape_ = epochs.get_data().shape210 self.epochs_ = epochs211 self.data_ = epochs.get_data()212 return self213 def compress(self, reduction_func):214 logger.info(215 'TimeLocked markers cannot be compressed '216 'epoch-wise ({})'.format(self._get_title()))217 def save(self, fname, overwrite=False):218 if not isinstance(fname, Path):219 fname = Path(fname)220 self._save_info(fname, overwrite=overwrite)221 save_vars = self._get_save_vars(222 exclude=['ch_info_', 'data_', 'epochs_'])223 has_epochs = False224 with h5py.File(fname, 'r') as h5fid:225 if 'nice/data/epochs' in h5fid:226 has_epochs = True227 logger.info('Epochs already present in HDF5 file, '228 'will not be overwritten')229 if not has_epochs:230 epochs = self.epochs_231 logger.info('Writing epochs to HDF5 file')232 write_hdf5_mne_epochs(fname, epochs, overwrite=overwrite)233 write_hdf5(234 fname, save_vars, overwrite=overwrite,235 title=_get_title(self.__class__, self.comment), slash='replace')236 @classmethod237 def _read(cls, fname, epochs, comment='default'):238 return _read_time_locked(cls, fname=fname, epochs=epochs,239 comment=comment)240 def _get_title(self):241 return _get_title(self.__class__, self.comment)242class BaseDecoding(BaseMarker):243 def __init__(self, tmin, tmax, comment):244 BaseMarker.__init__(self, tmin, tmax, comment)245 def fit(self, epochs):246 self._fit(epochs)247 return self248 def _get_title(self):249 return _get_title(self.__class__, self.comment)250def _get_title(klass, comment):251 if issubclass(klass, BaseMarker):252 kind = 'marker'253 elif issubclass(klass, BaseContainer):254 kind = 'container'255 else:256 raise NotImplementedError('Oh no-- what is this?')257 return '/'.join([258 'nice', kind, klass.__name__, comment])259def _read_container(klass, fname, comment='default'):260 data = read_hdf5(fname, _get_title(klass, comment), slash='replace')261 init_params = {k: v for k, v in data.items() if not k.endswith('_')}262 attrs = {k: v for k, v in data.items() if k.endswith('_')}263 file_info = read_hdf5(fname, title='nice/data/ch_info', slash='replace')264 if 'filename' in file_info:265 del(file_info['filename'])266 attrs['ch_info_'] = Info(file_info)267 out = klass(**init_params)268 for k, v in attrs.items():269 if k.endswith('_'):270 setattr(out, k, v)271 return out272def _check_epochs_consistency(info1, info2, shape1, shape2):273 if version.parse(mne.__version__) < version.parse('0.24'):274 from mne.epochs import _compare_epochs_infos...

Full Screen

Full Screen

metadata.py

Source:metadata.py Github

copy

Full Screen

...11 super(MetadataTab, self).__init__(app, figurepage, client)12 self.content = None13 def _is_useable(self):14 return True15 def _get_title(self, title):16 return Paragraph(17 text=title,18 css_classes=['table-title'])19 def _get_no_params(self):20 return Paragraph(text="No parameters", css_classes=['table-info'])21 def _get_parameter_table(self, params):22 tablegen = TableGenerator()23 params = get_params(params)24 if len(params) == 0:25 return self._get_no_params()26 else:27 for k, v in params.items():28 params[k] = paramval2str(k, v)29 return tablegen.get_table(params)30 def _get_values_table(self, values):31 tablegen = TableGenerator()32 if len(values) == 0:33 values[''] = ''34 return tablegen.get_table(values)35 def _get_strategy(self, strategy):36 columns = []37 childs = []38 childs.append(self._get_title(f'Strategy: {obj2label(strategy)}'))39 childs.append(self._get_parameter_table(strategy.params))40 for o in strategy.observers:41 childs.append(self._get_title(f'Observer: {obj2label(o)}'))42 childs.append(self._get_parameter_table(o.params))43 for a in strategy.analyzers:44 childs.append(self._get_title(f'Analyzer: {obj2label(a)}{" [Analysis Table]" if hasattr(a, "get_analysis_table") else ""}'))45 childs.append(self._get_parameter_table(a.params))46 columns.append(column(childs))47 return columns48 def _get_indicators(self, strategy):49 columns = []50 childs = []51 inds = strategy.getindicators()52 for i in inds:53 if isinstance(i, bt.IndicatorBase):54 childs.append(self._get_title(55 f'Indicator: {obj2label(i)}@{obj2data(i)}'))56 childs.append(self._get_parameter_table(i.params))57 columns.append(column(childs))58 return columns59 def _get_datas(self, strategy):60 columns = []61 childs = []62 for data in strategy.datas:63 tabdata = {64 'DataName:': str(data._dataname).replace('|', '\\|'),65 'Timezone:': str(data._tz),66 'Live:': f'{"Yes" if data.islive() else "No"}',67 'Length:': len(data),68 'Granularity:': f'{data._compression} {bt.TimeFrame.getname(data._timeframe, data._compression)}',69 }70 # live trading does not have valid data parameters (other datas71 # might also not have)72 if not math.isinf(data.fromdate):73 tabdata['Time From:'] = str(bt.num2date(data.fromdate))74 if not math.isinf(data.todate):75 tabdata['Time To:'] = str(bt.num2date(data.todate))76 childs.append(self._get_title(f'Data Feed: {obj2label(data, True)}'))77 childs.append(self._get_values_table(tabdata))78 columns.append(column(childs))79 return columns80 def _get_metadata_columns(self, strategy):81 acolumns = []82 acolumns.extend(self._get_strategy(strategy))83 acolumns.extend(self._get_indicators(strategy))84 acolumns.extend(self._get_datas(strategy))85 return acolumns86 def _get_metadata_info(self):87 acolumns = self._get_metadata_columns(self._figurepage.strategy)88 info = gridplot(89 acolumns,90 ncols=self._app.scheme.metadata_tab_num_cols,...

Full Screen

Full Screen

export_MPDS.py

Source:export_MPDS.py Github

copy

Full Screen

...26 for _ in range(12):27 basename.append(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))28 return "".join(basename)29 @classmethod30 def _get_title(cls, term):31 return cls.human_names.get(term, term.capitalize())32 @classmethod33 def save_plot(cls, data, columns, plottype, fmt='json', **kwargs):34 """35 Exports the data in the following formats for plotting:36 csv: for any external plotting application37 json: for a web-app at https://mpds.io/visavis38 """39 cls._verify_export_dir()40 plot = {"use_visavis_type": plottype, "payload": {}}41 if isinstance(data, pd.DataFrame):42 iter_data = data.iterrows43 pointers = columns44 else:45 iter_data = lambda: enumerate(data)46 pointers = range(len(data[0]))47 if fmt == 'csv':48 fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".csv")49 f_export = open(fmt_export, "w")50 f_export.write("%s\n" % ",".join(map(str, columns)))51 for _, row in iter_data():52 f_export.write("%s\n" % ",".join([str(row[i]) for i in pointers]))53 f_export.close()54 else:55 fmt_export = os.path.join(cls.export_dir, cls._gen_basename() + ".json")56 f_export = open(fmt_export, "w")57 if plottype == 'bar':58 plot["payload"] = {"x": [], "y": [], "xtitle": cls._get_title(columns[0]), "ytitle": cls._get_title(columns[1])}59 for _, row in iter_data():60 plot["payload"]["x"].append(row[pointers[0]])61 plot["payload"]["y"].append(row[pointers[1]])62 elif plottype == 'plot3d':63 plot["payload"]["points"] = {"x": [], "y": [], "z": [], "labels": []}64 plot["payload"]["meshes"] = []65 plot["payload"]["xtitle"] = cls._get_title(columns[0])66 plot["payload"]["ytitle"] = cls._get_title(columns[1])67 plot["payload"]["ztitle"] = cls._get_title(columns[2])68 recent_mesh = 069 for _, row in iter_data():70 plot["payload"]["points"]["x"].append(row[pointers[0]])71 plot["payload"]["points"]["y"].append(row[pointers[1]])72 plot["payload"]["points"]["z"].append(row[pointers[2]])73 plot["payload"]["points"]["labels"].append(row[pointers[3]])74 if row[4] != recent_mesh:75 plot["payload"]["meshes"].append({"x": [], "y": [], "z": []})76 recent_mesh = row[4]77 if plot["payload"]["meshes"]:78 plot["payload"]["meshes"][-1]["x"].append(row[pointers[0]])79 plot["payload"]["meshes"][-1]["y"].append(row[pointers[1]])80 plot["payload"]["meshes"][-1]["z"].append(row[pointers[2]])81 if kwargs:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pyatom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful