code stringlengths 1 18.2k |
|---|
def _get_indexes_by_path(self, field): """ Returns a list of indexes by field path. :param field: Field structure as following: *.subfield_2 would apply the function to the every subfield_2 of the elements 1.subfield_2 would apply the function to the subfield_2 of the element 1 * would apply the function to every eleme... |
def example(index): """Index page.""" pid = PersistentIdentifier.query.filter_by(id=index).one() record = RecordMetadata.query.filter_by(id=pid.object_uuid).first() return render_template("app/detail.html", record=record.json, pid=pid, title="Demosite Invenio Org") |
def rebin(a, factor, func=None): u"""Aggregate data from the input array ``a`` into rectangular tiles. The output array results from tiling ``a`` and applying `func` to each tile. ``factor`` specifies the size of the tiles. More precisely, the returned array ``out`` is such that:: out[i0, i1, ...] = func(a[f0*i0:f0*(i0... |
array is reduced to a (2, 2) array >>> import numpy >>> from rebin import rebin >>> a = numpy.arange(24).reshape(4, 6) >>> rebin(a, factor=(2, 3), func=numpy.sum) array([[ 24, 42], [ 96, 114]]) If the elements of `factor` are not integer multiples of the dimensions of `a`, the remainding cells are discarded. >>> rebin(... |
= [s*f for s, f in zip(a.strides, factor)]+list(a.strides) aa = as_strided(a, shape=new_shape, strides=new_strides) return func(aa, axis=tuple(range(-dim, 0))) |
def can_use_enum(func): """ Decorator to use Enum value on type checks. """ @wraps(func) def inner(self, value): if isinstance(value, Enum): return self.check_value(value.value) or func(self, value.value) return func(self, value) return inner |
def convert_enum(func): """ Decorator to use Enum value on type casts. """ @wraps(func) def inner(self, value): try: if self.check_value(value.value): return value.value return func(self, value.value) except AttributeError: pass return func(self, value) return inner |
def use_value(self, value): """Converts value to field type or use original""" if self.check_value(value): return value return self.convert_value(value) |
def set_value(self, obj, value): """Sets value to model if not empty""" if value: obj.set_field_value(self.name, value) else: self.delete_value(obj) |
def get_parsed_value(self, value): """ Helper to cast string to datetime using :member:`parse_format`. :param value: String representing a datetime :type value: str :return: datetime """ def get_parser(parser_desc): try: return parser_desc['parser'] except TypeError: try: return get_parser(self.date_parsers[parser_desc... |
def get_formatted_value(self, value): """ Returns a string from datetime using :member:`parse_format`. :param value: Datetime to cast to string :type value: datetime :return: str """ def get_formatter(parser_desc): try: return parser_desc['formatter'] except TypeError: if isinstance(parser_desc, str): try: return get_f... |
def action(self): """ Invoke functions according to the supplied flags """ user = self.args['--user'] if self.args['--user'] else None reset = True if self.args['--reset'] else False if self.args['generate']: generate_network(user, reset) elif self.args['publish']: publish_network(user, reset) |
def renderer(format, mimetypes=(), priority=0, name=None, test=None): """ Decorates a view method to say that it renders a particular format and mimetypes. Use as: @renderer(format="foo") def render_foo(self, request, context, template_name): ... or @renderer(format="foo", mimetypes=("application/x-foo",)) def render_f... |
async def wait_change(self): """ Wait for the list to change. """ future = asyncio.Future(loop=self.loop) self._change_futures.add(future) future.add_done_callback(self._change_futures.discard) await future |
def shift(self, count=1): """ Shift the view a specified number of times. :param count: The count of times to shift the view. """ if self: self._index = (self._index + count) % len(self) else: self._index = 0 |
def render(value): """ This function finishes the url pattern creation by adding starting character ^ end possibly by adding end character at the end :param value: naive URL value :return: raw string """ # Empty urls if not value: # use case: wild card imports return r'^$' if value[0] != beginning: value = beginning + ... |
def add_part(self, part): """ Function for adding partial pattern to the value :param part: string or compiled pattern """ if isinstance(part, RE_TYPE): part = part.pattern # Allow U / spmething syntax if self == '^$': return URLPattern(part, self.separator) else: # Erase dup separator inbetween sep = self.separator re... |
def get_conjunctive_graph(store_id=None): """ Returns an open conjunctive graph. """ if not store_id: store_id = DEFAULT_STORE store = DjangoStore(DEFAULT_STORE) graph = ConjunctiveGraph(store=store, identifier=store_id) if graph.open(None) != VALID_STORE: raise ValueError("The store identified by {0} is not a valid st... |
def get_named_graph(identifier, store_id=DEFAULT_STORE, create=True): """ Returns an open named graph. """ if not isinstance(identifier, URIRef): identifier = URIRef(identifier) store = DjangoStore(store_id) graph = Graph(store, identifier=identifier) if graph.open(None, create=create) != VALID_STORE: raise ValueError(... |
def read_readme(): """ Reads part of the README.rst for use as long_description in setup(). """ text = open("README.rst", "rt").read() text_lines = text.split("\n") ld_i_beg = 0 while text_lines[ld_i_beg].find("start long description") < 0: ld_i_beg += 1 ld_i_beg += 1 ld_i_end = ld_i_beg while text_lines[ld_i_end].find... |
def work(self): """ A list of :class:`Employment` instances describing the user's work history. Each structure has attributes ``employer``, ``position``, ``started_at`` and ``ended_at``. ``employer`` and ``position`` reference ``Page`` instances, while ``started_at`` and ``ended_at`` are datetime objects. """ employmen... |
def languages(self): """ A list of strings describing the user's languages. """ languages = [] for language in self.cache['languages']: language = Structure( id = language['id'], name = language['name'] ) languages.append(language) return languages |
def interested_in(self): """ A list of strings describing the genders the user is interested in. """ genders = [] for gender in self.cache['interested_in']: genders.append(gender) return genders |
def education(self): """ A list of structures describing the user's education history. Each structure has attributes ``school``, ``year``, ``concentration`` and ``type``. ``school``, ``year`` reference ``Page`` instances, while ``concentration`` is a list of ``Page`` instances. ``type`` is just a string that describes ... |
def permissions(self): """ A list of strings describing permissions. See Facebook's exhaustive `Permissions Reference <http://developers.facebook.com/docs/authentication/permissions/>`_ for a list of available permissions. """ response = self.graph.get('%s/permissions' % self.id) permissions = [] for permission, state ... |
def accounts(self): """ A list of structures describing apps and pages owned by this user. """ response = self.graph.get('%s/accounts' % self.id) accounts = [] for item in response['data']: account = Structure( page = Page( id = item['id'], name = item['name'], category = item['category'] ), access_token = item['access... |
def update_xml_element(self): """ Updates the XML element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) self.xml_element.clear() if hasattr(self, 'resolved'): self.xm... |
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ result_dict = super(Benchmark, self).as_dict() statuses = list() titles = list() descriptions = list() front_matters = list() rear_matters = list() platforms = list() version = None p... |
front_matters if len(rear_matters) > 0: result_dict['rear_matters'] = rear_matters if len(platforms) > 0: result_dict['platforms'] = platforms if len(profiles) > 0: result_dict['profiles'] = profiles if len(groups) > 0: result_dict['groups'] = groups return result_dict |
def post_message(plugin, polled_time, identity, message): """Post single message :type plugin: errbot.BotPlugin :type polled_time: datetime.datetime :type identity: str :type message: str """ user = plugin.build_identifier(identity) return plugin.send(user, message) |
async def start_pipe_server( client_connected_cb, *, path, loop=None, limit=DEFAULT_LIMIT ): """ Start listening for connection using Windows named pipes. """ path = path.replace('/', '\\') loop = loop or asyncio.get_event_loop() def factory(): reader = asyncio.StreamReader(limit=limit, loop=loop) protocol = asyncio.St... |
async def open_pipe_connection( path=None, *, loop=None, limit=DEFAULT_LIMIT, **kwargs ): """ Connect to a server using a Windows named pipe. """ path = path.replace('/', '\\') loop = loop or asyncio.get_event_loop() reader = asyncio.StreamReader(limit=limit, loop=loop) protocol = asyncio.StreamReaderProtocol(reader, l... |
def set_read_only(self, value): """ Sets whether model could be modified or not """ if self.__read_only__ != value: self.__read_only__ = value self._update_read_only() |
def is_locked(self): """ Returns whether model is locked """ if not self.__locked__: return False elif self.get_parent(): return self.get_parent().is_locked() return True |
def generate_gml(username, nodes, edges, cache=False): """ Generate a GML format file representing the given graph attributes """ # file segment that represents all the nodes in graph node_content = "" for i in range(len(nodes)): node_id = "\t\tid %d\n" % (i + 1) node_label = "\t\tlabel \"%s\"\n" % (nodes[i]) node_cont... |
def config_extensions(app): " Init application with extensions. " cache.init_app(app) db.init_app(app) main.init_app(app) collect.init_app(app) config_babel(app) |
def config_babel(app): " Init application with babel. " babel.init_app(app) def get_locale(): return request.accept_languages.best_match(app.config['BABEL_LANGUAGES']) babel.localeselector(get_locale) |
def activate_crontab(self): """Activate polling function and register first crontab """ self._crontab = [] if hasattr(self, 'CRONTAB'): for crontab_spec in self.CRONTAB: args = cronjob.parse_crontab(crontab_spec) job = cronjob.CronJob() if args['_timer'] == 'datetime': job.set_triggers(args['trigger_format'], args['tri... |
def poll_crontab(self): """Check crontab and run target jobs """ polled_time = self._get_current_time() if polled_time.second >= 30: self.log.debug('Skip cronjobs in {}'.format(polled_time)) return for job in self._crontab: if not job.is_runnable(polled_time): continue job.do_action(self, polled_time) |
def include(self, location, namespace=None, app_name=None): """ Return an object suitable for url_patterns. :param location: root URL for all URLs from this router :param namespace: passed to url() :param app_name: passed to url() """ sorted_entries = sorted(self.routes, key=operator.itemgetter(0), reverse=True) arg = ... |
def clone_source(self): " Clone source and prepare templates " print_header('Clone src: %s' % self.src, '-') # Get source source_dir = self._get_source() # Append settings from source self.read(op.join(source_dir, settings.CFGNAME)) self.templates += (self.args.template or self.template).split(',') self.templates = Ord... |
def _get_source(self): " Get source from CVS or filepath. " source_dir = op.join(self.deploy_dir, 'source') for tp, cmd in settings.SRC_CLONE: if self.src.startswith(tp + '+'): program = which(tp) assert program, '%s not found.' % tp cmd = cmd % dict(src=self.src[len(tp) + 1:], source_dir=source_dir, branch=self.branch... |
def quote(text, ws=plain): """Quote special characters in shell command arguments. E.g ``--foo bar>=10.1`` becomes "--foo bar\>\=10\.1``. """ return "".join(chr in ws and chr or '\\' + chr for chr in text) |
def render_to_response(self, context): "Return HttpResponse." return http.HttpResponse( self.render_template(context), content_type=self.mimetype) |
def prepare_plot_data(data_file): """ Return a list of Plotly elements representing the network graph """ G = ig.Graph.Read_GML(data_file) layout = G.layout('graphopt') labels = list(G.vs['label']) N = len(labels) E = [e.tuple for e in G.es] community = G.community_multilevel().membership communities = len(set(communit... |
name='ntw', marker=Marker(symbol='dot', size=5, color=color_list[i], line=Line( color='rgb(50,50,50)', width=0.5) ), text=node_labels[i], hoverinfo='text' ) plot_data.append(trace) return plot_data |
def publish_network(user=None, reset=False): """ Generate graph network for a user and plot it using Plotly """ username = generate_network(user, reset) network_file = username_to_file(username) plot_data = prepare_plot_data(network_file) data = Data(plot_data) # hide axis line, grid, ticklabels and title axis = dict(s... |
'Published the network graph at {0}'.format(plot_url) except Exception, e: raise e |
def pad_with_object(sequence, new_length, obj=None): """ Returns :samp:`sequence` :obj:`list` end-padded with :samp:`{obj}` elements so that the length of the returned list equals :samp:`{new_length}`. :type sequence: iterable :param sequence: Return *listified* sequence which has been end-padded. :type new_length: :ob... |
def shape_factors(n, dim=2): """ Returns a :obj:`numpy.ndarray` of factors :samp:`f` such that :samp:`(len(f) == {dim}) and (numpy.product(f) == {n})`. The returned factors are as *square* (*cubic*, etc) as possible. For example:: >>> shape_factors(24, 1) array([24]) >>> shape_factors(24, 2) array([4, 6]) >>> shape_fac... |
% f) == 0: factors = [f, ] + list(shape_factors(n // f, dim=dim - 1)) break factors.sort() return _np.array(factors) |
def calculate_tile_shape_for_max_bytes( array_shape, array_itemsize, max_tile_bytes, max_tile_shape=None, sub_tile_shape=None, halo=None ): """ Returns a tile shape :samp:`tile_shape` such that :samp:`numpy.product(tile_shape)*numpy.sum({array_itemsize}) <= {max_tile_bytes}`. Also, if :samp:`{max_tile_shape} is not Non... |
shape. :type halo: :obj:`int`, sequence of :obj:`int`, or :samp:`(len({array_shape}), 2)` shaped :obj:`numpy.ndarray` :param halo: How tiles are extended in each axis direction with *halo* elements. See :ref:`the-halo-parameter-examples` for meaning of :samp:`{halo}` values. :rtype: :obj:`numpy.ndarray` :return: A 1D a... |
logger.debug("halo=%s", halo) array_shape = _np.array(array_shape, dtype="int64") array_itemsize = _np.sum(array_itemsize, dtype="int64") if max_tile_shape is None: max_tile_shape = _np.array(array_shape, copy=True) max_tile_shape = \ _np.array(_np.minimum(max_tile_shape, array_shape), copy=True, dtype=array_shape.dtyp... |
axis=1)) * array_itemsize ) > max_tile_bytes ) ): if current_axis < (len(tile_sub_tile_split_shape) - 1): tile_sub_tile_split_shape[current_axis] = 1 tile_sub_tile_split_shape[current_axis] = \ ( max_tile_bytes // ( _np.product( tile_sub_tile_split_shape * sub_tile_shape + _np.sum( halo, axis=1)) * array_itemsize ) ) t... |
def calculate_num_slices_per_axis(num_slices_per_axis, num_slices, max_slices_per_axis=None): """ Returns a :obj:`numpy.ndarray` (:samp:`return_array` say) where non-positive elements of the :samp:`{num_slices_per_axis}` sequence have been replaced with positive integer values such that :samp:`numpy.product(return_arra... |
:return: An array :samp:`return_array` such that :samp:`numpy.product(return_array) == num_slices`. Examples:: >>> from array_split.split import calculate_num_slices_per_axis >>> >>> calculate_num_slices_per_axis([0, 0, 0], 16) array([4, 2, 2]) >>> calculate_num_slices_per_axis([1, 0, 0], 16) array([1, 4, 4]) >>> calcu... |
f = shape_factors(num_slices // prd, ridx[0].shape[0])[::-1] if _np.all(f < max_slices_per_axis[ridx]): ret_array[ridx] = f else: for i in range(ridx[0].shape[0]): if f[i] >= max_slices_per_axis[ridx[0][i]]: ret_array[ridx[0][i]] = max_slices_per_axis[ridx[0][i]] prd = _np.product(ret_array[_np.where(ret_array > 0)]) w... |
def convert_halo_to_array_form(halo, ndim): """ Converts the :samp:`{halo}` argument to a :samp:`(ndim, 2)` shaped array. :type halo: :samp:`None`, :obj:`int`, an :samp:`{ndim}` length sequence of :samp:`int` or :samp:`({ndim}, 2)` shaped array of :samp:`int` :param halo: Halo to be converted to :samp:`({ndim}, 2)` sha... |
(2,)): halo = _np.array([halo, ], copy=True, dtype=dtyp) elif len(_np.array(halo).shape) == 1: halo = _np.array([halo, halo], dtype=dtyp).T.copy() else: halo = _np.array(halo, copy=True, dtype=dtyp) if halo.shape[0] != ndim: raise ValueError( "Got halo.shape=%s, expecting halo.shape=(%s, 2)" % (halo.shape, ndim) ) retu... |
def array_split( ary, indices_or_sections=None, axis=None, tile_shape=None, max_tile_bytes=None, max_tile_shape=None, sub_tile_shape=None, halo=None ): "To be replaced." return [ ary[slyce] for slyce in shape_split( array_shape=ary.shape, indices_or_sections=indices_or_sections, axis=axis, array_start=None, array_items... |
def convert_halo_to_array_form(self, halo): """ Converts the :samp:`{halo}` argument to a :samp:`({self}.array_shape.size, 2)` shaped array. :type halo: :samp:`None`, :obj:`int`, :samp:`self.array_shape.size` length sequence of :samp:`int` or :samp:`(self.array_shape.size, 2)` shaped array of :samp:`int` :param halo: H... |
def check_tile_bounds_policy(self): """ Raises :obj:`ValueError` if :attr:`tile_bounds_policy` is not in :samp:`[{self}.ARRAY_BOUNDS, {self}.NO_BOUNDS]`. """ if self.tile_bounds_policy not in self.valid_tile_bounds_policies: raise ValueError( "Got self.tile_bounds_policy=%s, which is not in %s." % (self.tile_bounds_pol... |
def check_consistent_parameter_dimensions(self): """ Ensure that all parameter dimensions are consistent with the :attr:`array_shape` dimension. :raises ValueError: For inconsistent parameter dimensions. """ if self.indices_per_axis is not None: if len(self.indices_per_axis) > len(self.array_shape): raise ValueError( "... |
should be equal." % (len(self.max_tile_shape), len(self.array_shape)) ) if self.array_start is not None: if len(self.array_start) != len(self.array_shape): raise ValueError( "Got len(self.array_start)=%s > len(self.array_shape)=%s, should be equal." % (len(self.array_start), len(self.array_shape)) ) |
def check_consistent_parameter_grouping(self): """ Ensures this object does not have conflicting groups of parameters. :raises ValueError: For conflicting or absent parameters. """ parameter_groups = {} if self.indices_per_axis is not None: parameter_groups["indices_per_axis"] = \ {"self.indices_per_axis": self.indices... |
to define the split:\n" + ( "\n".join( [ ( ("Group %18s: " % ("'%s'" % group_key)) + str(parameter_groups[group_key]) ) for group_key in group_keys ] ) ) ) if len(parameter_groups.keys()) <= 0: raise ValueError( "No split parameters specified, need parameters from one of the groups: " + "'indices_per_axis', 'split_size... |
def update_tile_extent_bounds(self): """ Updates the :attr:`tile_beg_min` and :attr:`tile_end_max` data members according to :attr:`tile_bounds_policy`. """ if self.tile_bounds_policy == NO_BOUNDS: self.tile_beg_min = self.array_start - self.halo[:, 0] self.tile_end_max = self.array_start + self.array_shape + self.halo... |
def set_split_extents_by_indices_per_axis(self): """ Sets split shape :attr:`split_shape` and split extents (:attr:`split_begs` and :attr:`split_ends`) from values in :attr:`indices_per_axis`. """ if self.indices_per_axis is None: raise ValueError("Got None for self.indices_per_axis") self.logger.debug("self.array_shap... |
def calculate_split_from_extents(self): """ Returns split calculated using extents obtained from :attr:`split_begs` and :attr:`split_ends`. All calls to calculate the split end up here to produce the :mod:`numpy` `structured array <http://docs.scipy.org/doc/numpy/user/basics.rec.html>`_ of :obj:`tuple`-of-:obj:`slice` ... |
def calculate_axis_split_extents(self, num_sections, size): """ Divides :samp:`range(0, {size})` into (approximately) equal sized intervals. Returns :samp:`(begs, ends)` where :samp:`slice(begs[i], ends[i])` define the intervals for :samp:`i in range(0, {num_sections})`. :type num_sections: :obj:`int` :param num_sectio... |
begs.copy() ends[0:-1] = begs[1:] return begs, ends |
def set_split_extents_by_split_size(self): """ Sets split shape :attr:`split_shape` and split extents (:attr:`split_begs` and :attr:`split_ends`) from values in :attr:`split_size` and :attr:`split_num_slices_per_axis`. """ if self.split_size is None: if ( _np.all([s is not None for s in self.split_num_slices_per_axis])... |
) |
def set_split_extents_by_tile_shape(self): """ Sets split shape :attr:`split_shape` and split extents (:attr:`split_begs` and :attr:`split_ends`) from value of :attr:`tile_shape`. """ self.split_shape = ((self.array_shape - 1) // self.tile_shape) + 1 self.split_begs = [[], ] * len(self.array_shape) self.split_ends = [[... |
def set_split_extents_by_tile_max_bytes(self): """ Sets split extents (:attr:`split_begs` and :attr:`split_ends`) calculated using from :attr:`max_tile_bytes` (and :attr:`max_tile_shape`, :attr:`sub_tile_shape`, :attr:`halo`). """ self.tile_shape = \ calculate_tile_shape_for_max_bytes( array_shape=self.array_shape, arr... |
def set_split_extents(self): """ Sets split extents (:attr:`split_begs` and :attr:`split_ends`) calculated using selected attributes set from :meth:`__init__`. """ self.check_split_parameters() self.update_tile_extent_bounds() if self.indices_per_axis is not None: self.set_split_extents_by_indices_per_axis() elif (self... |
def load_children(self): """ Load the subelements from the xml_element in its correspondent classes. :returns: List of child objects. :rtype: list :raises CardinalityException: If there is more than one Version child. :raises CardinalityException: If there is no Version child. :raises CardinalityException: If there is ... |
required at least once' raise CardinalityException(error_msg) # List construction children.extend(statuses) if version is not None: children.append(version) children.extend(profiles) return children |
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) self.xml_element.clear() self.xml_element.set('id', self.id) fo... |
def make_predictor(regressor=LassoLarsIC(fit_intercept=False), Selector=GridSearchCV, fourier_degree=(2, 25), selector_processes=1, use_baart=False, scoring='r2', scoring_cv=3, **kwargs): """make_predictor(regressor=LassoLarsIC(fit_intercept=False), Selector=GridSearchCV, fourier_degree=(2, 25), selector_processes=1, u... |
use for *Selector*. This parameter can be: * "r2", in which case use :math:`R^2` (the default) * "mse", in which case use mean square error scoring_cv : positive integer, optional Number of cross validation folds used in scoring (default 3). **Returns** out : object with "fit" and "predict" methods The created predicto... |
def get_lightcurve(data, copy=False, name=None, predictor=None, periodogram=Lomb_Scargle, sigma_clipping=mad, scoring='r2', scoring_cv=3, scoring_processes=1, period=None, min_period=0.2, max_period=32, coarse_precision=1e-5, fine_precision=1e-9, period_processes=1, sigma=20, shift=None, min_phase_cover=0.0, min_observ... |
finds one or more *period*\s. If *period* is already provided, the function is not used. Defaults to :func:`plotypus.periodogram.Lomb_Scargle` sigma_clipping : function, optional Function which takes an array and assigns sigma scores to each element. Defaults to :func:`plotypus.utils.mad`. scoring : str, optional Scori... |
*periodogram* function (the default). * A single positive number, giving the period to phase *data*. min_period : non-negative number, optional Lower bound on period obtained by *periodogram* (default 0.2). max_period : non-negative number, optional Upper bound on period obtained by *periodogram* (default 32.0). course... |
occurs at ``phase[0]`` if None given (default None). min_phase_cover : number on interval [0, 1], optional Fraction of binned light curve that must contain points in order to proceed. If light curve has insufficient coverage, a warning is printed if "outlier" *verbosity* is on, and None is returned (default 0.0). n_pha... |
= [n_coeffs] Fitted light curve coefficients. * dA_0 : non-negative number Error on mean magnitude. * phased_data : array-like, shape = [n_samples] *data* transformed from temporal to phase space. * model : predictor object The predictor used to fit the light curve. * R2 : number The :math:`R^2` score of the fit. * MSE... |
signal = get_signal(data) if len(signal) <= scoring_cv: verbose_print( "{}: length of signal ({}) less than cv folds ({})".format( name, len(signal), scoring_cv), operation="coverage", verbosity=verbosity) return elif len(signal) < min_observations: verbose_print( "{}: length of signal ({}) " "less than min_observation... |
= sum(coverage)/100 if coverage < min_phase_cover: verbose_print("{}: {} {}".format(name, coverage, min_phase_cover), operation="coverage", verbosity=verbosity) verbose_print("Insufficient phase coverage", operation="outlier", verbosity=verbosity) return # Predict light curve with warnings.catch_warnings(record=True) a... |
arg_max_light/len(phases) data.T[0] = rephase(data.data, _period, shift).T[0] # Grab the coefficients from the model coefficients = predictor.named_steps['Regressor'].coef_ \ if isinstance(predictor, Pipeline) \ else predictor.best_estimator_.named_steps['Regressor'].coef_, # compute R^2 and MSE if they haven't already... |
def get_lightcurve_from_file(file, *args, use_cols=None, skiprows=0, verbosity=None, **kwargs): """get_lightcurve_from_file(file, *args, use_cols=None, skiprows=0, **kwargs) Fits a light curve to the data contained in *file* using :func:`get_lightcurve`. **Parameters** file : str or file File or filename to load data f... |
def find_outliers(data, predictor, sigma, method=mad): """find_outliers(data, predictor, sigma, method=mad) Returns a boolean array indicating the outliers in the given *data* array. **Parameters** data : array-like, shape = [n_samples, 2] or [n_samples, 3] Photometry array containing columns *phase*, *magnitude*, and ... |
def plot_lightcurve(name, lightcurve, period, data, output='.', legend=False, sanitize_latex=False, color=True, n_phases=100, err_const=0.005, **kwargs): """plot_lightcurve(name, lightcurve, period, data, output='.', legend=False, color=True, n_phases=100, err_const=0.005, **kwargs) Save a plot of the given *lightcurve... |
Number of phase points in fit (default 100). err_const : number, optional Constant to use in absence of error (default 0.005). **Returns** None """ phases = numpy.linspace(0, 1, n_phases, endpoint=False) ax = plt.gca() ax.invert_yaxis() plt.xlim(0,2) # Plot points used phase, mag, *err = get_signal(data).T error = err[... |
plt.xlabel('Phase ({0:0.7} day period)'.format(period)) plt.ylabel('Magnitude') plt.title(utils.sanitize_latex(name) if sanitize_latex else name) plt.tight_layout(pad=0.1) make_sure_path_exists(output) plt.savefig(path.join(output, name)) plt.clf() |
def register_app(app): " Configure application. " from .views import urls app.register_blueprint(urls) from .ext import admin admin.init_app(app) from flask_bootstrap import Bootstrap bootstrap = Bootstrap() bootstrap.init_app(app) from flask import render_template app.errorhandler(404)(lambda e: (render_template('core... |
def socket(self, socket_type, identity=None, mechanism=None): """ Create and register a new socket. :param socket_type: The type of the socket. :param loop: An optional event loop to associate the socket with. This is the preferred method to create new sockets. """ socket = Socket( context=self, socket_type=socket_type... |
def set_zap_authenticator(self, zap_authenticator): """ Setup a ZAP authenticator. :param zap_authenticator: A ZAP authenticator instance to use. The context takes ownership of the specified instance. It will close it automatically when it stops. If `None` is specified, any previously owner instance is disowned and ret... |
def transform_record(self, pid, record, links_factory=None): """Transform record into an intermediate representation. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :param links_factory: The link factory. (Default: ``None`... |
def transform_search_hit(self, pid, record_hit, links_factory=None): """Transform search result hit into an intermediate representation. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record_hit: A dictionary containing a ``'_source'`` key with the record data. :param links_facto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.