INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns a list of the implemented coordination geometries with the given coordination number. :param coordination: The coordination number of which the list of implemented coordination geometries are returned.
def get_not_implemented_geometries(self, coordination=None, returned='mp_symbol'): """ Returns a list of the implemented coordination geometries with the given coordination number. :param coordination: The coordination number of which the list of implemente...
Returns the coordination geometry of the given name. :param name: The name of the coordination geometry.
def get_geometry_from_name(self, name): """ Returns the coordination geometry of the given name. :param name: The name of the coordination geometry. """ for gg in self.cg_list: if gg.name == name or name in gg.alternative_names: return gg raise...
Returns the coordination geometry of the given IUPAC symbol. :param IUPAC_symbol: The IUPAC symbol of the coordination geometry.
def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): """ Returns the coordination geometry of the given IUPAC symbol. :param IUPAC_symbol: The IUPAC symbol of the coordination geometry. """ for gg in self.cg_list: if gg.IUPAC_symbol == IUPAC_symbol: ...
Returns the coordination geometry of the given IUCr symbol. :param IUCr_symbol: The IUCr symbol of the coordination geometry.
def get_geometry_from_IUCr_symbol(self, IUCr_symbol): """ Returns the coordination geometry of the given IUCr symbol. :param IUCr_symbol: The IUCr symbol of the coordination geometry. """ for gg in self.cg_list: if gg.IUCr_symbol == IUCr_symbol: return...
Returns the coordination geometry of the given mp_symbol. :param mp_symbol: The mp_symbol of the coordination geometry.
def get_geometry_from_mp_symbol(self, mp_symbol): """ Returns the coordination geometry of the given mp_symbol. :param mp_symbol: The mp_symbol of the coordination geometry. """ for gg in self.cg_list: if gg.mp_symbol == mp_symbol: return gg ra...
Checks whether a given coordination geometry is valid (exists) and whether the parameters are coherent with each other. :param IUPAC_symbol: :param IUCr_symbol: :param name: :param cn: :param mp_symbol: The mp_symbol of the coordination geometry.
def is_a_valid_coordination_geometry(self, mp_symbol=None, IUPAC_symbol=None, IUCr_symbol=None, name=None, cn=None): """ Checks whether a given coordination geometry is valid (exists) and whether the parameters are coheren...
True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. s...
def are_equal(self, sp1, sp2): """ True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the ...
True if element:amounts are exactly the same, i.e., oxidation state is not considered. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: amt} as per the ...
def are_equal(self, sp1, sp2): """ True if element:amounts are exactly the same, i.e., oxidation state is not considered. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species...
True if there is some overlap in composition between the species Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: amt} as per the definition in Site a...
def are_equal(self, sp1, sp2): """ True if there is some overlap in composition between the species Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: a...
Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. Returns: True if sets of occupancies...
def are_equal(self, sp1, sp2): """ Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. ...
Returns the supercell size, and whether the supercell should be applied to s1. If fu == 1, s1_supercell is returned as true, to avoid ambiguity.
def _get_supercell_size(self, s1, s2): """ Returns the supercell size, and whether the supercell should be applied to s1. If fu == 1, s1_supercell is returned as true, to avoid ambiguity. """ if self._supercell_size == 'num_sites': fu = s2.num_sites / s1.num_s...
Yields lattices for s with lengths and angles close to the lattice of target_s. If supercell_size is specified, the returned lattice will have that number of primitive cells in it Args: s, target_s: Structure objects
def _get_lattices(self, target_lattice, s, supercell_size=1): """ Yields lattices for s with lengths and angles close to the lattice of target_s. If supercell_size is specified, the returned lattice will have that number of primitive cells in it Args: s, targ...
Computes all supercells of one structure close to the lattice of the other if s1_supercell == True, it makes the supercells of struct1, otherwise it makes them of s2 yields: s1, s2, supercell_matrix, average_lattice, supercell_matrix
def _get_supercells(self, struct1, struct2, fu, s1_supercell): """ Computes all supercells of one structure close to the lattice of the other if s1_supercell == True, it makes the supercells of struct1, otherwise it makes them of s2 yields: s1, s2, supercell_matrix, aver...
Returns true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1
def _cmp_fstruct(self, s1, s2, frac_tol, mask): """ Returns true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1 """ if len(s2) > len(s1): raise ValueError("s1 must be larger than s2") if mask.shape != (len(s2), len(s1)): ...
Finds a matching in cartesian space. Finds an additional fractional translation vector to minimize RMS distance Args: s1, s2: numpy arrays of fractional coordinates. len(s1) >= len(s2) avg_lattice: Lattice on which to calculate distances mask: numpy array of booleans...
def _cart_dists(self, s1, s2, avg_lattice, mask, normalization, lll_frac_tol=None): """ Finds a matching in cartesian space. Finds an additional fractional translation vector to minimize RMS distance Args: s1, s2: numpy arrays of fractional coordinates. len(s1) >= len(s2) ...
Returns mask for matching struct2 to struct1. If struct1 has sites a b c, and fu = 2, assumes supercells of struct2 will be ordered aabbcc (rather than abcabc) Returns: mask, struct1 translation indices, struct2 translation index
def _get_mask(self, struct1, struct2, fu, s1_supercell): """ Returns mask for matching struct2 to struct1. If struct1 has sites a b c, and fu = 2, assumes supercells of struct2 will be ordered aabbcc (rather than abcabc) Returns: mask, struct1 translation indices, struct...
Fit two structures. Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: True or False.
def fit(self, struct1, struct2): """ Fit two structures. Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: True or False. """ struct1, struct2 = self._process_species([struct1, struct2]) if ...
Rescales, finds the reduced structures (primitive and niggli), and finds fu, the supercell size to make struct1 comparable to s2
def _preprocess(self, struct1, struct2, niggli=True): """ Rescales, finds the reduced structures (primitive and niggli), and finds fu, the supercell size to make struct1 comparable to s2 """ struct1 = struct1.copy() struct2 = struct2.copy() if niggli: ...
Matches one struct onto the other
def _match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False, break_on_match=False): """ Matches one struct onto the other """ ratio = fu if s1_supercell else 1/fu if len(struct1) * ratio >= len(struct2): return self._strict_match( ...
Matches struct2 onto struct1 (which should contain all sites in struct2). Args: struct1, struct2 (Structure): structures to be matched fu (int): size of supercell to create s1_supercell (bool): whether to create the supercell of struct1 (vs struct2) ...
def _strict_match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False, break_on_match=False): """ Matches struct2 onto struct1 (which should contain all sites in struct2). Args: struct1, struct2 (Structure): structures to be matched ...
Given a list of structures, use fit to group them by structural equality. Args: s_list ([Structure]): List of structures to be grouped anonymous (bool): Wheher to use anonymous mode. Returns: A list of lists of matched structures Assumption: if s...
def group_structures(self, s_list, anonymous=False): """ Given a list of structures, use fit to group them by structural equality. Args: s_list ([Structure]): List of structures to be grouped anonymous (bool): Wheher to use anonymous mode. Returns: ...
Tries all permutations of matching struct1 to struct2. Args: struct1, struct2 (Structure): Preprocessed input structures Returns: List of (mapping, match)
def _anonymous_match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False, break_on_match=False, single_match=False): """ Tries all permutations of matching struct1 to struct2. Args: struct1, struct2 (Structure): Preprocessed input structures ...
Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: (min_r...
def get_rms_anonymous(self, struct1, struct2): """ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. Args: struct1 (Structure): 1st structure stru...
Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. If multiple substitutions are within tolerance this will return the one which minimizes the difference in electronegativity betwe...
def get_best_electronegativity_anonymous_mapping(self, struct1, struct2): """ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. If multiple substitutions are within tolerance ...
Performs an anonymous fitting, which allows distinct species in one structure to map to another. Returns a dictionary of species substitutions that are within tolerance Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure niggli (bool):...
def get_all_anonymous_mappings(self, struct1, struct2, niggli=True, include_dist=False): """ Performs an anonymous fitting, which allows distinct species in one structure to map to another. Returns a dictionary of species substitutions that are within t...
Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: True/F...
def fit_anonymous(self, struct1, struct2, niggli=True): """ Performs an anonymous fitting, which allows distinct species in one structure to map to another. E.g., to compare if the Li2O and Na2O structures are similar. Args: struct1 (Structure): 1st structure ...
Returns the matrix for transforming struct to supercell. This can be used for very distorted 'supercells' where the primitive cell is impossible to find
def get_supercell_matrix(self, supercell, struct): """ Returns the matrix for transforming struct to supercell. This can be used for very distorted 'supercells' where the primitive cell is impossible to find """ if self._primitive_cell: raise ValueError("get_s...
Returns the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1. Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. Returns: supercell (numpy.ndarray(3,...
def get_transformation(self, struct1, struct2): """ Returns the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1. Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to ...
Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. include_ignored_species (bool): Defaults to True...
def get_s2_like_s1(self, struct1, struct2, include_ignored_species=True): """ Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (St...
Calculate the mapping from superset to subset. Args: superset (Structure): Structure containing at least the sites in subset (within the structure matching tolerance) subset (Structure): Structure containing some of the sites in superset (within the struc...
def get_mapping(self, superset, subset): """ Calculate the mapping from superset to subset. Args: superset (Structure): Structure containing at least the sites in subset (within the structure matching tolerance) subset (Structure): Structure containing so...
Args: d1: First defect. A pymatgen Defect object. d2: Second defect. A pymatgen Defect object. Returns: True if defects are identical in type and sublattice.
def are_equal(self, d1, d2): """ Args: d1: First defect. A pymatgen Defect object. d2: Second defect. A pymatgen Defect object. Returns: True if defects are identical in type and sublattice. """ possible_defect_types = (Defect, Vacancy, Substi...
Convenience constructor to make a ConversionElectrode from a composition and a phase diagram. Args: comp: Starting composition for ConversionElectrode, e.g., Composition("FeF3") pd: A PhaseDiagram of the relevant system (e.g., Li-F...
def from_composition_and_pd(comp, pd, working_ion_symbol="Li"): """ Convenience constructor to make a ConversionElectrode from a composition and a phase diagram. Args: comp: Starting composition for ConversionElectrode, e.g., Composition("FeF3...
Convenience constructor to make a ConversionElectrode from a composition and all entries in a chemical system. Args: comp: Starting composition for ConversionElectrode, e.g., Composition("FeF3") entries_in_chemsys: Sequence containing all entries in a ...
def from_composition_and_entries(comp, entries_in_chemsys, working_ion_symbol="Li"): """ Convenience constructor to make a ConversionElectrode from a composition and all entries in a chemical system. Args: comp: Starting composition for C...
If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2, LiTiO2 --> Li0.5TiO2, Li0.5TiO2 --> TiO2] This method can be ...
def get_sub_electrodes(self, adjacent_only=True): """ If this electrode contains multiple voltage steps, then it is possible to use only a subset of the voltage steps to define other electrodes. For example, an LiTiO2 electrode might contain three subelectrodes: [LiTiO2 --> TiO2,...
Checks if a particular conversion electrode is a sub electrode of the current electrode. Starting from a more lithiated state may result in a subelectrode that is essentially on the same path. For example, a ConversionElectrode formed by starting from an FePO4 composition would be a sup...
def is_super_electrode(self, conversion_electrode): """ Checks if a particular conversion electrode is a sub electrode of the current electrode. Starting from a more lithiated state may result in a subelectrode that is essentially on the same path. For example, a ConversionElect...
Args: print_subelectrodes: Also print data on all the possible subelectrodes Returns: a summary of this electrode"s properties in dictionary format
def get_summary_dict(self, print_subelectrodes=True): """ Args: print_subelectrodes: Also print data on all the possible subelectrodes Returns: a summary of this electrode"s properties in dictionary format """ d = {} framework_com...
Creates a ConversionVoltagePair from two steps in the element profile from a PD analysis. Args: step1: Starting step step2: Ending step normalization_els: Elements to normalize the reaction by. To ensure correct capacities.
def from_steps(step1, step2, normalization_els): """ Creates a ConversionVoltagePair from two steps in the element profile from a PD analysis. Args: step1: Starting step step2: Ending step normalization_els: Elements to normalize the reaction by. To ...
Creates an Xr object from a string representation. Args: string (str): string representation of an Xr object. use_cores (bool): use core positions and discard shell positions if set to True (default). Otherwise, use shell positions and discard co...
def from_string(string, use_cores=True, thresh=1.e-4): """ Creates an Xr object from a string representation. Args: string (str): string representation of an Xr object. use_cores (bool): use core positions and discard shell positions if set to True (d...
Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). Otherwise, use shell positions and discard core positio...
def from_file(filename, use_cores=True, thresh=1.e-4): """ Reads an xr-formatted file to create an Xr object. Args: filename (str): name of file to read from. use_cores (bool): use core positions and discard shell positions if set to True (default). ...
Frame a signal into overlapping frames. :param sig: the audio signal to frame. :param frame_len: length of each frame measured in samples. :param frame_step: number of samples after the start of the previous frame that the next frame should begin. :param winfunc: the analysis window to apply to each fr...
def framesig(sig, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,)), stride_trick=True): """Frame a signal into overlapping frames. :param sig: the audio signal to frame. :param frame_len: length of each frame measured in samples. :param frame_step: number of samples after the start of the prev...
Does overlap-add procedure to undo the action of framesig. :param frames: the array of frames. :param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples. :param frame_len: length of each frame measured in samples. :param frame_step: number of samples ...
def deframesig(frames, siglen, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,))): """Does overlap-add procedure to undo the action of framesig. :param frames: the array of frames. :param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples. :pa...
Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :returns: If frames is an NxD matrix, output will be...
def magspec(frames, NFFT): """Compute the magnitude spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :returns: If frame...
Compute the log power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :param norm: If norm=1, the log power spectrum is no...
def logpowspec(frames, NFFT, norm=1): """Compute the log power spectrum of each frame in frames. If frames is an NxD matrix, output will be Nx(NFFT/2+1). :param frames: the array of frames. Each row is a frame. :param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded. :param ...
Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples; a longer FFT than the window allows zero-padding of the FFT buffer which is neutral in terms...
def calculate_nfft(samplerate, winlen): """Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples; a longer FFT than the window allows zero-padding ...
Compute MFCC features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds) ...
def mfcc(signal,samplerate=16000,winlen=0.025,winstep=0.01,numcep=13, nfilt=26,nfft=None,lowfreq=0,highfreq=None,preemph=0.97,ceplifter=22,appendEnergy=True, winfunc=lambda x:numpy.ones((x,))): """Compute MFCC features from an audio signal. :param signal: the audio signal from which to comput...
Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen: the length of the analysis window in seconds. Default is 0.025s (25...
def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be ...
Compute log Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen: the length of the analysis window in seconds. Default is 0.025s...
def logfbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute log Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute feature...
Compute Spectral Subband Centroid features from an audio signal. :param signal: the audio signal from which to compute features. Should be an N*1 array :param samplerate: the sample rate of the signal we are working with, in Hz. :param winlen: the length of the analysis window in seconds. Default is 0.025s...
def ssc(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute Spectral Subband Centroid features from an audio signal. :param signal: the audio signal from which to compute features. Should be an...
Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1) :param nfilt: the number of filters in the filterbank, default 20. :param nfft: the FFT size. Default is 512. :param samplerate: the sample...
def get_filterbanks(nfilt=20,nfft=512,samplerate=16000,lowfreq=0,highfreq=None): """Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1) :param nfilt: the number of filters in the filterbank, defa...
Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. :param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size. :param L: the liftering coefficient to use. Default is 22. L <= 0 disables lifter.
def lifter(cepstra, L=22): """Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. :param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size. :param L: the liftering coefficient to use. Default is 22. L ...
Opens a CAN connection using `CanalOpen()`. :param str configuration: the configuration: "device_id; baudrate" :param int flags: the flags to be set :raises can.CanError: if any error occurred :returns: Valid handle for CANAL API functions on success
def open(self, configuration, flags): """ Opens a CAN connection using `CanalOpen()`. :param str configuration: the configuration: "device_id; baudrate" :param int flags: the flags to be set :raises can.CanError: if any error occurred :returns: Valid handle for CANAL AP...
Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns: A numpy array of size (NUM...
def delta(feat, N): """Compute delta features from a feature vector sequence. :param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector. :param N: For each frame, calculate delta features based on preceding and following N frames :returns:...
Fetches all messages in the database. :rtype: Generator[can.Message]
def read_all(self): """Fetches all messages in the database. :rtype: Generator[can.Message] """ result = self._cursor.execute("SELECT * FROM {}".format(self.table_name)).fetchall() return (SqliteReader._assemble_message(frame) for frame in result)
Creates a new databae or opens a connection to an existing one. .. note:: You can't share sqlite3 connections between threads (by default) hence we setup the db here. It has the upside of running async.
def _create_db(self): """Creates a new databae or opens a connection to an existing one. .. note:: You can't share sqlite3 connections between threads (by default) hence we setup the db here. It has the upside of running async. """ log.debug("Creating sqlite data...
Stops the reader an writes all remaining messages to the database. Thus, this might take a while and block.
def stop(self): """Stops the reader an writes all remaining messages to the database. Thus, this might take a while and block. """ BufferedReader.stop(self) self._stop_running_event.set() self._writer_thread.join() BaseIOHandler.stop(self)
Checks if the message parameters are valid. Assumes that the types are already correct. :raises ValueError: iff one or more attributes are invalid
def _check(self): """Checks if the message parameters are valid. Assumes that the types are already correct. :raises ValueError: iff one or more attributes are invalid """ if self.timestamp < 0.0: raise ValueError("the timestamp may not be negative") if isin...
Compares a given message with this one. :param can.Message other: the message to compare with :type timestamp_delta: float or int or None :param timestamp_delta: the maximum difference at which two timestamps are still considered equal or None to not compare tim...
def equals(self, other, timestamp_delta=1.0e-6): """ Compares a given message with this one. :param can.Message other: the message to compare with :type timestamp_delta: float or int or None :param timestamp_delta: the maximum difference at which two timestamps are ...
Map and return a symbol (function) from a C library. A reference to the mapped symbol is also held in the instance :param str func_name: symbol_name :param ctypes.c_* restype: function result type (i.e. ctypes.c_ulong...), defaults to void :param tuple(ctypes.c_*...
def map_symbol(self, func_name, restype=None, argtypes=(), errcheck=None): """ Map and return a symbol (function) from a C library. A reference to the mapped symbol is also held in the instance :param str func_name: symbol_name :param ctypes.c_* restype: ...
Decode (if needed) and return the ICS device serial string :param device: ics device :return: ics device serial string :rtype: str
def get_serial_number(device): """Decode (if needed) and return the ICS device serial string :param device: ics device :return: ics device serial string :rtype: str """ a0000 = 604661760 if device.SerialNumber >= a0000: return ics.base36enc(device.Ser...
Detect all configurations/channels that this interface could currently connect with. :rtype: Iterator[dict] :return: an iterable of dicts, each being a configuration suitable for usage in the interface's bus constructor.
def _detect_available_configs(): """Detect all configurations/channels that this interface could currently connect with. :rtype: Iterator[dict] :return: an iterable of dicts, each being a configuration suitable for usage in the interface's bus constructor. """ ...
CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>) /** * struct can_frame - basic CAN frame structure * @can_id: the CAN ID of the frame and CAN_*_FLAG flags, see above. * @can_dlc: the data length field of the CAN frame * @data: the CAN frame payload. */ struct c...
def build_can_frame(msg): """ CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>) /** * struct can_frame - basic CAN frame structure * @can_id: the CAN ID of the frame and CAN_*_FLAG flags, see above. * @can_dlc: the data length field of the CAN frame * @data: the CAN f...
create a broadcast manager socket and connect to the given interface
def create_bcm_socket(channel): """create a broadcast manager socket and connect to the given interface""" s = socket.socket(PF_CAN, socket.SOCK_DGRAM, CAN_BCM) if HAS_NATIVE_SUPPORT: s.connect((channel,)) else: addr = get_addr(s, channel) libc.connect(s.fileno(), addr, len(addr)...
Send raw frame to a BCM socket and handle errors.
def send_bcm(bcm_socket, data): """ Send raw frame to a BCM socket and handle errors. """ try: return bcm_socket.send(data) except OSError as e: base = "Couldn't send CAN BCM frame. OS Error {}: {}\n".format(e.errno, e.strerror) if e.errno == errno.EINVAL: raise ...
Creates a raw CAN socket. The socket will be returned unbound to any interface.
def create_socket(): """Creates a raw CAN socket. The socket will be returned unbound to any interface. """ sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW) log.info('Created a socket') return sock
Binds the given socket to the given interface. :param socket.socket sock: The socket to be bound :raises OSError: If the specified interface isn't found.
def bind_socket(sock, channel='can0'): """ Binds the given socket to the given interface. :param socket.socket sock: The socket to be bound :raises OSError: If the specified interface isn't found. """ log.debug('Binding socket to channel=%s', channel) if HAS_NATIVE_SUPPORT: ...
Captures a message from given socket. :param socket.socket sock: The socket to read a message from. :param bool get_channel: Find out which channel the message comes from. :return: The received message, or None on failure.
def capture_message(sock, get_channel=False): """ Captures a message from given socket. :param socket.socket sock: The socket to read a message from. :param bool get_channel: Find out which channel the message comes from. :return: The received message, or None on failure. """ ...
Update the contents of this periodically sent message. Note the Message must have the same :attr:`~can.Message.arbitration_id` like the first message.
def modify_data(self, message): """Update the contents of this periodically sent message. Note the Message must have the same :attr:`~can.Message.arbitration_id` like the first message. """ assert message.arbitration_id == self.can_id, "You cannot modify the can identifier" ...
Send a TX_DELETE message to cancel this task. This will delete the entry for the transmission of the CAN-message with the specified can_id CAN identifier. The message length for the command TX_DELETE is {[bcm_msg_head]} (only the header).
def stop(self): """Send a TX_DELETE message to cancel this task. This will delete the entry for the transmission of the CAN-message with the specified can_id CAN identifier. The message length for the command TX_DELETE is {[bcm_msg_head]} (only the header). """ log.debug...
Stops all active periodic tasks and closes the socket.
def shutdown(self): """Stops all active periodic tasks and closes the socket.""" self.stop_all_periodic_tasks() for channel in self._bcm_sockets: log.debug("Closing bcm socket for channel {}".format(channel)) bcm_socket = self._bcm_sockets[channel] bcm_socket....
Transmit a message to the CAN bus. :param can.Message msg: A message object. :param float timeout: Wait up to this many seconds for the transmit queue to be ready. If not given, the call may fail immediately. :raises can.CanError: if the message could not be...
def send(self, msg, timeout=None): """Transmit a message to the CAN bus. :param can.Message msg: A message object. :param float timeout: Wait up to this many seconds for the transmit queue to be ready. If not given, the call may fail immediately. :raises can.Can...
Start sending a message at a given period on this bus. The kernel's broadcast manager will be used. :param can.Message msg: Message to transmit :param float period: Period in seconds between each message :param float duration: The duration to keep se...
def _send_periodic_internal(self, msg, period, duration=None): """Start sending a message at a given period on this bus. The kernel's broadcast manager will be used. :param can.Message msg: Message to transmit :param float period: Period in seconds between each ...
Finds a list of USB devices where the serial number (partially) matches the given string. :param str serial_matcher (optional): only device IDs starting with this string are returned :rtype: List[str]
def find_serial_devices(serial_matcher="ED"): """ Finds a list of USB devices where the serial number (partially) matches the given string. :param str serial_matcher (optional): only device IDs starting with this string are returned :rtype: List[str] """ objWMIService = win32com.client...
Returns the names of all open can/vcan interfaces using the ``ip link list`` command. If the lookup fails, an error is logged to the console and an empty list is returned. :rtype: an iterable of :class:`str`
def find_available_interfaces(): """Returns the names of all open can/vcan interfaces using the ``ip link list`` command. If the lookup fails, an error is logged to the console and an empty list is returned. :rtype: an iterable of :class:`str` """ try: # it might be good to add "type v...
Converts a given error code (errno) to a useful and human readable string. :param int code: a possibly invalid/unknown error code :rtype: str :returns: a string explaining and containing the given error code, or a string explaining that the errorcode is unknown if that is the case
def error_code_to_str(code): """ Converts a given error code (errno) to a useful and human readable string. :param int code: a possibly invalid/unknown error code :rtype: str :returns: a string explaining and containing the given error code, or a string explaining that the errorcode i...
Spam the bus with messages including the data id. :param int id: the id of the thread/process
def producer(id, message_count=16): """Spam the bus with messages including the data id. :param int id: the id of the thread/process """ with can.Bus(bustype='socketcan', channel='vcan0') as bus: for i in range(message_count): msg = can.Message(arbitration_id=0x0cf02200+id, data=[i...
Append a message to the buffer. :raises: BufferError if the reader has already been stopped
def on_message_received(self, msg): """Append a message to the buffer. :raises: BufferError if the reader has already been stopped """ if self.is_stopped: raise RuntimeError("reader has already been stopped") else: self.buffer.put(msg)
Attempts to retrieve the latest message received by the instance. If no message is available it blocks for given timeout or until a message is received, or else returns None (whichever is shorter). This method does not block after :meth:`can.BufferedReader.stop` has been called. :param ...
def get_message(self, timeout=0.5): """ Attempts to retrieve the latest message received by the instance. If no message is available it blocks for given timeout or until a message is received, or else returns None (whichever is shorter). This method does not block after :meth:`ca...
Gets the text using the GetErrorText API function. If the function call succeeds, the translated error is returned. If it fails, a text describing the current error is returned. Multiple errors may be present in which case their individual messages are included in the return string, one ...
def _get_formatted_error(self, error): """ Gets the text using the GetErrorText API function. If the function call succeeds, the translated error is returned. If it fails, a text describing the current error is returned. Multiple errors may be present in which case their individu...
Command the PCAN driver to reset the bus after an error.
def reset(self): """ Command the PCAN driver to reset the bus after an error. """ status = self.m_objPCANBasic.Reset(self.m_PcanHandle) return status == PCAN_ERROR_OK
Turn on or off flashing of the device's LED for physical identification purposes.
def flash(self, flash): """ Turn on or off flashing of the device's LED for physical identification purposes. """ self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_CHANNEL_IDENTIFYING, bool(flash))
Convert status code to descriptive string.
def get_error_message(status_code): """Convert status code to descriptive string.""" errmsg = ctypes.create_string_buffer(1024) nican.ncStatusToString(status_code, len(errmsg), errmsg) return errmsg.value.decode("ascii")
Read a message from a NI-CAN bus. :param float timeout: Max time to wait in seconds or None if infinite :raises can.interfaces.nican.NicanError: If reception fails
def _recv_internal(self, timeout): """ Read a message from a NI-CAN bus. :param float timeout: Max time to wait in seconds or None if infinite :raises can.interfaces.nican.NicanError: If reception fails """ if timeout is None: timeout...
Send a message to NI-CAN. :param can.Message msg: Message to send :raises can.interfaces.nican.NicanError: If writing to transmit buffer fails. It does not wait for message to be ACKed currently.
def send(self, msg, timeout=None): """ Send a message to NI-CAN. :param can.Message msg: Message to send :raises can.interfaces.nican.NicanError: If writing to transmit buffer fails. It does not wait for message to be ACKed currently. """ ...
Unsupported. See note on :class:`~can.interfaces.nican.NicanBus`.
def set_filters(self, can_filers=None): """Unsupported. See note on :class:`~can.interfaces.nican.NicanBus`. """ if self.__set_filters_has_been_called: logger.warn("using filters is not supported like this, see note on NicanBus") else: # allow the constructor to c...
Send a :class:`~can.Message` every `period` seconds on the given bus. :param can.BusABC bus: A CAN bus which supports sending. :param can.Message message: Message to send periodically. :param float period: The minimum time between sending messages. :return: A started task instance
def send_periodic(bus, message, period, *args, **kwargs): """ Send a :class:`~can.Message` every `period` seconds on the given bus. :param can.BusABC bus: A CAN bus which supports sending. :param can.Message message: Message to send periodically. :param float period: The minimum time between sendin...
Read a message from kvaser device and return whether filtering has taken place.
def _recv_internal(self, timeout=None): """ Read a message from kvaser device and return whether filtering has taken place. """ arb_id = ctypes.c_long(0) data = ctypes.create_string_buffer(64) dlc = ctypes.c_uint(0) flags = ctypes.c_uint(0) timestamp = cty...
Turn on or off flashing of the device's LED for physical identification purposes.
def flash(self, flash=True): """ Turn on or off flashing of the device's LED for physical identification purposes. """ if flash: action = canstat.kvLED_ACTION_ALL_LEDS_ON else: action = canstat.kvLED_ACTION_ALL_LEDS_OFF try: kv...
Retrieves the bus statistics. Use like so: >>> stats = bus.get_stats() >>> print(stats) std_data: 0, std_remote: 0, ext_data: 0, ext_remote: 0, err_frame: 0, bus_load: 0.0%, overruns: 0 :returns: bus statistics. :rtype: can.interfaces.kvaser.structures.BusStatistics
def get_stats(self): """Retrieves the bus statistics. Use like so: >>> stats = bus.get_stats() >>> print(stats) std_data: 0, std_remote: 0, ext_data: 0, ext_remote: 0, err_frame: 0, bus_load: 0.0%, overruns: 0 :returns: bus statistics. :rtype: can.interfaces.kv...
Format a VCI error and attach failed function, decoded HRESULT and arguments :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :pa...
def __vciFormatErrorExtended(library_instance, function, HRESULT, arguments): """ Format a VCI error and attach failed function, decoded HRESULT and arguments :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function ...
Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :return: ...
def __vciFormatError(library_instance, function, HRESULT): """ Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT:...
Check the result of a vcinpl function call and raise appropriate exception in case of an error. Used as errcheck function when mapping C functions with ctypes. :param result: Function call numeric result :param callable function: Called function :param arguments: ...
def __check_status(result, function, arguments): """ Check the result of a vcinpl function call and raise appropriate exception in case of an error. Used as errcheck function when mapping C functions with ctypes. :param result: Function call numeric result :param callable fun...
Read a message from IXXAT device.
def _recv_internal(self, timeout): """ Read a message from IXXAT device. """ # TODO: handling CAN error messages? data_received = False if timeout == 0: # Peek without waiting try: _canlib.canChannelPeekMessage(self._channel_handle, ctypes.byref(...
Send a message using built-in cyclic transmit list functionality.
def _send_periodic_internal(self, msg, period, duration=None): """Send a message using built-in cyclic transmit list functionality.""" if self._scheduler is None: self._scheduler = HANDLE() _canlib.canSchedulerOpen(self._device_handle, self.channel, ...
Unsupported. See note on :class:`~can.interfaces.ixxat.IXXATBus`.
def set_filters(self, can_filers=None): """Unsupported. See note on :class:`~can.interfaces.ixxat.IXXATBus`. """ if self.__set_filters_has_been_called: log.warn("using filters is not supported like this, see note on IXXATBus") else: # allow the constructor to call...
Start transmitting message (add to list if needed).
def start(self): """Start transmitting message (add to list if needed).""" if self._index is None: self._index = ctypes.c_uint32() _canlib.canSchedulerAddMessage(self._scheduler, self._msg, self...
Stop transmitting message (remove from list).
def stop(self): """Stop transmitting message (remove from list).""" # Remove it completely instead of just stopping it to avoid filling up # the list with permanently stopped messages _canlib.canSchedulerRemMessage(self._scheduler, self._index) self._index = None
Add an arbitrary message to the log file as a global marker. :param str text: The group name of the marker. :param float timestamp: Absolute timestamp in Unix timestamp format. If not given, the marker will be placed along the last message.
def log_event(self, text, timestamp=None): """Add an arbitrary message to the log file as a global marker. :param str text: The group name of the marker. :param float timestamp: Absolute timestamp in Unix timestamp format. If not given, the marker will be pla...
Compresses and writes data in the cache to file.
def _flush(self): """Compresses and writes data in the cache to file.""" if self.file.closed: return cache = b"".join(self.cache) if not cache: # Nothing to write return uncompressed_data = cache[:self.MAX_CACHE_SIZE] # Save data that c...
Stops logging and closes the file.
def stop(self): """Stops logging and closes the file.""" self._flush() filesize = self.file.tell() super(BLFWriter, self).stop() # Write header in the beginning of the file header = [b"LOGG", FILE_HEADER_SIZE, APPLICATION_ID, 0, 0, 0, 2, 6, 8, 1] ...
Initializes a PCAN Channel Parameters: Channel : A TPCANHandle representing a PCAN Channel Btr0Btr1 : The speed for the communication (BTR0BTR1 code) HwType : NON PLUG&PLAY: The type of hardware and operation mode IOPort : NON PLUG&PLAY: The I/O address for the para...
def Initialize( self, Channel, Btr0Btr1, HwType = TPCANType(0), IOPort = c_uint(0), Interrupt = c_ushort(0)): """ Initializes a PCAN Channel Parameters: Channel : A TPCANHandle representing a PCAN Channel Btr0Btr1 : The spe...