MBsysPy.mbsyspy.mbs_results module¶
Module to handle results from MBS analysis.
Summary¶
Define the class MbsResults dedicated to load the MbsBuffer C structure. Such structures contains the result of the multibody analysis, except for modal analysis.
The module internal class ‘_buffer_ids’ must be updated to be coherent with the enumeration in the file “mbs_buffer.h”. Currently only the value of ‘BUFFER_Q’ is used.
-
class
MBsysPy.mbsyspy.mbs_results.
MbsNpArray
(array, header=None)¶ Bases:
numpy.ndarray
Overloaded Numpy.ndarray, allowing to access columns by name.
All methods and attributes of Numpy.ndarray are availables. Only additional methods and attributes are documented.
- Variables
header (list of str) – The name of each column of the array.
-
get
(names)¶ Return an array containing a copy of the columns in the list. The columns are identified with name or index value.
-
get_index
(name)¶ Return the index of the column with matching name.
Examples
>>> a = MbsNpArray(np.arange(1, 10).reshape((3,3)), ['fist', 'second', 'mult of 3']) >>> print(a) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> a.get(['mult of 3']) array([3, 6, 9])
Retrieve a single column as a 1 dimensional numpy array.
>>> a.get(['mult of 3', 'first']) array([[3, 1], [6, 4], [9, 7]])
Retrieve two columns from their name, respecting the provided ordering.
>>> a.get([2, 'first']) array([[3, 1], [6, 4], [9, 7]])
Retrieve two columns from their name or index, respecting the provided ordering.
>>> a.shape (3, 3) >>> print(a.transpose()) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Numpy.ndarray properties and methods are available on the instance.
- Attributes
T
The transposed array.
base
Base object if memory is from some other object.
ctypes
An object to simplify the interaction of the array with the ctypes module.
data
Python buffer object pointing to the start of the array’s data.
dtype
Data-type of the array’s elements.
flags
Information about the memory layout of the array.
flat
A 1-D iterator over the array.
imag
The imaginary part of the array.
itemsize
Length of one array element in bytes.
nbytes
Total bytes consumed by the elements of the array.
ndim
Number of array dimensions.
real
The real part of the array.
shape
Tuple of array dimensions.
size
Number of elements in the array.
strides
Tuple of bytes to step in each dimension when traversing an array.
Methods
all
([axis, out, keepdims])Returns True if all elements evaluate to True.
any
([axis, out, keepdims])Returns True if any of the elements of a evaluate to True.
argmax
([axis, out])Return indices of the maximum values along the given axis.
argmin
([axis, out])Return indices of the minimum values along the given axis of a.
argpartition
(kth[, axis, kind, order])Returns the indices that would partition this array.
argsort
([axis, kind, order])Returns the indices that would sort this array.
astype
(dtype[, order, casting, subok, copy])Copy of the array, cast to a specified type.
byteswap
([inplace])Swap the bytes of the array elements
choose
(choices[, out, mode])Use an index array to construct a new array from a set of choices.
clip
([min, max, out])Return an array whose values are limited to
[min, max]
.compress
(condition[, axis, out])Return selected slices of this array along given axis.
conj
()Complex-conjugate all elements.
conjugate
()Return the complex conjugate, element-wise.
copy
([order])Return a copy of the array.
cumprod
([axis, dtype, out])Return the cumulative product of the elements along the given axis.
cumsum
([axis, dtype, out])Return the cumulative sum of the elements along the given axis.
diagonal
([offset, axis1, axis2])Return specified diagonals.
dot
(b[, out])Dot product of two arrays.
dump
(file)Dump a pickle of the array to the specified file.
dumps
()Returns the pickle of the array as a string.
fill
(value)Fill the array with a scalar value.
flatten
([order])Return a copy of the array collapsed into one dimension.
get
(self, names)Extract a copy of the specified columns as numpy array.
get_index
(self, name)Return the index of the column.
getfield
(dtype[, offset])Returns a field of the given array as a certain type.
item
(*args)Copy an element of an array to a standard Python scalar and return it.
itemset
(*args)Insert scalar into an array (scalar is cast to array’s dtype, if possible)
max
([axis, out, keepdims, initial, where])Return the maximum along a given axis.
mean
([axis, dtype, out, keepdims])Returns the average of the array elements along given axis.
min
([axis, out, keepdims, initial, where])Return the minimum along a given axis.
newbyteorder
([new_order])Return the array with the same data viewed with a different byte order.
nonzero
()Return the indices of the elements that are non-zero.
partition
(kth[, axis, kind, order])Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
prod
([axis, dtype, out, keepdims, initial, …])Return the product of the array elements over the given axis
ptp
([axis, out, keepdims])Peak to peak (maximum - minimum) value along a given axis.
put
(indices, values[, mode])Set
a.flat[n] = values[n]
for all n in indices.ravel
([order])Return a flattened array.
repeat
(repeats[, axis])Repeat elements of an array.
reshape
(shape[, order])Returns an array containing the same data with a new shape.
resize
(new_shape[, refcheck])Change shape and size of array in-place.
round
([decimals, out])Return a with each element rounded to the given number of decimals.
searchsorted
(v[, side, sorter])Find indices where elements of v should be inserted in a to maintain order.
setfield
(val, dtype[, offset])Put a value into a specified place in a field defined by a data-type.
setflags
([write, align, uic])Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
sort
([axis, kind, order])Sort an array in-place.
squeeze
([axis])Remove single-dimensional entries from the shape of a.
std
([axis, dtype, out, ddof, keepdims])Returns the standard deviation of the array elements along given axis.
sum
([axis, dtype, out, keepdims, initial, where])Return the sum of the array elements over the given axis.
swapaxes
(axis1, axis2)Return a view of the array with axis1 and axis2 interchanged.
take
(indices[, axis, out, mode])Return an array formed from the elements of a at the given indices.
tobytes
([order])Construct Python bytes containing the raw data bytes in the array.
tofile
(fid[, sep, format])Write array to a file as text or binary (default).
tolist
()Return the array as an
a.ndim
-levels deep nested list of Python scalars.tostring
([order])A compatibility alias for tobytes, with exactly the same behavior.
trace
([offset, axis1, axis2, dtype, out])Return the sum along diagonals of the array.
transpose
(*axes)Returns a view of the array with axes transposed.
var
([axis, dtype, out, ddof, keepdims])Returns the variance of the array elements, along given axis.
view
([dtype][, type])New view of array with the same data.
-
get
(self, names)¶ Extract a copy of the specified columns as numpy array.
The columns are specified by their name or index.
- Parameters
names (list) – List of the column name or index.
- Returns
An copy of the selected rows.
- Return type
numpy.ndarray
-
get_index
(self, name)¶ Return the index of the column.
- Parameters
name (str or int) – The column name or the column index (then it is returned as it).
- Raises
RuntimeError – No header defined.
ValueError – Invalid name instance or no column matching name.
- Returns
The index of the column.
- Return type
int
-
class
MBsysPy.mbsyspy.mbs_results.
MbsResult
(mbs=None, prj_path=None)¶ Bases:
object
Class containing results of multibody analysis (except for modal analysis).
Each attribute are accessible via the properties. This allows to raise a warning instead of an exception if trying to access an unloaded field.
The user-defined outputs (vector or floats) are stored in a dictionary winch is the attribute ‘outputs’.
The class is overloaded by equilibrium analysis to add it specific informations that are not given by the buffers and files.
- Variables
_q (numpy.ndarray) – Array containing the history of the generalized coordinates.
_qd (numpy.ndarray) – Array containing the history of the generalized velocities.
_qdd (numpy.ndarray) – Array containing the history of the generalized accelerations.
_Lambda (numpy.ndarray) – Array containing the history of the lagrange multipliers related to the constraints.
prj_path (str) – Path of the project folder. This is required if the results must be loaded from files instead of loading from the buffers.
_Fl (numpy.ndarray) – Array containing the history of the forces in each links.
outputs (dict) – Dict containing the names (as key) and the history (as value) of the user outputs. Each history is a numpy.ndarray with first column being the time.
_Qa (numpy.ndarray) – Array containing the history of the actuation force (or torque) in each articulations, the value for non-articulated joints is always 0. This field is only relevant for inverse dynamic.
_Qc (numpy.ndarray) – Array containing the history of the force introduced in driven joints to respect the user-specified trajectory (position, velocity, acceleration). The values for non-driven joints is always 0.
_Qq (numpy.ndarray) – Array containing the history of the joint forces.
_t (numpy.ndarray) – Array containing the time vector.
_ux (numpy.ndarray) – Array containing the history of the user variables.
_uxd (numpy.ndarray) – Array containing the history of the time derivative of the user variables.
_Z (numpy.ndarray) – Array containing the history of the lenght of each link.
_Zd (numpy.ndarray) – Array containing the history of the speed (spreading) of each link.
_x (numpy.ndarray) – Array containing the equil. module history of the equilibrium variables.
_F (numpy.ndarray) – Array containing the equil. module history of the residual force on each equilibrium variable.
_R (numpy.ndarray) – Array containing the equil. module history of residual force.
Notes
The module internal class ‘_buffer_ids’ must be updated to be coherent with the enumeration in the file “mbs_buffer.h”
- Parameters
prj_path (str, optional) – The path to the project directory. It can be omitted if mbs is provided. The default is None.
mbs (MBsysPy.MbsData, optional) – The multibody system related to the results to be loaded. Only the project path will be read from this instance. If it is not provided, prj_path must be provided. The default is None.
- Raises
ValueError : – Exception raided if both mbs and prj_path are None.
- Attributes
F
Array containing the history of the residual force on equilibrium variables (read only).
Fl
Array containing the history of the forces in each links (read-only).
Lambda
Array containing the history of the lagrange multipliers related to the constraints (read-only).
Qa
Array containing the history of the actuation force (or torque) in each articulations (read only).
Qc
Array containing the history of the force introduced in driven joints (read only).
Qq
Array containing the history of the user joint forces (read-only).
R
Array containing the history of the equilibrium residual (read only).
Z
Array containing the history of the lenght of each link (read only).
Zd
Array containing the history of the speed (spreading) of each link (read only).
q
Array containing the history of the generalized coordinates (read-only).
qd
Array containing the history of the generalized velocities (read-only).
qdd
Array containing the history of the generalized accelerations (read-only).
t
Array containing the time vector (read-only).
unspecified
Dictionary containing the buffers that where not identified.
ux
Array containing the history of the user variables (read only).
uxd
Array containing the history of the time derivative of the user variables (read only).
x
Array containing the history of the equilibrium variables (read only).
Methods
clear
(self)Reset all data fields to None.
load_results_from_buffer
(self, c_ptr[, t0, …])Load the results from the buffer if completely available.
load_results_from_file
(self, filename[, …])Load the results from the files.
set_buffer
(self, buf_id, buf_array[, name, …])Set the buffer array in the field corresponding the the buffer id.
set_time_from_array
(self, array)If the time array is not yet defined, fill it from the provided.
-
property
F
¶ Array containing the history of the residual force on equilibrium variables (read only).
This results is specific to equilibrium analysis.
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Fl
¶ Array containing the history of the forces in each links (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Lambda
¶ Array containing the history of the lagrange multipliers related to the constraints (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Qa
¶ Array containing the history of the actuation force (or torque) in each articulations (read only).
The value for non-articulated joints is always 0.
This field is only relevant for inverse dynamic.
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Qc
¶ Array containing the history of the force introduced in driven joints (read only).
The force introduced is required to respect the user-specified trajectory (position, velocity, acceleration). The values for non-driven joints is always 0.
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Qq
¶ Array containing the history of the user joint forces (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
R
¶ Array containing the history of the equilibrium residual (read only).
This results is specific to equilibrium analysis.
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Z
¶ Array containing the history of the lenght of each link (read only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
Zd
¶ Array containing the history of the speed (spreading) of each link (read only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
__init__
(self, mbs=None, prj_path=None)¶ Initialize the fields to None.
-
clear
(self)¶ Reset all data fields to None.
-
load_results_from_buffer
(self, c_ptr, t0=None, resfilename='')¶ Load the results from the buffer if completely available.
- Parameters
c_ptr (ctypes.POINTER to either MbsDirdyn_c or MbsSolvekin_c or MbsInvdyn_c) – Pointer to the c-structure of the current module. The module must contain the fields ‘buffers’ (MbsBuffer**), ‘bufferNb’ (int) and ‘user_buffer’ (MbsGrowingBuffer*).
t0 (float, optional) – Initial time (if relevant) of the analysis. If the initial time in the buffer does not match the provided value, the buffer are not loaded. If the value is None, then the buffers are loaded whatever the available timesteps. The default is None.
resfilename (str, optional) – The option of ‘resfilename’ of the module, this variable is only used to create the user output vectors name from the user filename. The default is ‘’ (empty str).
- Returns
True if the whole analysis was loaded from the buffers. False if nothing was loaded from the buffers in case of incomplete or invalid buffers.
- Return type
bool
Notes
Usually the first buffer is dedicated to generalized coordinates. At the exception of equilibrium analysis, where it is the fourth buffer. Even if equilibrium analysis is not (yet) handled by this function the loading iterates on the buffers until finding the one dedicated to generalized coordinates.
The buffer of the generalized coordinates is used to check if the full simulation is available in the buffer.
-
load_results_from_file
(self, filename, result_path='resultsR', module=0, user_output=None, user_vector=None, mode=1, sep=None)¶ Load the results from the files.
This function is called if the buffers do not contain the full simulation.
- Parameters
filename (str) – The filename of the results to load. It is either the base filename (without the suffix and extension) or the name of a file containing basic buffers (ie: q, qd, qdd…) to be loaded. In the second case the suffix and extension will be stripped to retrieve the basefilename. It can contain the full path to files, but it will be ignored.
result_path (str, optional) – The relative path of the result folder from the project folder. The default is “resultsR”.
user_output (list, optional) – List containing the user output files to be loaded if not None. default is None.
user_vector (list, optional) – List containing the user vector output files to be loaded if not None. default is None.
mode (list, optional) –
- Specify the results saving mode:
1: classic mode, value only using default (space) separator
2: CSV mode, header and value using new (;) separator by default.
sep (str, optional) – Allows to force the separator for mode==2. If None, it uses the mode 2 default separator (;). Otherwhise the provided separator is considered.
- Returns
False if the result path was not located.
- Return type
bool
-
property
q
¶ Array containing the history of the generalized coordinates (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
qd
¶ Array containing the history of the generalized velocities (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
qdd
¶ Array containing the history of the generalized accelerations (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
set_buffer
(self, buf_id, buf_array, name=None, header=None)¶ Set the buffer array in the field corresponding the the buffer id.
- Parameters
buf_id (int) – Value of the buffer id to be set. Buffer id are defined in the _buffer_ids class.
buf_array (numpy.ndarray) – Array with the history of the variable stored in the specified buffer.
name (str, optionnal) – Name of the user buffer to be set, ignored for other buffer.
- Returns
True if success, False otherwise.
- Return type
bool
-
set_time_from_array
(self, array)¶ If the time array is not yet defined, fill it from the provided.
- Parameters
array (np.ndarray) – Any array of results whose first col is the time array.
- Returns
- Return type
None.
-
property
t
¶ Array containing the time vector (read-only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
unspecified
¶ Dictionary containing the buffers that where not identified.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
ux
¶ Array containing the history of the user variables (read only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
uxd
¶ Array containing the history of the time derivative of the user variables (read only).
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.
-
property
x
¶ Array containing the history of the equilibrium variables (read only).
This results is specific to equilibrium analysis.
Return an empty array if no results are set in memory.
- Raises
UserWarning – Exception raised when no results has been loaded.