text
stringlengths
81
112k
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 ...
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 geo...
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_coordinat...
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...
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 ...
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...
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...
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, ...
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...
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_s...
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): ...
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...
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):...
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 ...
Calculate RMS displacement between two structures Args: struct1 (Structure): 1st structure struct2 (Structure): 2nd structure Returns: rms displacement normalized by (Vol / nsites) ** (1/3) and maximum distance between paired sites. If no matching ...
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 s...
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): re...
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) ...
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...
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=F...
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...
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...
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):...
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...
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 us...
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,...
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...
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...
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. ...
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...
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 ...
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 ...
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...
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: ...
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, step...
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...
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...
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...
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 ...
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...
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...
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...
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) ...
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...
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...
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...
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...
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(...
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...
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, flag...
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 (SqliteReade...
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 ...
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._...
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: i...
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...
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_*...
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...
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 c...
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...
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 =...
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) ...
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: Th...
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...
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 ...
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:`~...
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_soc...
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...
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...
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 seri...
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 ...
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_...
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: ...
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: ...
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 ...
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 ...
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, b...
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 ti...
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...
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 o...
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(bu...
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) ...
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 ...
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 d...
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...
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: ...
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: ...
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(...
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.canSchedulerOpe...
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 I...
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....
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._ind...
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,...
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 = cach...
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, APPLICA...
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...
Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_* values. * parameter and values must be separated by '=' * Couples of Pa...
Uninitializes one or all PCAN Channels initialized by CAN_Initialize Remarks: Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels Parameters: Channel : A TPCANHandle representing a PCAN Channel Returns: A TPCANStatus error code de...