text stringlengths 81 112k |
|---|
Find match for a file by slicing away its directory elements
from the front and replacing them with pathdir. Assume that the
end of curpath is right and but that the beginning may contain
some garbage (or it may be short)
Overlaps are allowed:
e.g /tmp/fdjsklf/real/path/elements, /al... |
Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name.
def lookupmodule(self, filename):
"""Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (p... |
Sets a condition for set_trace statements that have the
specified marker. A condition can be either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which case the break will
... |
Start debugging from here.
def _set_trace(self, skip=0):
"""Start debugging from here."""
frame = sys._getframe().f_back
# go up the specified number of frames
for i in range(skip):
frame = frame.f_back
self.reset()
while frame:
frame.f_trace = se... |
This method is called when there is the remote possibility
that we ever need to stop in this function.
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self.stop_here(frame):
... |
This function is called when a return trap is set here.
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
pdb.Pdb.user_return(self, frame, return_value) |
This function is called if an exception occurs,
but only if we are to stop at or just below this level.
def user_exception(self, frame, exc_info):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
pdb.Pdb.user_exception(self, f... |
Convert a chain of traceback or frame objects into a list of frames.
def stackToList(stack):
"""
Convert a chain of traceback or frame objects into a list of frames.
"""
if isinstance(stack, types.TracebackType):
while stack.tb_next:
stack = stack.tb_next
stack = stack.tb_fr... |
Read in and parse IAC commands as passed by telnetlib.
SB/SE commands are stored in sbdataq, and passed in w/ a command
of SE.
def process_IAC(self, sock, cmd, option):
"""
Read in and parse IAC commands as passed by telnetlib.
SB/SE commands are stored in sbda... |
Performs endless processing of socket input/output, passing
cooked information onto the local process.
def handle(self):
"""
Performs endless processing of socket input/output, passing
cooked information onto the local process.
"""
while True:
toR... |
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler.
def handle(self):
"""
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via t... |
Handle one request - serve current process to one connection.
Use close_request() to disconnect this process.
def handle_request(self):
"""
Handle one request - serve current process to one connection.
Use close_request() to disconnect this process.
"""
try... |
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
def _serve_process(self, slaveFd, serverPid):
"""
Serves a process by connecting its outputs/inputs to the pty
... |
Ask a user for a int input between two values
args:
message (str): Prompt for user
low (int): Low value, user entered value must be > this value to be accepted
high (int): High value, user entered value must be < this value to be accepted
show_range (boolean, Default True): Print hi... |
Ask a user for a float input between two values
args:
message (str): Prompt for user
low (float): Low value, user entered value must be > this value to be accepted
high (float): High value, user entered value must be < this value to be accepted
returns:
float_in (int): Input fl... |
Ask a user for a boolean input
args:
message (str): Prompt for user
returns:
bool_in (boolean): Input boolean
def bool_input(message):
'''
Ask a user for a boolean input
args:
message (str): Prompt for user
returns:
bool_in (boolean): Input boolean
'''
... |
Main entry point for transfer command line tool.
This essentially will marshall the user to the functions they need.
def main(args = None):
'''
Main entry point for transfer command line tool.
This essentially will marshall the user to the functions they need.
'''
parser = argparse.ArgumentP... |
Configure the transfer environment and store
def configure():
'''
Configure the transfer environment and store
'''
completer = Completer()
readline.set_completer_delims('\t')
readline.parse_and_bind('tab: complete')
readline.set_completer(completer.path_completer)
home = os.path.expand... |
Configure the transfer environment and store
def configure_server():
'''
Configure the transfer environment and store
'''
home = os.path.expanduser('~')
if os.path.isfile(os.path.join(home, '.transfer', 'config.yaml')):
with open(os.path.join(home, '.transfer', 'config.yaml'), 'r') as fp:
... |
Select a project from configuration to run transfer on
args:
user_provided_project (str): Project name that should match a project in the config
returns:
project (dict): Configuration settings for a user selected project
def select_project(user_provided_project):
'''
Select a project ... |
Store configuration
args:
config (list[dict]): configurations for each project
def store_config(config, suffix = None):
'''
Store configuration
args:
config (list[dict]): configurations for each project
'''
home = os.path.expanduser('~')
if suffix is not None:
conf... |
Update project in configuration
args:
updated_project (dict): Updated project configuration values
def update_config(updated_project):
'''
Update project in configuration
args:
updated_project (dict): Updated project configuration values
'''
home = os.path.expanduser('~')
... |
An auxiliary function to construct a dictionary of Criteria
def atom_criteria(*params):
"""An auxiliary function to construct a dictionary of Criteria"""
result = {}
for index, param in enumerate(params):
if param is None:
continue
elif isinstance(param, int):
result... |
the size must be the same as the length of the array numbers and all elements must be strings
def _check_symbols(self, symbols):
"""the size must be the same as the length of the array numbers and all elements must be strings"""
if len(symbols) != self.size:
raise TypeError("The number of s... |
Construct a MolecularGraph object based on interatomic distances
All short distances are computed with the binning module and compared
with a database of bond lengths. Based on this comparison, bonded
atoms are detected.
Before marking a pair of atoms A and B as bonded, it ... |
Construct a molecular graph from the blob representation
def from_blob(cls, s):
"""Construct a molecular graph from the blob representation"""
atom_str, edge_str = s.split()
numbers = np.array([int(s) for s in atom_str.split(",")])
edges = []
orders = []
for s in edge_st... |
A compact text representation of the graph
def blob(self):
"""A compact text representation of the graph"""
atom_str = ",".join(str(number) for number in self.numbers)
edge_str = ",".join("%i_%i_%i" % (i, j, o) for (i, j), o in zip(self.edges, self.orders))
return "%s %s" % (atom_str, e... |
Return a string based on the atom number
def get_vertex_string(self, i):
"""Return a string based on the atom number"""
number = self.numbers[i]
if number == 0:
return Graph.get_vertex_string(self, i)
else:
# pad with zeros to make sure that string sort is identi... |
Return a string based on the bond order
def get_edge_string(self, i):
"""Return a string based on the bond order"""
order = self.orders[i]
if order == 0:
return Graph.get_edge_string(self, i)
else:
# pad with zeros to make sure that string sort is identical to nu... |
Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information.
def get_subgraph(self, subvertices, normalize=False):
"""Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information.
"""
... |
Returns a molecular graph where hydrogens are added explicitely
When the bond order is unknown, it assumes bond order one. If the
graph has an attribute formal_charges, this routine will take it
into account when counting the number of hydrogens to be added. The
returned gr... |
Check if the (onset for a) match can be a valid (part of a) ring
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid (part of a) ring"""
if not CustomPattern.check_next_match(self, match, new_relations, subject_graph, one_match)... |
Check the completeness of the ring match
def complete(self, match, subject_graph):
"""Check the completeness of the ring match"""
if not CustomPattern.complete(self, match, subject_graph):
return False
if self.strong:
# If the ring is not strong, return False
... |
Return the kind (type) of the attribute
def get_kind(self, value):
"""Return the kind (type) of the attribute"""
if isinstance(value, float):
return 'f'
elif isinstance(value, int):
return 'i'
else:
raise ValueError("Only integer or floating point val... |
Write the attribute to a file-like object
def dump(self, f, name):
"""Write the attribute to a file-like object"""
# print the header line
value = self.get()
kind = self.get_kind(value)
print("% 40s kind=%s value=%s" % (name, kind, value), file=f) |
Return the value of the attribute
def get(self, copy=False):
"""Return the value of the attribute"""
array = getattr(self.owner, self.name)
if copy:
return array.copy()
else:
return array |
Write the attribute to a file-like object
def dump(self, f, name):
"""Write the attribute to a file-like object"""
array = self.get()
# print the header line
print("% 40s kind=%s shape=(%s)" % (
name,
array.dtype.kind,
",".join([str(int(size_axis)) ... |
Load the array data from a file-like object
def load(self, f, skip):
"""Load the array data from a file-like object"""
array = self.get()
counter = 0
counter_limit = array.size
convert = array.dtype.type
while counter < counter_limit:
line = f.readline()
... |
Register a new attribute to take care of with dump and load
Arguments:
| ``name`` -- the name to be used in the dump file
| ``AttrCls`` -- an attr class describing the attribute
def _register(self, name, AttrCls):
"""Register a new attribute to take care of with dump and... |
Return a dictionary object with the registered fields and their values
Optional rgument:
| ``subset`` -- a list of names to restrict the number of fields
in the result
def get(self, subset=None):
"""Return a dictionary object with the registered fields an... |
Assign the registered fields based on a dictionary
Argument:
| ``new_fields`` -- the dictionary with the data to be assigned to
the attributes
Optional argument:
| ``subset`` -- a list of names to restrict the fields that are
... |
Dump the registered fields to a file
Argument:
| ``filename`` -- the file to write to
def dump(self, filename):
"""Dump the registered fields to a file
Argument:
| ``filename`` -- the file to write to
"""
with open(filename, "w") as f:
... |
Load data into the registered fields
Argument:
| ``filename`` -- the filename to read from
Optional argument:
| ``subset`` -- a list of field names that are read from the file.
If not given, all data is read from the file.
def load(self,... |
Load the bond data from the given file
It's assumed that the uncommented lines in the data file have the
following format:
symbol1 symbol2 number1 number2 bond_length_single_a bond_length_double_a bond_length_triple_a bond_length_single_b bond_length_double_b bond_length_triple_b ..."
... |
Completes the bond length database with approximations based on VDW radii
def _approximate_unkown_bond_lengths(self):
"""Completes the bond length database with approximations based on VDW radii"""
dataset = self.lengths[BOND_SINGLE]
for n1 in periodic.iter_numbers():
for n2 in peri... |
Return the estimated bond type
Arguments:
| ``n1`` -- the atom number of the first atom in the bond
| ``n2`` -- the atom number of the second atom the bond
| ``distance`` -- the distance between the two atoms
This method checks whether for the given pair... |
Return the length of a bond between n1 and n2 of type bond_type
Arguments:
| ``n1`` -- the atom number of the first atom in the bond
| ``n2`` -- the atom number of the second atom the bond
Optional argument:
| ``bond_type`` -- the type of bond [default=B... |
Construct a 3D unit cell with the given parameters
The a vector is always parallel with the x-axis and they point in the
same direction. The b vector is always in the xy plane and points
towards the positive y-direction. The c vector points towards the
positive z-direction.
... |
The volume of the unit cell
The actual definition of the volume depends on the number of active
directions:
* num_active == 0 -- always -1
* num_active == 1 -- length of the cell vector
* num_active == 2 -- surface of the parallelogram
* num_acti... |
The indexes of the active and the inactive cell vectors
def active_inactive(self):
"""The indexes of the active and the inactive cell vectors"""
active_indices = []
inactive_indices = []
for index, active in enumerate(self.active):
if active:
active_indices.a... |
The reciprocal of the unit cell
In case of a three-dimensional periodic system, this is trivially the
transpose of the inverse of the cell matrix. This means that each
column of the matrix corresponds to a reciprocal cell vector. In case
of lower-dimensional periodicity, the... |
The cell parameters (lengths and angles)
def parameters(self):
"""The cell parameters (lengths and angles)"""
length_a = np.linalg.norm(self.matrix[:, 0])
length_b = np.linalg.norm(self.matrix[:, 1])
length_c = np.linalg.norm(self.matrix[:, 2])
alpha = np.arccos(np.dot(self.matr... |
An equivalent unit cell with the active cell vectors coming first
def ordered(self):
"""An equivalent unit cell with the active cell vectors coming first"""
active, inactive = self.active_inactive
order = active + inactive
return UnitCell(self.matrix[:,order], self.active[order]) |
Computes the rotation matrix that aligns the unit cell with the
Cartesian axes, starting with cell vector a.
* a parallel to x
* b in xy-plane with b_y positive
* c with c_z positive
def alignment_a(self):
"""Computes the rotation matrix that aligns the unit cell wi... |
Computes the distances between neighboring crystal planes
def spacings(self):
"""Computes the distances between neighboring crystal planes"""
result_invsq = (self.reciprocal**2).sum(axis=0)
result = np.zeros(3, float)
for i in range(3):
if result_invsq[i] > 0:
... |
Returns a new unit cell with an additional cell vector
def add_cell_vector(self, vector):
"""Returns a new unit cell with an additional cell vector"""
act = self.active_inactive[0]
if len(act) == 3:
raise ValueError("The unit cell already has three active cell vectors.")
mat... |
Return ranges of indexes of the interacting neighboring unit cells
Interacting neighboring unit cells have at least one point in their
box volume that has a distance smaller or equal than radius to at
least one point in the central cell. This concept is of importance
when co... |
Return the indexes of the interacting neighboring unit cells
Interacting neighboring unit cells have at least one point in their
box volume that has a distance smaller or equal than radius to at
least one point in the central cell. This concept is of importance
when computin... |
Construct a molecular geometry based on a molecular graph.
This routine does not require initial coordinates and will give a very
rough picture of the initial geometry. Do not expect all details to be
in perfect condition. A subsequent optimization with a more accurate
level of theory is at... |
Fine tune a molecular geometry, starting from a (very) poor guess of
the initial geometry.
Do not expect all details to be in perfect condition. A subsequent
optimization with a more accurate level of theory is at least advisable.
Arguments:
| ``graph`` -- The molecular graph of ... |
Update the coordinates (and derived quantities)
Argument:
coordinates -- new Cartesian coordinates of the system
def update_coordinates(self, coordinates=None):
"""Update the coordinates (and derived quantities)
Argument:
coordinates -- new Cartesian coordi... |
Compute the energy of the system
def energy(self):
"""Compute the energy of the system"""
result = 0.0
for index1 in range(self.numc):
for index2 in range(index1):
if self.scaling[index1, index2] > 0:
for se, ve in self.yield_pair_energies(index1,... |
Compute the gradient of the energy for one atom
def gradient_component(self, index1):
"""Compute the gradient of the energy for one atom"""
result = np.zeros(3, float)
for index2 in range(self.numc):
if self.scaling[index1, index2] > 0:
for (se, ve), (sg, vg) in zip(... |
Compute the gradient of the energy for all atoms
def gradient(self):
"""Compute the gradient of the energy for all atoms"""
result = np.zeros((self.numc, 3), float)
for index1 in range(self.numc):
result[index1] = self.gradient_component(index1)
return result |
Compute the hessian of the energy for one atom pair
def hessian_component(self, index1, index2):
"""Compute the hessian of the energy for one atom pair"""
result = np.zeros((3, 3), float)
if index1 == index2:
for index3 in range(self.numc):
if self.scaling[index1, in... |
Compute the hessian of the energy
def hessian(self):
"""Compute the hessian of the energy"""
result = np.zeros((self.numc, 3, self.numc, 3), float)
for index1 in range(self.numc):
for index2 in range(self.numc):
result[index1, :, index2, :] = self.hessian_component(i... |
Yields pairs ((s(r_ij), v(bar{r}_ij))
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield c1*c... |
Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
d_2 = 1/self.distances[index1, index2]**2
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
... |
Yields pairs ((s''(r_ij), grad_i (x) grad_i v(bar{r}_ij))
def yield_pair_hessians(self, index1, index2):
"""Yields pairs ((s''(r_ij), grad_i (x) grad_i v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
d_3 = d_1**3
if self.charges is not None:
c1 = self.charges[index1]... |
Compute the electrostatic potential at each atom due to other atoms
def esp(self):
"""Compute the electrostatic potential at each atom due to other atoms"""
result = np.zeros(self.numc, float)
for index1 in range(self.numc):
result[index1] = self.esp_component(index1)
return... |
Compute the electrostatic potential at each atom due to other atoms
def efield(self):
"""Compute the electrostatic potential at each atom due to other atoms"""
result = np.zeros((self.numc,3), float)
for index1 in range(self.numc):
result[index1] = self.efield_component(index1)
... |
Yields pairs ((s(r_ij), v(bar{r}_ij))
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
strength = self.strengths[index1, index2]
distance = self.distances[index1, index2]
yield strength*distance**(-6), 1 |
Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
strength = self.strengths[index1, index2]
distance = self.distances[index1, index2]
yield -6*strength*distance**(-7), np.zeros(3) |
Yields pairs ((s(r_ij), v(bar{r}_ij))
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
A = self.As[index1, index2]
B = self.Bs[index1, index2]
distance = self.distances[index1, index2]
yield A*np.exp(-B*distance), 1 |
Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
A = self.As[index1, index2]
B = self.Bs[index1, index2]
distance = self.distances[index1, index2]
yield -B*A*np.exp(-B*distance), np.... |
Load the molecules from a CML file
Argument:
| ``cml_filename`` -- The filename of a CML file.
Returns a list of molecule objects with optional molecular graph
attribute and extra attributes.
def load_cml(cml_filename):
"""Load the molecules from a CML file
Argument:
... |
Dump a single molecule to a CML file
Arguments:
| ``f`` -- a file-like object
| ``molecule`` -- a Molecule instance
def _dump_cml_molecule(f, molecule):
"""Dump a single molecule to a CML file
Arguments:
| ``f`` -- a file-like object
| ``molecule`` -- a Molec... |
Write a list of molecules to a CML file
Arguments:
| ``f`` -- a filename of a CML file or a file-like object
| ``molecules`` -- a list of molecule objects.
def dump_cml(f, molecules):
"""Write a list of molecules to a CML file
Arguments:
| ``f`` -- a filename of a CML ... |
Read the extra properties, taking into account an exclude list
def _get_extra(self, attrs, exclude):
"""Read the extra properties, taking into account an exclude list"""
result = {}
for key in attrs.getNames():
if key not in exclude:
result[str(key)] = str(attrs[key]... |
Read all the requested fields
Arguments:
| ``filename`` -- the filename of the FCHK file
| ``field_labels`` -- when given, only these fields are read
def _read(self, filename, field_labels=None):
"""Read all the requested fields
Arguments:
| ``fil... |
Convert a few elementary fields into a molecule object
def _analyze(self):
"""Convert a few elementary fields into a molecule object"""
if ("Atomic numbers" in self.fields) and ("Current cartesian coordinates" in self.fields):
self.molecule = Molecule(
self.fields["Atomic nu... |
Return the coordinates of the geometries at each point in the optimization
def get_optimization_coordinates(self):
"""Return the coordinates of the geometries at each point in the optimization"""
coor_array = self.fields.get("Opt point 1 Geometries")
if coor_array is None:
ret... |
Return a molecule object of the optimal geometry
def get_optimized_molecule(self):
"""Return a molecule object of the optimal geometry"""
opt_coor = self.get_optimization_coordinates()
if len(opt_coor) == 0:
return None
else:
return Molecule(
self... |
Return the energy gradients of all geometries during an optimization
def get_optimization_gradients(self):
"""Return the energy gradients of all geometries during an optimization"""
grad_array = self.fields.get("Opt point 1 Gradient at each geome")
if grad_array is None:
retur... |
Return the hessian
def get_hessian(self):
"""Return the hessian"""
force_const = self.fields.get("Cartesian Force Constants")
if force_const is None:
return None
N = len(self.molecule.numbers)
result = np.zeros((3*N, 3*N), float)
counter = 0
for row i... |
Return a copy with (a few) changed attributes
The keyword arguments are the attributes to be replaced by new
values. All other attributes are copied (or referenced) from the
original object. This only works if the constructor takes all
(read-only) attributes as arguments.
d... |
Internal routine that reads all data from the punch file.
def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), Mas... |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
self.used = True
data["title"] = f.readline().strip()
data["symmetry"] = f.readline().split()[0]
if data["symmetry"] != "C1":
raise NotImplementedError("Only C1 symmetry is... |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
f.readline()
f.readline()
N = len(data["symbols"])
# if the data are already read before, just overwrite them
numbers = data.get("numbers")
if numbers is None:
... |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
data["energy"] = float(f.readline().split()[1])
N = len(data["symbols"])
# if the data are already read before, just overwrite them
gradient = data.get("gradient")
if gradient ... |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
line = f.readline()
assert(line == " $HESS\n")
while line != " $END\n":
line = f.readline() |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
assert("hessian" not in data)
f.readline()
N = len(data["symbols"])
hessian = np.zeros((3*N, 3*N), float)
tmp = hessian.ravel()
counter = 0
while True:
... |
See :meth:`PunchParser.read`
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
N = len(data["symbols"])
masses = np.zeros(N, float)
counter = 0
while counter < N:
words = f.readline().split()
for word in words:
masses[count... |
Create a simple ForceField object for hydrocarbons based on the graph.
def setup_hydrocarbon_ff(graph):
"""Create a simple ForceField object for hydrocarbons based on the graph."""
# A) Define parameters.
# the bond parameters:
bond_params = {
(6, 1): 310*kcalmol/angstrom**2,
(6, 6): 22... |
Add the contributions of this energy term to the Hessian
Arguments:
| ``coordinates`` -- A numpy array with 3N Cartesian coordinates.
| ``hessian`` -- A matrix for the full Hessian to which this energy
term has to add its contribution.
def add_to_hessian... |
Compute the force-field Hessian for the given coordinates.
Argument:
| ``coordinates`` -- A numpy array with the Cartesian atom
coordinates, with shape (N,3).
Returns:
| ``hessian`` -- A numpy array with the Hessian, with shape (3*N,
... |
Compute the rotational symmetry number
Arguments:
| ``molecule`` -- The molecule
| ``graph`` -- The corresponding bond graph
Optional argument:
| ``threshold`` -- only when a rotation results in an rmsd below the
given threshold, the rotation is... |
Return the quaternion product of the two arguments
def quaternion_product(quat1, quat2):
"""Return the quaternion product of the two arguments"""
return np.array([
quat1[0]*quat2[0] - np.dot(quat1[1:], quat2[1:]),
quat1[0]*quat2[1] + quat2[0]*quat1[1] + quat1[2]*quat2[3] - quat1[3]*quat2[2],
... |
Apply the rotation represented by the quaternion to the vector
Warning: This only works correctly for normalized quaternions.
def quaternion_rotation(quat, vector):
"""Apply the rotation represented by the quaternion to the vector
Warning: This only works correctly for normalized quaternions.
"... |
Compute the quaternion representing the rotation given by the matrix
def rotation_matrix_to_quaternion(rotation_matrix):
"""Compute the quaternion representing the rotation given by the matrix"""
invert = (np.linalg.det(rotation_matrix) < 0)
if invert:
factor = -1
else:
factor = 1
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.