code stringlengths 1 18.2k |
|---|
histogram, it is highly recommended that you use `numpy.clip` to ensure that any of the values in the spectrogram that are greater than your largest bin are not thrown away! For example, if you decide on a fixed range between 0 and 500, and your spectrogram contains a value of 777, the following code would produce a hi... |
= ibmseti.features.entropy(p,w) You can also choose to fix the number of bins bins = 50 p, bin_edges = np.histogram(spectrogram.flatten(), bins=bins, density=True) w = np.diff(bin_edges) h_p, h_max = ibmseti.features.entropy(p,w) It is suggested to use any of the following measures as features: bin range, spectrogram.m... |
or with the variable sized arrays as can be calculated with Bayesian Blocks with astroML. However, nothing is ruled out. In preliminary testing, the calculated entropy from a histogram calculated with Bayesian Block binning seemed to be more sensitive to a simulated signal than using fixed binning. However, it's unclea... |
produce more bins. More testing is required and your mileage may vary. import astroML.plotting bin_edges = astroML.density_estimation.bayesian_blocks(spectrogram.flatten()) p, _ = np.histogram(spectrogram.flatten(), bins=bin_edges, density=True) w = np.diff(bin_edges) h_p, h_max = ibmseti.features.entropy(p,w) Also to ... |
def refine_get_urls(original): """ serve static files (and media files also) in production the webserver should serve requested static files itself and never let requests to /static/* and /media/* get to the django application. """ def get_urls(): from django.conf.urls import url from django.conf import settings from d... |
def download(url): """Uses requests to download an URL, maybe from a file""" session = requests.Session() session.mount('file://', FileAdapter()) try: res = session.get(url) except requests.exceptions.ConnectionError as e: raise e res.raise_for_status() return res |
def get_uri_name(url): """Gets the file name from the end of the URL. Only useful for PyBEL's testing though since it looks specifically if the file is from the weird owncloud resources distributed by Fraunhofer""" url_parsed = urlparse(url) url_parts = url_parsed.path.split('/') log.info('url parts: %s', url_parts) re... |
def numbafy(fn, args, compiler="jit", **nbkws): """ Compile a string, sympy expression or symengine expression using numba. Not all functions are supported by Python's numerical package (numpy). For difficult cases, valid Python code (as string) may be more suitable than symbolic expressions coming from sympy, symengin... |
compiler_ = getattr(nb, compiler, None) if compiler is None: raise AttributeError("No numba function with name {}.".format(compiler)) compiler = compiler_ if compiler in (nb.jit, nb.njit, nb.autojit): kwargs.update(jitkwargs) sig = nbkws.pop("signature", None) else: kwargs.update(veckwargs) sig = nbkws.pop("signatures"... |
def summary(raster, geometry=None, all_touched=False, mean_only=False, bounds=None, exclude_nodata_value=True): """Return ``ST_SummaryStats`` style stats for the given raster. If ``geometry`` is provided, we mask the raster with the given geometry and return the stats for the intersection. The parameter can be a GeoJSO... |
to the raster no data value. If ``mean_only`` is ``False``, we return a ``namedtuple`` representing the stats. All other attributes should be obvious and are consistent with PostGIS (``min``, ``max``, ``std``, etc). If ``mean_only`` is ``True``, we simply return a ``float`` or ``None`` representing the mean value of th... |
isinstance(geometry, dict): geojson = mapping(geometry) else: geojson = geometry geometry = shape(geometry) result, _ = mask( raster, [geojson], crop=True, all_touched=all_touched, ) pixels = result.data.flatten() else: pixels = raster.read(1).flatten() except ValueError: return no_result(mean_only) raster_shape = rast... |
def parse_template(template_path, **kwargs): """ Load and render template. First line of template should contain the subject of email. Return tuple with subject and content. """ template = get_template(template_path) context = Context(kwargs) data = template.render(context).strip() subject, content = re.split(r'\r?\n',... |
def email_template(rcpt, template_path, **kwargs): """ Load, render and email template. **kwargs may contain variables for template rendering. """ subject, content = parse_template(template_path, **kwargs) count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, [rcpt], fail_silently=True) return bool(count) |
def get_instance_from_path(path, *args, **kwargs): """ Return an instance of a class, given the dotted Python import path (as a string) to the backend class. If the backend cannot be located (e.g., because no such module exists, or because the module does not contain a class of the appropriate name), ``django.core.exce... |
def substitute(search, replace, text): 'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``' return re.sub(re.compile(str(search)), replace, text) |
def search(pattern, text): 'Regex pattern search. Returns match if ``pattern`` is found in ``text``' return re.compile(str(pattern)).search(str(text)) |
def get(cls, route, args, kwargs): """ :cls (class) <Class> of the object requested :route (dict) Debris route schema :args (list) of argument provided for initializing :kwargs (dict) of given data to construct the object """ # --------- # Namespace # --------- if None in args: namespace = None else: namespace = call(r... |
information # - replaces existing object in memory beceause this data is # given to be "newer" data if len(kwargs) > 0: cls = call(route.get('substitute'), args, kwargs) or cls obj = cls.__new__(cls, *args, **kwargs) obj.__init__(*args, **kwargs) if namespace: debris.services.memory.set(namespace, obj) return obj elif ... |
', ')+")") if not data: data = {} # -------------------- # Manage Args / Kwargs # -------------------- # remove the default "self" argument insp.args.pop(0) [data.pop(k) for k in insp.args if k in data] # substiture class w/ known data if route.get('substitute'): cls = callattr(cls, route['substitute'], args, data) or ... |
def getmany(cls, route, args, kwargs, _keys): """ 1. build name space 2. look locally for copies 3. build group for batch 4. fetch the new ones 5. return found + new list """ # copy the list of keys keys = [] + _keys # build a list of returning objects returning = [] # dictionary of references namespaces = {} # key: ns... |
add to namespace list namespaces[str(key)] = namespace namespace_keys[namespace] = str(key) if not namespaces: # all data found, return the findings return returning # ----------------- # Retrieve the Data # ----------------- insp = inspect.getargspec(cls.__init__) insp.args.pop(0) # self data = None for r in route['ge... |
Results Found # ------------- if results: # [(ns, data), ...] for namespace, data in results: if data: # substiture class w/ known data # ------------------------------ if route.get('substitute'): _cls = callattr(cls, route.get('substitute'), args, data) or cls else: _cls = cls # initialize class # ---------------- obj... |
def _load_data(self, data, from_db=False): """ Stores the data at self._data, actual object creation done at _generate_instances() Args: data (list): List of dicts. from_db (bool): Default False. Is this data coming from DB or not. """ self._data = data[:] self.setattrs( values=[], node_stack=[], node_dict={}, ) self._... |
def _generate_instances(self): """ ListNode item generator. Will be used internally by __iter__ and __getitem__ Yields: ListNode items (instances) """ for node in self.node_stack: yield node while self._data: yield self._make_instance(self._data.pop(0)) |
def _make_instance(self, node_data): """ Create a ListNode instance from node_data Args: node_data (dict): Data to create ListNode item. Returns: ListNode item. """ node_data['from_db'] = self._from_db clone = self.__call__(**node_data) clone.setattrs(container = self, _is_item = True) for name in self._nodes: _name = ... |
def clean_value(self): """ Populates json serialization ready data. This is the method used to serialize and store the object data in to DB Returns: List of dicts. """ result = [] for mdl in self: result.append(super(ListNode, mdl).clean_value()) return result |
def remove(self): """ Removes an item from ListNode. Raises: TypeError: If it's called on container ListNode (intstead of ListNode's item) Note: Parent object should be explicitly saved. """ if not self._is_item: raise TypeError("Should be called on an item, not ListNode's itself.") self.container.node_stack.remove(sel... |
def entityTriples(self, aURI): """ Builds all triples for an entity Note: if a triple object is a blank node (=a nested definition) we try to extract all relevant data recursively (does not work with sparql endpoins) 2015-10-18: updated """ aURI = aURI qres = self.rdfgraph.query( """CONSTRUCT {<%s> ?y ?z } WHERE { { <%... |
def getAllClasses(self, hide_base_schemas=True): """ by default, obscure all RDF/RDFS/OWL/XML stuff 2016-05-06: not obscured anymore """ query = """SELECT DISTINCT ?x ?c WHERE { { { ?x a owl:Class } union { ?x a rdfs:Class } union { ?x rdfs:subClassOf ?y } union { ?z rdfs:subClassOf ?x } union { ?y rdfs:domain ?x } uni... |
def getClassDirectSubs(self, aURI): """ 2015-06-03: currenlty not used, inferred from above """ aURI = aURI qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { ?x rdfs:subClassOf <%s> } FILTER (!isBlank(?x)) } """ % (aURI)) return list(qres) |
def getClassAllSupers(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { <%s> rdfs:subClassOf+ ?x } FILTER (!isBlank(?x)) } """ % (aURI)) except: printDebug("... warning: the 'getClassAllSupers' ... |
def getClassAllSubs(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { ?x rdfs:subClassOf+ <%s> } FILTER (!isBlank(?x)) } """ % (aURI)) except: printDebug("... warning: the 'getClassAllSubs' quer... |
def getPropAllSupers(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { <%s> rdfs:subPropertyOf+ ?x } FILTER (!isBlank(?x)) } """ % (aURI)) except: printDebug("... warning: the 'getPropAllSupers'... |
def getPropAllSubs(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { ?x rdfs:subPropertyOf+ <%s> } FILTER (!isBlank(?x)) } """ % (aURI)) except: printDebug("... warning: the 'getPropAllSubs' que... |
def getSKOSDirectSubs(self, aURI): """ 2015-08-19: currenlty not used, inferred from above """ aURI = aURI qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { { { ?x skos:broader <%s> } UNION { <%s> skos:narrower ?s } } FILTER (!isBlank(?x)) } """ % (aURI, aURI)) return list(qres) |
def encode(self): """ Encodes the object to a xml.etree.ElementTree.Element :return: the encoded element :rtype: xml.etree.ElementTree.Element """ root_element = ElementTree.Element(self.TAG_NAME) for value in [value for value in self.__dict__.values() if isinstance(value, fields.Field)]: if value.required or value.val... |
def progressbar( iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None): """Create a progressbar that works in Jupyter/IPython notebooks and ... |
def plot(graph, show_x_axis=True, head=None, tail=None, label_length=4, padding=0, height=2, show_min_max=True, show_data_range=True, show_title=True): """ show_x_axis: Display X axis head: Show first [head:] elements tail: Show last [-tail:] elements padding: Padding size between columns (default 0) height: Override g... |
= [sep.join(a) for a in out] if show_min_max: lines[0] = lines[0] + " -- Max: %s" % str(max(graph.data)) lines[-1] = lines[-1] + " -- Min %s" % str(min(graph.data)) print '\n'.join(lines) if graph.labels and show_x_axis: print (u'%s' % x_sep.join(['<%s>[%s]%s' % (label[:label_length], str(v), get_padding_str(label, v))... |
graph.labels: # 2('[])' + 2('<>') + 1 space sep = ' ' * (label_length + 1 + 2 + m + 2) __plot(graph) |
def strings(self): """ The structure of the bar graph. A list that contains all the strings that build up a bar in the given position. thise strings are inside a list, starting from the top level. structure: [ 1st bar -> ['1st level str', ..., 'height-1 str', 'height str'], 2nd bar -> ['1st level str', ..., 'height-1 s... |
_str(idx) strings.append(_s) return strings has_0 = min(self.data) == 0 self.__list = STACK_VALUES if has_0: self.__list = STACK_VALUES_0 mapped_values = ([self.__get_stack_id(x, self.data, self.height) for x in self.data]) return ([get_strings(stack_id, self.height) for stack_id in mapped_values]) |
def __get_stack_id(self, value, values, height): """ Returns the index of the column representation of the given value ▁ ▂ ▃ ▄ ▅ ▆ ▇' ... ▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ▇ ▇ ▇ ▇ ▇ ... ▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ... For example given the values: 1, 2, 3, ..., 2... |
or 1) step_value = step(values, height) return int(round((value - min(values)) / step_value)) |
def seaborn_set(context='poster', style='white', palette='colorblind', font_scale=1.3, font='serif', rc=mpl_rc): """ Perform `seaborn.set(**kwargs)`. Additional keyword arguments are passed in using this module's `attr:mpl_rc` attribute. """ sns.set(context="poster", style="white", palette="colorblind", font_scale=1.3,... |
def _gen_figure(nxplot=1, nyplot=1, figargs=None, projection=None, sharex='none', joinx=False, sharey='none', joiny=False, x=None, nxlabel=None, xlabels=None, nxdecimal=None, xmin=None, xmax=None, y=None, nylabel=None, ylabels=None, nydecimal=None, ymin=None, ymax=None, z=None, nzlabel=None, zlabels=None, nzdecimal=Non... |
{} for ax in axs: if 'x' in data: methods['x'] = (ax.set_xlim, ax.set_xticks, ax.set_xticklabels, nxlabel, xlabels, nxdecimal, xmin, xmax) if 'y' in data: methods['y'] = (ax.set_ylim, ax.set_yticks, ax.set_yticklabels, nylabel, ylabels, nydecimal, ymin, ymax) if 'z' in data: methods['z'] = (ax.set_zlim, ax.set_zticks, ... |
= mins if mins is not None else arr.min() amax = maxs if maxs is not None else arr.max() lim((amin, amax)) elif mins is not None and maxs is not None: if nlabel is not None: ticks(np.linspace(amin, amax, nlabel)) if decs is not None: sub = "{{:.{}f}}".format(decs).format labels([sub(i) for i in np.linspace(amin, amax, ... |
def check_key(data_object, key, cardinal=False): """ Update the value of an index key by matching values or getting positionals. """ itype = (int, np.int32, np.int64) if not isinstance(key, itype + (slice, tuple, list, np.ndarray)): raise KeyError("Unknown key type {} for key {}".format(type(key), key)) keys = data_obj... |
def slice_naive(self, key): """ Slice a data object based on its index, either by value (.loc) or position (.iloc). Args: key: Single index value, slice, tuple, or list of indices/positionals Returns: data: Slice of self """ cls = self.__class__ key = check_key(self, key) return cls(self.loc[key]) |
def cardinal_groupby(self): """ Group this object on it cardinal dimension (_cardinal). Returns: grpby: Pandas groupby object (grouped on _cardinal) """ g, t = self._cardinal self[g] = self[g].astype(t) grpby = self.groupby(g) self[g] = self[g].astype('category') return grpby |
def slice_cardinal(self, key): """ Get the slice of this object by the value or values of the cardinal dimension. """ cls = self.__class__ key = check_key(self, key, cardinal=True) return cls(self[self[self._cardinal[0]].isin(key)]) |
def copy(self, *args, **kwargs): """ Make a copy of this object. See Also: For arguments and description of behavior see `pandas docs`_. .. _pandas docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.copy.html """ cls = self.__class__ # Note that type conversion does not perform copy return cls(pd... |
def copy(self, *args, **kwargs): """ Make a copy of this object. See Also: For arguments and description of behavior see `pandas docs`_. .. _pandas docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.copy.html """ cls = self.__class__ # Note that type conversion does not perform copy return cls(pd... |
def _revert_categories(self): """ Inplace conversion to categories. """ for column, dtype in self._categories.items(): if column in self.columns: self[column] = self[column].astype(dtype) |
def _set_categories(self): """ Inplace conversion from categories. """ for column, _ in self._categories.items(): if column in self.columns: self[column] = self[column].astype('category') |
def copy(self, *args, **kwargs): """ Make a copy of this object. Note: Copies both field data and field values. See Also: For arguments and description of behavior see `pandas docs`_. .. _pandas docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.copy.html """ cls = self.__class__ # Note that type... |
def memory_usage(self): """ Get the combined memory usage of the field data and field values. """ data = super(Field, self).memory_usage() values = 0 for value in self.field_values: values += value.memory_usage() data['field_values'] = values return data |
def slice_naive(self, key): """ Naively (on index) slice the field data and values. Args: key: Int, slice, or iterable to select data and values Returns: field: Sliced field object """ cls = self.__class__ key = check_key(self, key) enum = pd.Series(range(len(self))) enum.index = self.index values = self.field_values[e... |
def cli(): """Function for cli""" epilog = ('The actions are:\n' '\tnew\t\tCreate a new torn app\n' '\trun\t\tRun the app and start a Web server for development\n' '\tcontroller\tCreate a new controller\n' '\tversion\t\treturns the current version of torn\n') parser = ArgumentParser(prog='torn', description='A full fle... |
def release(self): """Destroys the state, along with its functions.""" self.clear() if hasattr(self, "functions"): del self.functions if hasattr(self, "lib") and self.lib is not None: self.lib._jit_destroy_state(self.state) self.lib = None |
def clear(self): """Clears state so it can be used for generating entirely new instructions.""" if not self._clear: self.lib._jit_clear_state(self.state) self._clear = True |
def emit_function(self, return_type=None, argtypes=[], proxy=True): """Compiles code and returns a Python-callable function.""" if argtypes is not None: make_func = ctypes.CFUNCTYPE(return_type, *argtypes) else: make_func = ctypes.CFUNCTYPE(return_type) # NOTE: An optional way of binding the function is to use cffi. # ... |
func |
def _worker_method(self): """ The body of the multi-get worker. Loops until :meth:`_should_quit` returns ``True``, taking tasks off the input queue, fetching the object, and putting them on the output queue. """ while not self._should_quit(): try: task = self._inq.get(block=True, timeout=0.25) except TypeError: if self... |
async def change_url(self, url: str, description: str = None): """ change the url of that attachment |methcoro| Args: url: url you want to change description: *optional* description for your attachment Raises: ValueError: url must not be None APIException """ await self._change(url=url, description=description) |
async def change_file(self, file_path: str, description: str = None): """ change the file of that attachment |methcoro| Warning: |unstable| Args: file_path: path to the file you want to add / modify description: *optional* description for your attachment Raises: ValueError: file_path must not be None APIException """ w... |
def cached(namespace=None, service="memory", debug=False): """ Wrapper for tornado requests. Example ``` class MainHandler(tornado.web.RequestHandler): @debris.tornado.cached("home-page") def get(self): self.write("Hello, world") ``` """ _service = getattr(debris.services, service) def wrapper(_f): @functools.wraps(_f)... |
def which(program, environ=None): """ Find out if an executable exists in the supplied PATH. If so, the absolute path to the executable is returned. If not, an exception is raised. :type string :param program: Executable to be checked for :param dict :param environ: Any additional ENV variables required, specifically P... |
def run(command, timeout=None, cwd=None, env=None, debug=None): """ Runs a given command on the system within a set time period, providing an easy way to access command output as it happens without waiting for the command to finish running. :type list :param command: Should be a list that contains the command that shou... |
is not considered when searching the executable, so you can’t specify the program’s path relative to cwd. :type dict :param env: A dict of any ENV variables that should be combined into the OS ENV that will help the command to run successfully. Note that more often than not the command run does not have the same ENV va... |
commands or redirect output of a tail -f call as lines get outputted without having to wait till the command finishes. :return returns :class:`Command.Response` that contains the exit code and the output from the command """ return Command.run(command, timeout=timeout, cwd=cwd, env=env, debug=debug) |
def run(cls, command, timeout=None, cwd=None, env=None, debug=None): """ Runs a given command on the system within a set time period, providing an easy way to access command output as it happens without waiting for the command to finish running. :type list :param command: Should be a list that contains the command that... |
directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd. :type dict :param env: A dict of any ENV variables that should be combined into the OS ENV that will help the command to run successfully. Note that more often than not the command run does not have the s... |
running commands or redirect output of a tail -f call as lines get outputted without having to wait till the command finishes. :return returns :class:`Command.Response` that contains the exit code and the output from the command """ # Merge together the system ENV details and the passed in ones if any environ = dict(os... |
can call debug_output = False if debug and (callable(debug) or hasattr(debug, "__call__")): debug_output = True if debug_output: def track(thefile, shutdown=None): """Process the temp file until a valid line is found and return it""" thefile.seek(0, 2) while True: if shutdown and shutdown.isSet(): break line = thefile.... |
= threading.Thread(target=target, name='Command Runner') thread.start() thread.join(timeout) if thread.is_alive(): cls.process.terminate() thread.join() if thread.is_alive(): cls.process.kill() # Prime the response response = Response response.command = command response.exit = cls.process.returncode # Fetch from the te... |
def form_valid(self, form): """This is what's called when the form is valid.""" instance = form.save(commit=False) if hasattr(self.request, 'user'): instance.user = self.request.user if settings.CONTACT_FORM_FILTER_MESSAGE: instance.message = bleach.clean( instance.message, tags=settings.CONTACT_FORM_ALLOWED_MESSAGE_TA... |
def form_invalid(self, form): """This is what's called when the form is invalid.""" ip = get_user_ip(self.request) if settings.CONTACT_FORM_USE_SIGNALS: contact_form_invalid.send( sender=self, event=self.invalid_event, ip=ip, site=self.site, sender_name=form['sender_name'], sender_email=form['sender_email'] ) return su... |
def bind_settings(): """ Put DJANGO_TEMPLATE_* under the right settings.* name according to django-version :return: """ from django_productline import settings if settings.TEMPLATE_LOADER_CACHED_ENABLED: loaders = [ ['django.template.loaders.cached.Loader', settings.DJANGO_TEMPLATE_LOADERS] ] else: loaders = settings.D... |
def add_tag(self, name): """ Create a Tag to current object :param name: the name of the tag :type name: str :return: newly created Tag :rtype: Tag """ from highton.models.tag import Tag created_id = self._post_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Tag.ENDPOINT, data=self.element_to_string( Tag(n... |
def time_bins(header): ''' Returns the time-axis lower bin edge values for the spectrogram. ''' return np.arange(header['number_of_half_frames'], dtype=np.float64)*constants.bins_per_half_frame\ *(1.0 - header['over_sampling']) / header['subband_spacing_hz'] |
def frequency_bins(header): ''' Returnes the frequency-axis lower bin edge values for the spectrogram. ''' center_frequency = 1.0e6*header['rf_center_frequency'] if header["number_of_subbands"] > 1: center_frequency += header["subband_spacing_hz"]*(header["number_of_subbands"]/2.0 - 0.5) return np.fft.fftshift(\ np.fft... |
def complex_to_fourier(cdata, over_sampling, norm=None): ''' cdata: 3D complex data (shaped by subbands and half_frames, as returned from Compamp.complex_data()) over_sampling: The fraction of oversampling across subbands (typically 0.25) norm: None or "ortho" -- see Numpy FFT Normalization documentation. Default is No... |
def fourier_to_time(fcdata, norm=None): ''' Converts the data from 2D fourier space signal to a 1D time-series. fcdata: Complex fourier spectrum as a 2D array, The axis=0 is for each "half frame", and axis=1 contains the fourier-space data for that half frame. Typically there are 129 "half frames" in the data. Furtherm... |
= cdata_1d.reshape(aca.header()['number_of_half_frames'], int(aca.header()['number_of_subbands'] * ibmseti.constants.bins_per_half_frame*(1 - aca.header()['over_sampling']))) fcdata_2d_v2 = np.fft.fftshift(np.fft.fft(cdata_2d), 1) #fcdata_2d_v2 and fcdata_2d should be the same np.sum(np.sum(fcdata_2d - fcdata_2d_v2)) #... |
def complex_to_power(cdata, over_sampling): ''' cdata: 3D complex data (shaped by subbands and half_frames, as returned from Compamp.complex_data()) over_sampling: The fraction of oversampling across subbands (typically 0.25). returns a 3D spectrogram Example: aca = ibmseti.compamp.Compamp(raw_data) cdata = aca.complex... |
def reshape_to_2d(arr): ''' Assumes a 3D Numpy array, and reshapes like arr.reshape((arr.shape[0], arr.shape[1]*arr.shape[2])) This is useful for converting processed data from `complex_to_power` and from `autocorrelation` into a 2D array for image analysis and display. ''' return arr.reshape((arr.shape[0], arr.shape[1... |
def compamp_to_spectrogram(compamp): ''' Returns spectrogram, with each row containing the measured power spectrum for a XX second time sample. Using this function is shorthand for: aca = ibmseti.compamp.Compamp(raw_data) power = ibmseti.dsp.complex_to_power(aca.complex_data(), aca.header()['over_sampling']) spectrogra... |
def compamp_to_ac(compamp, window=np.hanning): # convert single or multi-subband compamps into autocorrelation waterfall ''' Adapted from Gerry Harp at SETI. ''' header = compamp.header() cdata = compamp.complex_data() #Apply Windowing and Padding cdata = np.multiply(cdata, window(cdata.shape[2])) # window for smoothin... |
each row to sqrt of AC triangle cdata = np.divide(cdata, np.sqrt(np.sum(cdata, axis=2))[:, :, np.newaxis]) return cdata |
def ac_viz(acdata): ''' Adapted from Gerry Harp at SETI. Slightly massages the autocorrelated calculation result for better visualization. In particular, the natural log of the data are calculated and the values along the subband edges are set to the maximum value of the data, and the t=0 delay of the autocorrelation r... |
:, acdata.shape[2] - 1] = np.max(acdata) # visualize subband edges return acdata |
def server_error(request, template_name='500.html'): """ 500 error handler. Templates: `500.html` Context: STATIC_URL Path of static media (e.g. "media.example.org") """ t = loader.get_template(template_name) return HttpResponseServerError( t.render(Context({'STATIC_URL': settings.STATIC_URL}))) |
def relation(x_start, x_end, y_start, y_end): """ Returns the relation between two intervals. :param int x_start: The start point of the first interval. :param int x_end: The end point of the first interval. :param int y_start: The start point of the second interval. :param int y_end: The end point of the second interv... |
Allen.X_OVERLAPS_WITH_Y if diff_start == 0: return Allen.X_STARTS_Y if diff_start < 0: return Allen.X_DURING_Y |
def server_factory(global_conf, host, port, **options): """Server factory for paste. Options are: * proactor: class name to use from cogen.core.proactors (default: DefaultProactor - best available proactor for current platform) * proactor_resolution: float * sched_default_priority: int (see cogen.core.util.priority) * ... |
def start_response(self, status, headers, exc_info = None): """WSGI callable to begin the HTTP response.""" if self.started_response: if not exc_info: raise AssertionError("WSGI start_response called a second " "time with no exc_info.") else: try: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None sel... |
def simple_response(self, status, msg=""): """Return a operation for writing simple response back to the client.""" status = str(status) buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status), "Content-Length: %s\r\n" % len(msg), "Content-Type: text/plain\r\n"] if status[:3] == "413" and self.response_pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.