Search is not available for this dataset
text
stringlengths
75
104k
def periods(ts, phi=0.0): """For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeser...
def circmean(ts, axis=2): """Circular mean phase""" return np.exp(1.0j * ts).mean(axis=axis).angle()
def order_param(ts, axis=2): """Order parameter of phase synchronization""" return np.abs(np.exp(1.0j * ts).mean(axis=axis))
def cwtmorlet(points, width): """complex morlet wavelet function compatible with scipy.signal.cwt Parameters: points: int Number of points in `vector`. width: scalar Width parameter of wavelet. Equals (sample rate / fundamental frequenc...
def roughcwt(data, wavelet, widths): """ Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT performs a convolution with `data` using the `wavelet` function, which is characterized by a width parameter and length parameter. P...
def variability_fp(ts, freqs=None, ncycles=6, plot=True): """Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the ...
def _rescale(ar): """Shift and rescale array ar to the interval [-1, 1]""" max = np.nanmax(ar) min = np.nanmin(ar) midpoint = (max + min) / 2.0 return 2.0 * (ar - midpoint) / (max - min)
def _get_color_list(): """Get cycle of colors in a way compatible with all matplotlib versions""" if 'axes.prop_cycle' in plt.rcParams: return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])] else: return plt.rcParams['axes.color_cycle']
def _plot_variability(ts, variability, threshold=None, epochs=None): """Plot the timeseries and variability. Optionally plot epochs.""" import matplotlib.style import matplotlib as mpl mpl.style.use('classic') import matplotlib.pyplot as plt if variability.ndim is 1: variability = variab...
def epochs(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceedi...
def epochs_distributed(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Same as `epochs()`, but computes channels in parallel for speed. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Identify...
def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0, proportion=0.75, plot=True): """Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This req...
def plot(ts, title=None, show=True): """Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a figure object """ ts = _remove_pi_crossings(ts) fig = plt.figure() ylabelprops = dict(rotation=0, hor...
def _remove_pi_crossings(ts): """For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points where the phase crosses pi to 'nan' so that spurious lines will not be plotted. If ts does not need adjustment, then return ts. Otherwis...
def timeseries_from_mat(filename, varname=None, fs=1.0): """load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str): .mat file to load varname (str): variable name. only needed if there is more than one variable saved in the .mat file fs (scalar): sample rate of t...
def save_mat(ts, filename): """save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save to """ import scipy.io as sio tspan = ts.tspan fs = (1.0*len(tspan) - 1) / (tspan[-1] - tspan[0]) mat_dict = {'data': np.asar...
def timeseries_from_file(filename): """Load a multi-channel Timeseries from any file type supported by `biosig` Supported file formats include EDF/EDF+, BDF/BDF+, EEG, CNT and GDF. Full list is here: http://pub.ist.ac.at/~schloegl/biosig/TESTED For EDF, EDF+, BDF and BDF+ files, we will use python-edf...
def _load_edflib(filename): """load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: Timeseries """ import edflib e = edflib.EdfReader(filename, annotations_mode='all') if np.ptp(e.get_samples_...
def annotations_from_file(filename): """Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text] """ import edflib e = edflib.EdfR...
def _ufunc_wrap(out_arr, ufunc, method, i, inputs, **kwargs): """After using the superclass __numpy_ufunc__ to route ufunc computations on the array data, convert any resulting ndarray, RemoteArray and DistArray instances into Timeseries, RemoteTimeseries and DistTimeseries instances if appropriate""" ...
def _rts_from_ra(ra, tspan, labels, block=True): """construct a RemoteTimeseries from a RemoteArray""" def _convert(a, tspan, labels): from nsim import Timeseries return Timeseries(a, tspan, labels) return distob.call( _convert, ra, tspan, labels, prefer_local=False, block=block)
def _dts_from_da(da, tspan, labels): """construct a DistTimeseries from a DistArray""" sublabels = labels[:] new_subarrays = [] for i, ra in enumerate(da._subarrays): if isinstance(ra, RemoteTimeseries): new_subarrays.append(ra) else: if labels[da._distaxis]: ...
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True): """Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulati...
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel): """Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and...
def __clone_function(f, name=None): """Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the ...
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis <= self._distaxis: subaxis = axis new_distaxis = self._distaxis + 1 ...
def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) """ da = distob.vectorize(np.absolute)(self) return _dts_from_da(da, self.tspan, self.label...
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
def coupling(self, source_y, target_y, weight): """How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the ...
def f(self, y, t): """Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the compl...
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
def _reshape_timeseries(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" if np.count_nonzero(np.diff(self._sublengths)) == 0: # then all submodels have the same dimension, so can reshape array # in place without copying data: subdim = se...
def _reshape_output(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" subodim = len(self.submodels[0].output_vars) shp = list(ts.shape) shp[1] = subodim shp.insert(2, self._n) ts = ts.reshape(tuple(shp)) ts.labels[2] = self._node_labe...
def timeseries(self): """Simulated time series""" if self._timeseries is None: self.compute() if isinstance(self.system, NetworkModel): return self.system._reshape_timeseries(self._timeseries) else: return self._timeseries
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [s.output for s in self.sims] sub_ndim = subts[0].ndim if sub...
def _tosub(self, ix): """Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m] """ N = self._n if ix >= N or ix < -N: raise IndexError( ...
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [rms.output for rms in self._subsims] distaxis = subts[0].ndim - 1 ...
def crossing_times(ts, c=0.0, d=0.0): """For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the time...
def first_return_times(ts, c=None, d=0.0): """For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: t...
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: ...
def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a se...
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # qui...
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02...
def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. ...
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self...
def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, ...
def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) ...
def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._he...
def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call th...
def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster...
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done...
def process_results(self): """ Process results by providers """ for result in self._results: provider = result.provider self.providers.append(provider) if result.error: self.failed_providers.append(provider) continue if not ...
async def dnsbl_request(self, addr, provider): """ Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError "...
async def _check_ip(self, addr): """ Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object """ tasks = [] for provider in self.providers: tasks.append(self.dnsbl_request(ad...
def check_ips(self, addrs): """ sync check multiple ips """ tasks = [] for addr in addrs: tasks.append(self._check_ip(addr)) return self._loop.run_until_complete(asyncio.gather(*tasks))
def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step
def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 ...
def load_nouns(self, file): """ Load dict from file for random words. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nouns = json.load(f)
def load_dmails(self, file): """ Load list from file for random mails :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.dmails = frozenset(json.load(f))
def load_nicknames(self, file): """ Load dict from file for random nicknames. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nicknames = json.load(f)
def random_words(self, letter=None, count=1): """ Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError """ self.check_count(count) words =...
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
def get_sentences_list(self, sentences=1): """ Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list """ if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') ...
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
def _discover_toc(zf, opf_xmldoc, opf_filepath): ''' Returns a list of objects: {title: str, src: str, level: int, index: int} ''' toc = None # ePub 3.x tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav') if tag and 'href' in tag.attributes.keys(): filepath = unquote(tag.attribu...
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True): ''' References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata ''' if not zipfile.is_zipfile(filepath): r...
def get_epub_opf_xml(filepath): ''' Returns the file.OPF contents of the ePub file ''' if not zipfile.is_zipfile(filepath): raise EPubException('Unknown file') # print('Reading ePub file: {}'.format(filepath)) zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi...
def firstname(self, value, case, gender=None): u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Firstname cannot ...
def lastname(self, value, case, gender=None): u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Lastname cannot ...
def middlename(self, value, case, gender=None): u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Middlename ca...
def __split_name(self, name): u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями """ def gen(name, separators): if len(separators) == 0: yield name else:...
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
def compress(expression): """ Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5...
def selections(expression, keep_delimiters=True): """ Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. ...
def resolve(container, expression): """ Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. """ itemgetter = getattr(container, 'get_item', container.get) tokens = [] expression = expression.strip() for sel_delim, _id, _r...
def referents(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by ...
def referrers(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`. """ if refattrs is None: result = {} else: result = {...
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'): """ >>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ...
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
def _get_file_content(source): """Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in ...
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
def _open_next(self): """Proceed to next volume.""" # is the file split over archives? if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0: return False if self._fd: self._fd.close() self._fd = None # open next part self._volfil...
def _check(self): # TODO: fix? """Do not check final CRC.""" if self._returncode: rarfile.check_returncode(self, '') if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")