code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_type_name(t): # Lookup in the mapping try: return __type_names[t] except KeyError: # Specific types if issubclass(t, six.integer_types): return _(u'Integer number') # Get name from the Type itself return six.text_type(t.__name__).capitalize()
Get a human-friendly name for the given type. :type t: type|None :rtype: unicode
def get_callable_name(c): if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) + u'()' else: return six.text_type(c)
Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode
def get_primitive_name(schema): try: return { const.COMPILED_TYPE.LITERAL: six.text_type, const.COMPILED_TYPE.TYPE: get_type_name, const.COMPILED_TYPE.ENUM: get_type_name, const.COMPILED_TYPE.CALLABLE: get_callable_name, const.COMPILED_TYPE.IT...
Get a human-friendly name for the given primitive. :param schema: Schema :type schema: * :rtype: unicode
def primitive_type(schema): schema_type = type(schema) # Literal if schema_type in const.literal_types: return const.COMPILED_TYPE.LITERAL # Enum elif Enum is not None and isinstance(schema, (EnumMeta, Enum)): return const.COMPILED_TYPE.ENUM # Type elif issubclass(schem...
Get schema type for the primitive argument. Note: it does treats markers & schemas as callables! :param schema: Value of a primitive type :type schema: * :return: const.COMPILED_TYPE.* :rtype: str|None
def commajoin_as_strings(iterable): return _(u',').join((six.text_type(i) for i in iterable))
Join the given iterable with ','
def prepare_topoplots(topo, values): values = np.atleast_2d(values) topomaps = [] for i in range(values.shape[0]): topo.set_values(values[i, :]) topo.create_map() topomaps.append(topo.get_map()) return topomaps
Prepare multiple topo maps for cached plotting. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_values`. Parameters ---------- topo : :class:`~eegtopo.topoplot.Topoplot` Scalp maps are created with this class values : array, shape = [...
def plot_topo(axis, topo, topomap, crange=None, offset=(0,0), plot_locations=True, plot_head=True): topo.set_map(topomap) h = topo.plot_map(axis, crange=crange, offset=offset) if plot_locations: topo.plot_locations(axis, offset=offset) if plot_head: topo.plot_head(axis...
Draw a topoplot in given axis. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- axis : axis Axis to draw into. topo : :class:`~eegtopo.topoplot.Topoplot` This object draws the topo plot topomap :...
def plot_connectivity_topos(layout='diagonal', topo=None, topomaps=None, fig=None): m = len(topomaps) if fig is None: fig = new_figure() if layout == 'diagonal': for i in range(m): ax = fig.add_subplot(m, m, i*(1+m) + 1) plot_topo(ax, topo, topomaps[i]) ...
Place topo plots in a figure suitable for connectivity visualization. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- layout : str 'diagonal' -> place topo plots on diagonal. otherwise -> place topo plo...
def plot_whiteness(var, h, repeats=1000, axis=None): pr, q0, q = var.test_whiteness(h, repeats, True) if axis is None: axis = current_axis() pdf, _, _ = axis.hist(q0, 30, normed=True, label='surrogate distribution') axis.plot([q,q], [0,np.max(pdf)], 'r-', label='fitted model') #df = ...
Draw distribution of the Portmanteu whiteness test. Parameters ---------- var : :class:`~scot.var.VARBase`-like object Vector autoregressive model (VAR) object whose residuals are tested for whiteness. h : int Maximum lag to include in the test. repeats : int, optional Numbe...
def singletrial(num_trials, skipstep=1): for t in range(0, num_trials, skipstep): trainset = [t] testset = [i for i in range(trainset[0])] + \ [i for i in range(trainset[-1] + 1, num_trials)] testset = sort([t % num_trials for t in testset]) yield trainset, tes...
Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns ------- gen : generator object the generat...
def splitset(num_trials, skipstep=None): split = num_trials // 2 a = list(range(0, split)) b = list(range(split, num_trials)) yield a, b yield b, a
Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns ------- gen : generator object the gene...
def set_data(self, data, cl=None, time_offset=0): self.data_ = atleast_3d(data) self.cl_ = np.asarray(cl if cl is not None else [None]*self.data_.shape[0]) self.time_offset_ = time_offset self.var_model_ = None self.var_cov_ = None self.connectivity_ = None ...
Assign data to the workspace. This function assigns a new data set to the workspace. Doing so invalidates currently fitted VAR models, connectivity estimates, and activations. Parameters ---------- data : array-like, shape = [n_trials, n_channels, n_samples] or [n_channels, n_s...
def set_used_labels(self, labels): mask = np.zeros(self.cl_.size, dtype=bool) for l in labels: mask = np.logical_or(mask, self.cl_ == l) self.trial_mask_ = mask return self
Specify which trials to use in subsequent analysis steps. This function masks trials based on their class labels. Parameters ---------- labels : list of class labels Marks all trials that have a label that is in the `labels` list for further processing. Returns ...
def do_mvarica(self, varfit='ensemble', random_state=None): if self.data_ is None: raise RuntimeError("MVARICA requires data to be set") result = mvarica(x=self.data_[self.trial_mask_, :, :], cl=self.cl_[self.trial_mask_], var=self.var_, ...
Perform MVARICA Perform MVARICA source decomposition and VAR model fitting. Parameters ---------- varfit : string Determines how to calculate the residuals for source decomposition. 'ensemble' (default) fits one model to the whole data set, 'class' f...
def do_cspvarica(self, varfit='ensemble', random_state=None): if self.data_ is None: raise RuntimeError("CSPVARICA requires data to be set") try: sorted(self.cl_) for c in self.cl_: assert(c is not None) except (TypeError, AssertionErr...
Perform CSPVARICA Perform CSPVARICA source decomposition and VAR model fitting. Parameters ---------- varfit : string Determines how to calculate the residuals for source decomposition. 'ensemble' (default) fits one model to the whole data set, 'clas...
def do_ica(self, random_state=None): if self.data_ is None: raise RuntimeError("ICA requires data to be set") result = plainica(x=self.data_[self.trial_mask_, :, :], reducedim=self.reducedim_, backend=self.backend_, random_state=random_state) self.mixing_ = result.mixing ...
Perform ICA Perform plain ICA source decomposition. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain data.
def remove_sources(self, sources): if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") self.mixing_ = np.delete(self.mixing_, sources, 0) self.unmixing_ = np.delete(self.unmixing_, sources, 1) if self.a...
Remove sources from the decomposition. This function removes sources from the decomposition. Doing so invalidates currently fitted VAR models and connectivity estimates. Parameters ---------- sources : {slice, int, array of ints} Indices of components to remove. ...
def keep_sources(self, keep): if self.unmixing_ is None or self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") n_sources = self.mixing_.shape[0] self.remove_sources(np.setdiff1d(np.arange(n_sources), np.array(keep))) return self
Keep only the specified sources in the decomposition.
def fit_var(self): if self.activations_ is None: raise RuntimeError("VAR fitting requires source activations (run do_mvarica first)") self.var_.fit(data=self.activations_[self.trial_mask_, :, :]) self.connectivity_ = Connectivity(self.var_.coef, self.var_.rescov, self.nfft_)...
Fit a VAR model to the source activations. Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain source activations.
def optimize_var(self): if self.activations_ is None: raise RuntimeError("VAR fitting requires source activations (run do_mvarica first)") self.var_.optimize(self.activations_[self.trial_mask_, :, :]) return self
Optimize the VAR model's hyperparameters (such as regularization). Returns ------- self : Workspace The Workspace object. Raises ------ RuntimeError If the :class:`Workspace` instance does not contain source activations.
def get_connectivity(self, measure_name, plot=False): if self.connectivity_ is None: raise RuntimeError("Connectivity requires a VAR model (run do_mvarica or fit_var first)") cm = getattr(self.connectivity_, measure_name)() cm = np.abs(cm) if np.any(np.iscomplex(cm)) else ...
Calculate spectral connectivity measure. Parameters ---------- measure_name : str Name of the connectivity measure to calculate. See :class:`Connectivity` for supported measures. plot : {False, None, Figure object}, optional Whether and where to plot the connecti...
def get_surrogate_connectivity(self, measure_name, repeats=100, plot=False, random_state=None): cs = surrogate_connectivity(measure_name, self.activations_[self.trial_mask_, :, :], self.var_, self.nfft_, repeats, random_state=random_state) if plot is None or...
Calculate spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no causal structure in the data. Parameters ---------- measu...
def plot_source_topos(self, common_scale=None): if self.unmixing_ is None and self.mixing_ is None: raise RuntimeError("No sources available (run do_mvarica first)") self._prepare_plots(True, True) self.plotting.plot_sources(self.topo_, self.mixmaps_, self.unmixmaps_, comm...
Plot topography of the Source decomposition. Parameters ---------- common_scale : float, optional If set to None, each topoplot's color axis is scaled individually. Otherwise specifies the percentile (1-99) of values in all plot. This value is taken as the maximum color ...
def plot_connectivity_topos(self, fig=None): self._prepare_plots(True, False) if self.plot_outside_topo: fig = self.plotting.plot_connectivity_topos('outside', self.topo_, self.mixmaps_, fig) elif self.plot_diagonal == 'topo': fig = self.plotting.plot_connectivit...
Plot scalp projections of the sources. This function only plots the topos. Use in combination with connectivity plotting. Parameters ---------- fig : {None, Figure object}, optional Where to plot the topos. f set to **None**, a new figure is created. Otherwise plot into the...
def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None): cb = self.get_surrogate_connectivity(measure_name, repeats) self._prepare_plots(True, False) cu = np.percentile(cb, 95, axis=0) fig = self.plotting.plot_connectivity_spectrum([cu], self.fs_, freq_rang...
Plot spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no causal structure in the data. Parameters ---------- measure_na...
def parallel_loop(func, n_jobs=1, verbose=1): if n_jobs: try: from joblib import Parallel, delayed except ImportError: try: from sklearn.externals.joblib import Parallel, delayed except ImportError: n_jobs = None if not n_...
run loops in parallel, if joblib is available. Parameters ---------- func : function function to be executed in parallel n_jobs : int | None Number of jobs. If set to None, do not attempt to use joblib. verbose : int verbosity level Notes ----- Execution of the ...
def _convert_errors(func): cast_Invalid = lambda e: Invalid( u"{message}, expected {expected}".format( message=e.message, expected=e.expected) if e.expected != u'-none-' else e.message, e.path, six.text_type(e)) @wraps(func) def wrapper(*args, **...
Decorator to convert throws errors to Voluptuous format.
def on_compiled(self, name=None, key_schema=None, value_schema=None, as_mapping_key=None): if self.name is None: self.name = name if self.key_schema is None: self.key_schema = key_schema if self.value_schema is None: self.value_schema = value_schema ...
When CompiledSchema compiles this marker, it sets informational values onto it. Note that arguments may be provided in two incomplete sets, e.g. (name, key_schema, None) and then (None, None, value_schema). Thus, all assignments must be handled individually. It is possible that a marke...
def colorlogs(format="short"): try: from rainbow_logging_handler import RainbowLoggingHandler import sys # setup `RainbowLoggingHandler` logger = logging.root # same as default if format == "short": fmt = "%(message)s " else: fmt =...
Append a rainbow logging handler and a formatter to the root logger
def main(): arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments['--disable-logger']: ...
main bmi runner program
def get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ref get_def_conf(): '''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
return default configurations as simple dict
def move(self): if len(self.moves) == MAX_MOVES: return False elif len(self.moves) % 2: active_engine = self.black_engine active_engine_name = self.black inactive_engine = self.white_engine inactive_engine_name = self.white els...
Advance game by single move, if possible. @return: logical indicator if move was performed.
def setposition(self, moves=[]): self.put('position startpos moves %s' % Engine._movelisttostr(moves)) self.isready()
Move list is a list of moves (i.e. ['e2e4', 'e7e5', ...]) each entry as a string. Moves must be in full algebraic notation.
def bestmove(self): self.go() last_info = "" while True: text = self.stdout.readline().strip() split_text = text.split(' ') print(text) if split_text[0] == "info": last_info = Engine._bestmove_get_info(text) if ...
Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponder value and info dictionary.
def _bestmove_get_info(text): result_dict = Engine._get_info_pv(text) result_dict.update(Engine._get_info_score(text)) single_value_fields = ['depth', 'seldepth', 'multipv', 'nodes', 'nps', 'tbhits', 'time'] for field in single_value_fields: result_dict.update(Engin...
Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 nps 43000 tbhits 0 \ time 1 pv g7g6 h3g3 g6f7" "info depth 10 seldepth 12 multipv 1 score mate 5 nodes 2378 nps 1189000 tbhits 0 \ time 2 pv h3g3 g6f7 ...
def _get_info_singlevalue_subfield(info, field): search = re.search(pattern=field + " (?P<value>\d+)", string=info) return {field: int(search.group("value"))}
Helper function for _bestmove_get_info. Extracts (integer) values for single value fields.
def _get_info_score(info): search = re.search(pattern="score (?P<eval>\w+) (?P<value>-?\d+)", string=info) return {"score": {"eval": search.group("eval"), "value": int(search.group("value"))}}
Helper function for _bestmove_get_info. Example inputs: score cp -100 <- engine is behind 100 centipawns score mate 3 <- engine has big lead or checkmated opponent
def _get_info_pv(info): search = re.search(pattern=PV_REGEX, string=info) return {"pv": search.group("move_list")}
Helper function for _bestmove_get_info. Extracts "pv" field from bestmove's info and returns move sequence in UCI notation.
def isready(self): self.put('isready') while True: text = self.stdout.readline().strip() if text == 'readyok': return text
Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.'
def overview(index, start, end): results = { "activity_metrics": [SubmittedPRs(index, start, end), ClosedPRs(index, start, end)], "author_metrics": [], "bmi_metrics": [BMIPR(index, start, end)], "time_to_close_metrics": [DaysToClosePRMedian(index, s...
Compute metrics in the overview section for enriched github issues indexes. Returns a dictionary. Each key in the dictionary is the name of a metric, the value is the value of that metric. Value can be a complex object (eg, a time series). :param index: index object :param start: date to apply ...
def project_activity(index, start, end): results = { "metrics": [SubmittedPRs(index, start, end), ClosedPRs(index, start, end)] } return results
Compute the metrics for the project activity section of the enriched github pull requests index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to get the data from :param end: end date to get ...
def project_process(index, start, end): results = { "bmi_metrics": [BMIPR(index, start, end)], "time_to_close_metrics": [], "time_to_close_review_metrics": [DaysToClosePRAverage(index, start, end), DaysToClosePRMedian(index, start, end)], ...
Compute the metrics for the project process section of the enriched github issues index. Returns a dictionary containing "bmi_metrics", "time_to_close_metrics", "time_to_close_review_metrics" and patchsets_metrics as the keys and the related Metrics as the values. time_to_close_title and time_to_cl...
def aggregations(self): prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) agg = super().aggregations() if agg is None: agg = 0 # None is because NaN in ES. Let's convert to 0 return agg
Get the single valued aggregations with respect to the previous time interval.
def timeseries(self, dataframe=False): self.query.by_period() ts = super().timeseries(dataframe=dataframe) ts['value'] = ts['value'].apply(lambda x: float("%.2f" % x)) return ts
Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object
def timeseries(self, dataframe=False): closed_timeseries = self.closed.timeseries(dataframe=dataframe) opened_timeseries = self.opened.timeseries(dataframe=dataframe) return calculate_bmi(closed_timeseries, opened_timeseries)
Get BMIPR as a time series.
def get_section_metrics(cls): # Those metrics are only for Pull Requests # github issues is covered as ITS return { "overview": { "activity_metrics": [ClosedPR, SubmittedPR], "author_metrics": [], "bmi_metrics": [BMIPR], ...
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
def __get_metrics(self): esfilters_close = None esfilters_submit = None if self.esfilters: esfilters_close = self.esfilters.copy() esfilters_submit = self.esfilters.copy() closed = ClosedPR(self.es_url, self.es_index, start=self...
Each metric must have its own filters copy to modify it freely
def get_definition(self): def_ = { "id": self.id, "name": self.name, "desc": self.desc } return def_
Get the dict with the basic fields used to describe a metrics: id, name and desc :return: a dict with the definition
def get_query(self, evolutionary=False): if not evolutionary: interval = None offset = None else: interval = self.interval offset = self.offset if not interval: raise RuntimeError("Evolutionary query without an interva...
Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value. :return: the DSL query to be sent to Elasticsearch
def get_list(self): field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=self.FIELD_DATE, start=self.start, end=self.end, filters=self.esfilters) logger...
Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response
def get_metrics_data(self, query): if self.es_url.startswith("http"): url = self.es_url else: url = 'http://' + self.es_url es = Elasticsearch(url) s = Search(using=es, index=self.es_index) s = s.update_from_dict(query) try: re...
Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict with the results of executing the query
def get_ts(self): query = self.get_query(True) res = self.get_metrics_data(query) # Time to convert it to our grimoire timeseries format ts = {"date": [], "value": [], "unixtime": []} agg_id = ElasticQuery.AGGREGATION_ID if 'buckets' not in res['aggregations'][s...
Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific instantiated class metric per interval. This is built on a hash table. :return: a list with a time series with the values of the metric
def get_agg(self): """ Returns an aggregated value """ query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res # If we have agg data use it agg_id = str(ElasticQuery.AGGREGATION_ID) if 'aggregations...
Returns the aggregated value for the metric :return: the value of the metric
def get_trend(self): """ """ # TODO: We just need the last two periods, not the full ts ts = self.get_ts() last = ts['value'][len(ts['value']) - 1] prev = ts['value'][len(ts['value']) - 2] trend = last - prev trend_percentage = None if last == ...
Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals
def get_section_metrics(cls): return { "overview": { "activity_metrics": [Closed, Opened], "author_metrics": [], "bmi_metrics": [BMI], "time_to_close_metrics": [DaysToCloseMedian], "projects_metrics": [Projects...
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
def __get_metrics(self): esfilters_closed = None esfilters_opened = None if self.esfilters: esfilters_closed = self.esfilters.copy() esfilters_opened = self.esfilters.copy() closed = self.closed_class(self.es_url, self.es_index, ...
Each metric must have its own filters copy to modify it freely
def _load_preset(self, path): ''' load, validate and store a single preset file''' try: with open(path, 'r') as f: presetBody = json.load(f) except IOError as e: raise PresetException("IOError: " + e.strerror) except ValueError as e: r...
load, validate and store a single preset file
def validate(self, data): ''' Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control. ''' for prop in self.properties: if prop.id in data: ...
Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control.
def requestedFormat(request,acceptedFormat): if 'format' in request.args: fieldFormat = request.args.get('format') if fieldFormat not in acceptedFormat: raise ValueError("requested format not supported: "+ fieldFormat) return fieldFormat else:...
Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: chooseFormat(request, ['text/html','application/json'...
def routes_collector(gatherer): def hatFunc(rule, **options): def decorator(f): rule_dict = {'rule':rule, 'view_func':f} rule_dict.update(options) gatherer.append(rule_dict) return decorator return hatFunc
Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided by this function should be used as the ...
def add_routes(fapp, routes, prefix=""): for r in routes: r['rule'] = prefix + r['rule'] fapp.add_url_rule(**r)
Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :param prefix: url prefix under which register all...
def get_centered_pagination(current, total, visible=5): ''' Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the curre...
Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the current page :param total: total number of pages available ...
def get_section_metrics(cls): return { "overview": { "activity_metrics": [Closed, Submitted], "author_metrics": None, "bmi_metrics": [BMI], "time_to_close_metrics": [DaysToMergeMedian], "projects_metrics": [Pro...
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
def __get_metrics(self): esfilters_merge = None esfilters_abandon = None if self.esfilters: esfilters_merge = self.esfilters.copy() esfilters_abandon = self.esfilters.copy() merged = Merged(self.es_url, self.es_index, start=self.s...
Each metric must have its own filters copy to modify it freely
def __get_metrics(self): esfilters_merge = None esfilters_abandon = None esfilters_submit = None if self.esfilters: esfilters_merge = self.esfilters.copy() esfilters_abandon = self.esfilters.copy() esfilters_submit = self.esfilters.copy() ...
Each metric must have its own filters copy to modify it freely
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak class MultiplePeaks(Exception): pass class NoPeaksFound(Exception): pass half_max = np.amax(y) / 2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(ro...
Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k.
def build_arg_parser(): parser = argparse.ArgumentParser(description="Smatch calculator -- arguments") parser.add_argument('-f', nargs=2, required=True, type=argparse.FileType('r'), help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line') pa...
Build an argument parser using argparse. Use it when python version is 2.7 or later.
def build_arg_parser2(): usage_str = "Smatch calculator -- arguments" parser = optparse.OptionParser(usage=usage_str) parser.add_option("-f", "--files", nargs=2, dest="f", type="string", help='Two files containing AMR pairs. AMRs in each file are ' \ 'se...
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
def smart_init_mapping(candidate_mapping, instance1, instance2): random.seed() matched_dict = {} result = [] # list to store node indices that have no concept match no_word_match = [] for i, candidates in enumerate(candidate_mapping): if not candidates: # no possible map...
Initialize mapping based on the concept mapping (smart initialization) Arguments: candidate_mapping: candidate node match list instance1: instance triples of AMR 1 instance2: instance triples of AMR 2 Returns: initialized node mapping between two AMRs
def random_init_mapping(candidate_mapping): # if needed, a fixed seed could be passed here to generate same random (to help debugging) random.seed() matched_dict = {} result = [] for c in candidate_mapping: candidates = list(c) if not candidates: # -1 indicates no po...
Generate a random node mapping. Args: candidate_mapping: candidate_mapping: candidate node match list Returns: randomly-generated node mapping between two AMRs
def move_gain(mapping, node_id, old_id, new_id, weight_dict, match_num): # new node mapping after moving new_mapping = (node_id, new_id) # node mapping before moving old_mapping = (node_id, old_id) # new nodes mapping list (all node pairs) new_mapping_list = mapping[:] new_mapping_list[...
Compute the triple match number gain from the move operation Arguments: mapping: current node mapping node_id: remapped node in AMR 1 old_id: original node id in AMR 2 to which node_id is mapped new_id: new node in to which node_id is mapped weight_dict: weight dictionary ...
def print_alignment(mapping, instance1, instance2): result = [] for instance1_item, m in zip(instance1, mapping): r = instance1_item[1] + "(" + instance1_item[2] + ")" if m == -1: r += "-Null" else: instance2_item = instance2[m] r += "-" + instanc...
print the alignment based on a node mapping Args: mapping: current node mapping list instance1: nodes of AMR 1 instance2: nodes of AMR 2
def compute_f(match_num, test_num, gold_num): if test_num == 0 or gold_num == 0: return 0.00, 0.00, 0.00 precision = float(match_num) / float(test_num) recall = float(match_num) / float(gold_num) if (precision + recall) != 0: f_score = 2 * precision * recall / (precision + recall) ...
Compute the f-score based on the matching triple number, triple number of AMR set 1, triple number of AMR set 2 Args: match_num: matching triple number test_num: triple number of AMR 1 (test file) gold_num: triple number of ...
def generate_amr_lines(f1, f2): while True: cur_amr1 = amr.AMR.get_amr_line(f1) cur_amr2 = amr.AMR.get_amr_line(f2) if not cur_amr1 and not cur_amr2: pass elif not cur_amr1: print("Error: File 1 has less AMRs than file 2", file=ERROR_LOG) prin...
Read one AMR line at a time from each file handle :param f1: file handle (or any iterable of strings) to read AMR 1 lines from :param f2: file handle (or any iterable of strings) to read AMR 2 lines from :return: generator of cur_amr1, cur_amr2 pairs: one-line AMR strings
def main(arguments): global verbose global veryVerbose global iteration_num global single_score global pr_flag global match_triple_dict # set the iteration number # total iteration number = restart number + 1 iteration_num = arguments.r + 1 if arguments.ms: single_sc...
Main function of smatch score calculation
def normalize_attachment(attachment): ''' Convert attachment metadata from es to archivant format This function makes side effect on input attachment ''' res = dict() res['type'] = 'attachment' res['id'] = attachment['id'] del(attachment['id']) res['u...
Convert attachment metadata from es to archivant format This function makes side effect on input attachment
def denormalize_volume(volume): '''convert volume metadata from archivant to es format''' id = volume.get('id', None) res = dict() res.update(volume['metadata']) denorm_attachments = list() for a in volume['attachments']: denorm_attachments.append(Archivant.de...
convert volume metadata from archivant to es format
def denormalize_attachment(attachment): '''convert attachment metadata from archivant to es format''' res = dict() ext = ['id', 'url'] for k in ext: if k in attachment['metadata']: raise ValueError("metadata section could not contain special key '{}'".format(k...
convert attachment metadata from archivant to es format
def iter_all_volumes(self): '''iterate over all stored volumes''' for raw_volume in self._db.iterate_all(): v = self.normalize_volume(raw_volume) del v['score'] yield f iter_all_volumes(self): '''iterate over all stored volumes''' for raw_volume in sel...
iterate over all stored volumes
def delete_attachments(self, volumeID, attachmentsID): ''' delete attachments from a volume ''' log.debug("deleting attachments from volume '{}': {}".format(volumeID, attachmentsID)) rawVolume = self._req_raw_volume(volumeID) insID = [a['id'] for a in rawVolume['_source']['_attachments']...
delete attachments from a volume
def insert_attachments(self, volumeID, attachments): ''' add attachments to an already existing volume ''' log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments)) if not attachments: return rawVolume = self._req_raw_volume(volumeID) attsID...
add attachments to an already existing volume
def update_volume(self, volumeID, metadata): '''update existing volume metadata the given metadata will substitute the old one ''' log.debug('updating volume metadata: {}'.format(volumeID)) rawVolume = self._req_raw_volume(volumeID) normalized = self.normalize_volume(r...
update existing volume metadata the given metadata will substitute the old one
def dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fif dangling_files(self): '''iterate over fsdb files no more attached to any volume''' for f...
iterate over fsdb files no more attached to any volume
def shrink_local_fsdb(self, dangling=True, corrupted=True, dryrun=False): '''shrink local fsdb by removing dangling and/or corrupted files return number of deleted files ''' log.debug('shrinking local fsdb [danglings={}, corrupted={}]'.format(dangling, corrupted)) count = 0 ...
shrink local fsdb by removing dangling and/or corrupted files return number of deleted files
def _get_string(data, position, obj_end, dummy): length = _UNPACK_INT(data[position:position + 4])[0] position += 4 if length < 1 or obj_end - position < length: raise InvalidBSON("invalid string length") end = position + length - 1 if data[end:end + 1] != b"\x00": raise Invalid...
Decode a BSON string to python unicode string.
def _get_object(data, position, obj_end, opts): obj_size = _UNPACK_INT(data[position:position + 4])[0] end = position + obj_size - 1 if data[end:position + obj_size] != b"\x00": raise InvalidBSON("bad eoo") if end >= obj_end: raise InvalidBSON("invalid object length") obj = _ele...
Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.
def _get_boolean(data, position, dummy0, dummy1): end = position + 1 return data[position:end] == b"\x01", end
Decode a BSON true/false to python True/False.
def _get_date(data, position, dummy, opts): end = position + 8 millis = _UNPACK_LONG(data[position:end])[0] diff = ((millis % 1000) + 1000) % 1000 seconds = (millis - diff) / 1000 micros = diff * 1000 if opts.tz_aware: return EPOCH_AWARE + datetime.timedelta( seconds=sec...
Decode a BSON datetime to python datetime.datetime.
def _get_code_w_scope(data, position, obj_end, opts): code, position = _get_string(data, position + 4, obj_end, opts) scope, position = _get_object(data, position, obj_end, opts) return Code(code, scope), position
Decode a BSON code_w_scope to bson.code.Code.
def _get_regex(data, position, dummy0, dummy1): pattern, position = _get_c_string(data, position) bson_flags, position = _get_c_string(data, position) bson_re = Regex(pattern, bson_flags) return bson_re, position
Decode a BSON regex to bson.regex.Regex or a python pattern object.
def _elements_to_dict(data, position, obj_end, opts, subdocument=None): if type(opts.document_class) == tuple: result = opts.document_class[0](**opts.document_class[1]) if not subdocument else dict() else: result = opts.document_class() if not subdocument else dict() end = obj_end - 1 ...
Decode a BSON document.
def _bson_to_dict(data, opts): try: obj_size = _UNPACK_INT(data[:4])[0] except struct.error as exc: raise InvalidBSON(str(exc)) if obj_size != len(data): raise InvalidBSON("invalid object size") if data[obj_size - 1:obj_size] != b"\x00": raise InvalidBSON("bad eoo") ...
Decode a BSON string to document_class.
def _encode_mapping(name, value, check_keys, opts): data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
Encode a mapping type.
def _encode_datetime(name, value, dummy0, dummy1): if value.utcoffset() is not None: value = value - value.utcoffset() millis = int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000) return b"\x09" + name + _PACK_LONG(millis)
Encode datetime.datetime.
def _encode_code(name, value, dummy, opts): cstring = _make_c_string(value) cstrlen = len(cstring) if not value.scope: return b"\x0D" + name + _PACK_INT(cstrlen) + cstring scope = _dict_to_bson(value.scope, False, opts, False) full_length = _PACK_INT(8 + cstrlen + len(scope)) return...
Encode bson.code.Code.
def simToReg(self, sim): # remove initial slash if present res = re.sub('^/', '', sim) res = re.sub('/$', '', res) return '^/?' + re.sub('\*', '[^/]+', res) + '/?$'
Convert simplified domain expression to regular expression
def match(self, dom, act): return self.match_domain(dom) and self.match_action(act)
Check if the given `domain` and `act` are allowed by this capability
def to_list(self): '''convert an actions bitmask into a list of action strings''' res = [] for a in self.__class__.ACTIONS: aBit = self.__class__.action_bitmask(a) if ((self & aBit) == aBit): res.append(a) return ref to_list(self): '''conve...
convert an actions bitmask into a list of action strings
def from_list(cls, actions): '''convert list of actions into the corresponding bitmask''' bitmask = 0 for a in actions: bitmask |= cls.action_bitmask(a) return Action(bitmaskf from_list(cls, actions): '''convert list of actions into the corresponding bitmask''' ...
convert list of actions into the corresponding bitmask
def get_section_metrics(cls): return { "overview": { "activity_metrics": [Commits], "author_metrics": [Authors], "bmi_metrics": [], "time_to_close_metrics": [], "projects_metrics": [Projects] }, ...
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report