INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns plot, renderer and format for single frame export. | def single_frame_plot(obj):
"""
Returns plot, renderer and format for single frame export.
"""
obj = Layout.from_values(obj) if isinstance(obj, AdjointLayout) else obj
backend = Store.current_backend
renderer = Store.renderers[backend]
plot_cls = renderer.plotting_class(obj)
plot = plo... |
Only display the first frame of an animated plot | def first_frame(obj):
"Only display the first frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
plot.update(0)
return {'text/html': renderer.html(plot, fmt)} |
Only display the (approximately) middle frame of an animated plot | def middle_frame(obj):
"Only display the (approximately) middle frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
middle_frame = int(len(plot) / 2)
plot.update(middle_frame)
return {'text/html': renderer.html(plot, fmt)} |
Only display the last frame of an animated plot | def last_frame(obj):
"Only display the last frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
plot.update(len(plot))
return {'text/html': renderer.html(plot, fmt)} |
A decorator to wrap display hooks that return a MIME bundle or None.
Additionally it handles adding output to the notebook archive, saves
files specified with the output magic and handles tracebacks. | def display_hook(fn):
"""
A decorator to wrap display hooks that return a MIME bundle or None.
Additionally it handles adding output to the notebook archive, saves
files specified with the output magic and handles tracebacks.
"""
@wraps(fn)
def wrapped(element):
global FULL_TRACEBACK... |
Renders any HoloViews object to HTML and displays it
using the IPython display function. If raw is enabled
the raw HTML is returned instead of displaying it directly. | def display(obj, raw_output=False, **kwargs):
"""
Renders any HoloViews object to HTML and displays it
using the IPython display function. If raw is enabled
the raw HTML is returned instead of displaying it directly.
"""
if not Store.loaded_backends() and isinstance(obj, Dimensioned):
ra... |
Used to render elements to an image format (svg or png) if requested
in the display formats. | def image_display(element, max_frames, fmt):
"""
Used to render elements to an image format (svg or png) if requested
in the display formats.
"""
if fmt not in Store.display_formats:
return None
info = process_object(element)
if info:
display(HTML(info))
return
b... |
Map elements from given `order` array to bins ranging from `start`
to `end`. | def _map_order_to_ticks(start, end, order, reverse=False):
"""Map elements from given `order` array to bins ranging from `start`
to `end`.
"""
size = len(order)
bounds = np.linspace(start, end, size + 1)
if reverse:
bounds = bounds[::-1]
mapping = list... |
Compute x and y positions for separation lines for given angles. | def _compute_separations(inner, outer, angles):
"""Compute x and y positions for separation lines for given angles.
"""
return [np.array([[a, inner], [a, outer]]) for a in angles] |
Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dimension ranges
Whether to include Dimension range and soft... | def range(self, dim, data_range=True, dimension_range=True):
"""Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dime... |
Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
on the type of data:
* Colum... | def dimension_values(self, dim, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior ... |
Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Declared type of values along the dimension | def get_dimension_type(self, dim):
"""Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Decl... |
Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
multi_index: Convert key dimensions to (multi-)index
Return... | def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... |
message receive routine for UDP link | def recv_msg(self):
'''message receive routine for UDP link'''
self.pre_message()
s = self.recv()
if len(s) > 0:
if self.first_byte:
self.auto_mavlink_version(s)
m = self.mav.parse_char(s)
if m is not None:
self.post_message(m)
... |
Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimension | def columns(self, dimensions=None):
"""Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimensio... |
Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a
specified region of interest (LocationGlobal).
The vehicle may also turn to face the ROI.
For more information see:
http://copter.ardupilot.com/common-mavlink-mission-command-messages-mav_cmd/#mav_cmd_do_set_roi | def set_roi(location):
"""
Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a
specified region of interest (LocationGlobal).
The vehicle may also turn to face the ROI.
For more information see:
http://copter.ardupilot.com/common-mavlink-mission-command-messages-mav_cmd/#mav_cmd_do_se... |
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned LocationGlobal has the same `alt` value
as `original_location`.
The function is useful when you want to move the vehicle around specifying locations relative t... | def get_location_metres(original_location, dNorth, dEast):
"""
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned LocationGlobal has the same `alt` value
as `original_location`.
The function is useful w... |
Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py | def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/d... |
Returns the bearing between the two LocationGlobal objects passed as parameters.
This method is an approximation, and may not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py | def get_bearing(aLocation1, aLocation2):
"""
Returns the bearing between the two LocationGlobal objects passed as parameters.
This method is an approximation, and may not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diy... |
Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal.
For more information see: https://pixhawk.ethz.ch/mavlink/#SET_POSITION_TARGET_GLOBAL_INT
See the above link for information on the type_mask (0=enable, 1=ignore).
At time of writing, acceleration and ya... | def goto_position_target_global_int(aLocation):
"""
Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal.
For more information see: https://pixhawk.ethz.ch/mavlink/#SET_POSITION_TARGET_GLOBAL_INT
See the above link for information on the type_mask (0=ena... |
Send SET_POSITION_TARGET_LOCAL_NED command to request the vehicle fly to a specified
location in the North, East, Down frame.
It is important to remember that in this frame, positive altitudes are entered as negative
"Down" values. So if down is "10", this will be 10 metres below the home altitude.
... | def goto_position_target_local_ned(north, east, down):
"""
Send SET_POSITION_TARGET_LOCAL_NED command to request the vehicle fly to a specified
location in the North, East, Down frame.
It is important to remember that in this frame, positive altitudes are entered as negative
"Down" values. So if... |
Moves the vehicle to a position dNorth metres North and dEast metres East of the current position.
The method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for
the target position. This allows it to be called with different position-setting commands.
By default i... | def goto(dNorth, dEast, gotoFunction=vehicle.simple_goto):
"""
Moves the vehicle to a position dNorth metres North and dEast metres East of the current position.
The method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for
the target position. This allows it t... |
Move vehicle in direction based on specified velocity vectors and
for the specified duration.
This uses the SET_POSITION_TARGET_LOCAL_NED command with a type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided-mode/#set_position_target_local_ned).
... | def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors and
for the specified duration.
This uses the SET_POSITION_TARGET_LOCAL_NED command with a type mask enabling only
velocity components
(http://dev.ardupilot.c... |
Move vehicle in direction based on specified velocity vectors.
This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided-mode/#set_position_target_global_int).
Note that from AC3.3 the message sh... | def send_global_velocity(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors.
This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided... |
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
This function is used by upload_mission(). | def readmission(aFileName):
"""
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
This function is used by upload_mission().
"""
print("\nReading mission from file: %s" % aFil... |
Upload a mission from a file. | def upload_mission(aFileName):
"""
Upload a mission from a file.
"""
#Read mission from file
missionlist = readmission(aFileName)
print("\nUpload mission from a file: %s" % aFileName)
#Clear existing mission from vehicle
print(' Clear mission')
cmds = vehicle.commands
cmds.... |
Downloads the current mission and returns it in a list.
It is used in save_mission() to get the file information to save. | def download_mission():
"""
Downloads the current mission and returns it in a list.
It is used in save_mission() to get the file information to save.
"""
print(" Download mission from vehicle")
missionlist=[]
cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
for cmd in cm... |
Save a mission in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). | def save_mission(aFileName):
"""
Save a mission in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
"""
print("\nSave mission from Vehicle to file: %s" % aFileName)
#Download mission from vehicle
missionlist = download_mission()
#A... |
Print a mission file to demonstrate "round trip" | def printfile(aFileName):
"""
Print a mission file to demonstrate "round trip"
"""
print("\nMission file: %s" % aFileName)
with open(aFileName) as f:
for line in f:
print(' %s' % line.strip()) |
Gets distance in metres to the current waypoint.
It returns None for the first waypoint (Home location). | def distance_to_current_waypoint():
"""
Gets distance in metres to the current waypoint.
It returns None for the first waypoint (Home location).
"""
nextwaypoint = vehicle.commands.next
if nextwaypoint==0:
return None
missionitem=vehicle.commands[nextwaypoint-1] #commands are zero i... |
Given telemetry log, get a series of wpts approximating the previous flight | def position_messages_from_tlog(filename):
"""
Given telemetry log, get a series of wpts approximating the previous flight
"""
# Pull out just the global position msgs
messages = []
mlog = mavutil.mavlink_connection(filename)
while True:
try:
m = mlog.recv_match(type=['GL... |
Arms vehicle and fly to aTargetAltitude. | def arm_and_takeoff(aTargetAltitude):
"""
Arms vehicle and fly to aTargetAltitude.
"""
# Don't try to arm until autopilot is ready
while not vehicle.is_armable:
print(" Waiting for vehicle to initialise...")
time.sleep(1)
# Set mode to GUIDED for arming and takeoff:
... |
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned Location has the same `alt` value
as `original_location`.
The function is useful when you want to move the vehicle around specifying locations relative to
... | def get_location_metres(original_location, dNorth, dEast):
"""
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned Location has the same `alt` value
as `original_location`.
The function is useful when yo... |
Adds a takeoff command and four waypoint commands to the current mission.
The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation).
The function assumes vehicle.commands matches the vehicle mission state
(you must have called download at least o... | def adds_square_mission(aLocation, aSize):
"""
Adds a takeoff command and four waypoint commands to the current mission.
The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation).
The function assumes vehicle.commands matches the vehicle missi... |
Returns a :py:class:`Vehicle` object connected to the address specified by string parameter ``ip``.
Connection string parameters (``ip``) for different targets are listed in the :ref:`getting started guide <get_started_connecting>`.
The method is usually called with ``wait_ready=True`` to ensure that vehicle p... | def connect(ip,
_initialize=True,
wait_ready=None,
timeout=30,
still_waiting_callback=default_still_waiting_callback,
still_waiting_interval=1,
status_printer=None,
vehicle_class=None,
rate=4,
baud=115200,
... |
Distance away from home, in meters. Returns 3D distance if `down` is known, otherwise 2D distance. | def distance_home(self):
"""
Distance away from home, in meters. Returns 3D distance if `down` is known, otherwise 2D distance.
"""
if self.north is not None and self.east is not None:
if self.down is not None:
return math.sqrt(self.north**2 + self.east**2 + ... |
Add an attribute listener callback.
The callback function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are updated
whenever a message is received from the vehicle. Attributes wh... | def add_attribute_listener(self, attr_name, observer):
"""
Add an attribute listener callback.
The callback function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are upd... |
Remove an attribute listener (observer) that was previously added using :py:func:`add_attribute_listener`.
For example, the following line would remove a previously added vehicle 'global_frame'
observer called ``location_callback``:
.. code:: python
vehicle.remove_attribute_listen... | def remove_attribute_listener(self, attr_name, observer):
"""
Remove an attribute listener (observer) that was previously added using :py:func:`add_attribute_listener`.
For example, the following line would remove a previously added vehicle 'global_frame'
observer called ``location_call... |
This method is used to update attribute observers when the named attribute is updated.
You should call it in your message listeners after updating an attribute with
information from a vehicle message.
By default the value of ``cache`` is ``False`` and every update from the vehicle is sent to l... | def notify_attribute_listeners(self, attr_name, value, cache=False):
"""
This method is used to update attribute observers when the named attribute is updated.
You should call it in your message listeners after updating an attribute with
information from a vehicle message.
By d... |
Decorator for attribute listeners.
The decorated function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are updated
whenever a message is received from the vehicle. Attributes wh... | def on_attribute(self, name):
"""
Decorator for attribute listeners.
The decorated function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are updated
whenever a m... |
Decorator for message listener callback functions.
.. tip::
This is the most elegant way to define message listener callback functions.
Use :py:func:`add_message_listener` only if you need to be able to
:py:func:`remove the listener <remove_message_listener>` later.
... | def on_message(self, name):
"""
Decorator for message listener callback functions.
.. tip::
This is the most elegant way to define message listener callback functions.
Use :py:func:`add_message_listener` only if you need to be able to
:py:func:`remove the li... |
Adds a message listener function that will be called every time the specified message is received.
.. tip::
We recommend you use :py:func:`on_message` instead of this method as it has a more elegant syntax.
This method is only preferred if you need to be able to
:py:func:`r... | def add_message_listener(self, name, fn):
"""
Adds a message listener function that will be called every time the specified message is received.
.. tip::
We recommend you use :py:func:`on_message` instead of this method as it has a more elegant syntax.
This method is on... |
Removes a message listener (that was previously added using :py:func:`add_message_listener`).
See :ref:`mavlink_messages` for more information.
:param String name: The name of the message for which the listener is to be removed (or '*' to remove an 'all messages' observer).
:param fn: The list... | def remove_message_listener(self, name, fn):
"""
Removes a message listener (that was previously added using :py:func:`add_message_listener`).
See :ref:`mavlink_messages` for more information.
:param String name: The name of the message for which the listener is to be removed (or '*' t... |
Current system batter status (:py:class:`Battery`). | def battery(self):
"""
Current system batter status (:py:class:`Battery`).
"""
if self._voltage is None or self._current is None or self._level is None:
return None
return Battery(self._voltage, self._current, self._level) |
GPS position information (:py:class:`GPSInfo`). | def gps_0(self):
"""
GPS position information (:py:class:`GPSInfo`).
"""
return GPSInfo(self._eph, self._epv, self._fix_type, self._satellites_visible) |
Returns ``True`` if the vehicle is ready to arm, false otherwise (``Boolean``).
This attribute wraps a number of pre-arm checks, ensuring that the vehicle has booted,
has a good GPS fix, and that the EKF pre-arm is complete. | def is_armable(self):
"""
Returns ``True`` if the vehicle is ready to arm, false otherwise (``Boolean``).
This attribute wraps a number of pre-arm checks, ensuring that the vehicle has booted,
has a good GPS fix, and that the EKF pre-arm is complete.
"""
# check that mod... |
System status (:py:class:`SystemStatus`).
The status has a ``state`` property with one of the following values:
* ``UNINIT``: Uninitialized system, state is unknown.
* ``BOOT``: System is booting up.
* ``CALIBRATING``: System is calibrating and not flight-ready.
* ``STANDBY``: ... | def system_status(self):
"""
System status (:py:class:`SystemStatus`).
The status has a ``state`` property with one of the following values:
* ``UNINIT``: Uninitialized system, state is unknown.
* ``BOOT``: System is booting up.
* ``CALIBRATING``: System is calibrating ... |
``True`` if the EKF status is considered acceptable, ``False`` otherwise (``boolean``). | def ekf_ok(self):
"""
``True`` if the EKF status is considered acceptable, ``False`` otherwise (``boolean``).
"""
# legacy check for dronekit-python for solo
# use same check that ArduCopter::system.pde::position_ok() is using
if self.armed:
return self._ekf_p... |
Sets the home location (``LocationGlobal``).
The value cannot be set until it has successfully been read from the vehicle. After being
set the value is cached in the home_location attribute and does not have to be re-read.
.. note::
Setting the value will fail silently if the spec... | def home_location(self, pos):
"""
Sets the home location (``LocationGlobal``).
The value cannot be set until it has successfully been read from the vehicle. After being
set the value is cached in the home_location attribute and does not have to be re-read.
.. note::
... |
Wait for a condition to be True.
Wait for condition, a callable, to return True. If timeout is
nonzero, raise a TimeoutError(errmsg) if the condition is not
True after timeout seconds. Check the condition everal
interval seconds. | def wait_for(self, condition, timeout=None, interval=0.1, errmsg=None):
'''Wait for a condition to be True.
Wait for condition, a callable, to return True. If timeout is
nonzero, raise a TimeoutError(errmsg) if the condition is not
True after timeout seconds. Check the condition evera... |
Wait for the vehicle to become armable.
If timeout is nonzero, raise a TimeoutError if the vehicle
is not armable after timeout seconds. | def wait_for_armable(self, timeout=None):
'''Wait for the vehicle to become armable.
If timeout is nonzero, raise a TimeoutError if the vehicle
is not armable after timeout seconds.
'''
def check_armable():
return self.is_armable
self.wait_for(check_armable... |
Arm the vehicle.
If wait is True, wait for arm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not armed after timeout seconds. | def arm(self, wait=True, timeout=None):
'''Arm the vehicle.
If wait is True, wait for arm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not armed after timeout seconds.
'''
self.armed = True
if wait:
... |
Disarm the vehicle.
If wait is True, wait for disarm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not disarmed after timeout seconds. | def disarm(self, wait=True, timeout=None):
'''Disarm the vehicle.
If wait is True, wait for disarm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not disarmed after timeout seconds.
'''
self.armed = False
... |
Set the flight mode.
If wait is True, wait for the mode to change before returning.
If timeout is nonzero, raise a TimeoutError if the flight mode
hasn't changed after timeout seconds. | def wait_for_mode(self, mode, timeout=None):
'''Set the flight mode.
If wait is True, wait for the mode to change before returning.
If timeout is nonzero, raise a TimeoutError if the flight mode
hasn't changed after timeout seconds.
'''
if not isinstance(mode, VehicleMo... |
Wait for the vehicle to reach the specified altitude.
Wait for the vehicle to get within epsilon meters of the
given altitude. If rel is True (the default), use the
global_relative_frame. If rel is False, use the global_frame.
If timeout is nonzero, raise a TimeoutError if the specifie... | def wait_for_alt(self, alt, epsilon=0.1, rel=True, timeout=None):
'''Wait for the vehicle to reach the specified altitude.
Wait for the vehicle to get within epsilon meters of the
given altitude. If rel is True (the default), use the
global_relative_frame. If rel is False, use the glob... |
Take off and fly the vehicle to the specified altitude (in metres) and then wait for another command.
.. note::
This function should only be used on Copter vehicles.
The vehicle must be in GUIDED mode and armed before this is called.
There is no mechanism for notification when t... | def simple_takeoff(self, alt=None):
"""
Take off and fly the vehicle to the specified altitude (in metres) and then wait for another command.
.. note::
This function should only be used on Copter vehicles.
The vehicle must be in GUIDED mode and armed before this is called... |
Go to a specified global location (:py:class:`LocationGlobal` or :py:class:`LocationGlobalRelative`).
There is no mechanism for notification when the target location is reached, and if another command arrives
before that point that will be executed immediately.
You can optionally set the desir... | def simple_goto(self, location, airspeed=None, groundspeed=None):
'''
Go to a specified global location (:py:class:`LocationGlobal` or :py:class:`LocationGlobalRelative`).
There is no mechanism for notification when the target location is reached, and if another command arrives
before t... |
An alias for send_capabilities_request.
The word "capabilities" was misspelled in previous versions of this code. This is simply
an alias to send_capabilities_request using the legacy name. | def send_capabilties_request(self, vehicle, name, m):
'''An alias for send_capabilities_request.
The word "capabilities" was misspelled in previous versions of this code. This is simply
an alias to send_capabilities_request using the legacy name.
'''
return self.send_capabilitie... |
Request an AUTOPILOT_VERSION packet | def send_capabilities_request(self, vehicle, name, m):
'''Request an AUTOPILOT_VERSION packet'''
capability_msg = vehicle.message_factory.command_long_encode(0, 0, mavutil.mavlink.MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, 0, 1, 0, 0, 0, 0, 0, 0)
vehicle.send_mavlink(capability_msg) |
Play a tune on the vehicle | def play_tune(self, tune):
'''Play a tune on the vehicle'''
msg = self.message_factory.play_tune_encode(0, 0, tune)
self.send_mavlink(msg) |
Waits for specified attributes to be populated from the vehicle (values are initially ``None``).
This is typically called "behind the scenes" to ensure that :py:func:`connect` does not return until
attributes have populated (via the ``wait_ready`` parameter). You can also use it after connecting to
... | def wait_ready(self, *types, **kwargs):
"""
Waits for specified attributes to be populated from the vehicle (values are initially ``None``).
This is typically called "behind the scenes" to ensure that :py:func:`connect` does not return until
attributes have populated (via the ``wait_rea... |
Requests an autopilot reboot by sending a ``MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`` command. | def reboot(self):
"""Requests an autopilot reboot by sending a ``MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`` command."""
reboot_msg = self.message_factory.command_long_encode(
0, 0, # target_system, target_component
mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, # command
... |
Request magnetometer calibration. | def send_calibrate_magnetometer(self):
"""Request magnetometer calibration."""
# ArduPilot requires the MAV_CMD_DO_START_MAG_CAL command, only present in the ardupilotmega.xml definition
if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA:
calibration_command = se... |
Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration | def send_calibrate_accelerometer(self, simple=False):
"""Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration
"""
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0, # target_system,... |
Request barometer calibration. | def send_calibrate_barometer(self):
"""Request barometer calibration."""
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0, # target_system, target_component
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command
0, #... |
Rotate the gimbal to a specific vector.
.. code-block:: python
#Point the gimbal straight down
vehicle.gimbal.rotate(-90, 0, 0)
:param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude <figure_attitude>`).
A value of 0 represent... | def rotate(self, pitch, roll, yaw):
"""
Rotate the gimbal to a specific vector.
.. code-block:: python
#Point the gimbal straight down
vehicle.gimbal.rotate(-90, 0, 0)
:param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude... |
Point the gimbal at a specific region of interest (ROI).
.. code-block:: python
#Set the camera to track the current home location.
vehicle.gimbal.target_location(vehicle.home_location)
The target position must be defined in a :py:class:`LocationGlobalRelative` or :py:class:`L... | def target_location(self, roi):
"""
Point the gimbal at a specific region of interest (ROI).
.. code-block:: python
#Set the camera to track the current home location.
vehicle.gimbal.target_location(vehicle.home_location)
The target position must be defined in ... |
Release control of the gimbal to the user (RC Control).
This should be called once you've finished controlling the mount with either :py:func:`rotate`
or :py:func:`target_location`. Control will automatically be released if you change vehicle mode. | def release(self):
"""
Release control of the gimbal to the user (RC Control).
This should be called once you've finished controlling the mount with either :py:func:`rotate`
or :py:func:`target_location`. Control will automatically be released if you change vehicle mode.
"""
... |
Add a listener callback on a particular parameter.
The callback can be removed using :py:func:`remove_attribute_listener`.
.. note::
The :py:func:`on_attribute` decorator performs the same operation as this method, but with
a more elegant syntax. Use ``add_attribute_listener``... | def add_attribute_listener(self, attr_name, *args, **kwargs):
"""
Add a listener callback on a particular parameter.
The callback can be removed using :py:func:`remove_attribute_listener`.
.. note::
The :py:func:`on_attribute` decorator performs the same operation as this ... |
Remove a paremeter listener that was previously added using :py:func:`add_attribute_listener`.
For example to remove the ``thr_min_callback()`` callback function:
.. code:: python
vehicle.parameters.remove_attribute_listener('thr_min', thr_min_callback)
See :ref:`vehicle_state_ob... | def remove_attribute_listener(self, attr_name, *args, **kwargs):
"""
Remove a paremeter listener that was previously added using :py:func:`add_attribute_listener`.
For example to remove the ``thr_min_callback()`` callback function:
.. code:: python
vehicle.parameters.remov... |
Decorator for parameter listeners.
.. note::
There is no way to remove a listener added with this decorator. Use
:py:func:`add_attribute_listener` if you need to be able to remove
the :py:func:`listener <remove_attribute_listener>`.
The callback function is invoked... | def on_attribute(self, attr_name, *args, **kwargs):
"""
Decorator for parameter listeners.
.. note::
There is no way to remove a listener added with this decorator. Use
:py:func:`add_attribute_listener` if you need to be able to remove
the :py:func:`listener... |
Download all waypoints from the vehicle.
The download is asynchronous. Use :py:func:`wait_ready()` to block your thread until the download is complete. | def download(self):
'''
Download all waypoints from the vehicle.
The download is asynchronous. Use :py:func:`wait_ready()` to block your thread until the download is complete.
'''
self.wait_ready()
self._vehicle._ready_attrs.remove('commands')
self._vehicle._wp_lo... |
Clear the command list.
This command will be sent to the vehicle only after you call :py:func:`upload() <Vehicle.commands.upload>`. | def clear(self):
'''
Clear the command list.
This command will be sent to the vehicle only after you call :py:func:`upload() <Vehicle.commands.upload>`.
'''
# Add home point again.
self.wait_ready()
home = None
try:
home = self._vehicle._wplo... |
Add a new command (waypoint) at the end of the command list.
.. note::
Commands are sent to the vehicle only after you call ::py:func:`upload() <Vehicle.commands.upload>`.
:param Command cmd: The command to be added. | def add(self, cmd):
'''
Add a new command (waypoint) at the end of the command list.
.. note::
Commands are sent to the vehicle only after you call ::py:func:`upload() <Vehicle.commands.upload>`.
:param Command cmd: The command to be added.
'''
self.wait_re... |
Call ``upload()`` after :py:func:`adding <CommandSequence.add>` or :py:func:`clearing <CommandSequence.clear>` mission commands.
After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an
exception) and future reads will see their effects.
:param int timeout: ... | def upload(self, timeout=None):
"""
Call ``upload()`` after :py:func:`adding <CommandSequence.add>` or :py:func:`clearing <CommandSequence.clear>` mission commands.
After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an
exception) and future reads w... |
Arms vehicle and fly to aTargetAltitude without GPS data. | def arm_and_takeoff_nogps(aTargetAltitude):
"""
Arms vehicle and fly to aTargetAltitude without GPS data.
"""
##### CONSTANTS #####
DEFAULT_TAKEOFF_THRUST = 0.7
SMOOTH_TAKEOFF_THRUST = 0.6
print("Basic pre-arm checks")
# Don't let the user try to arm until autopilot is ready
# If y... |
use_yaw_rate: the yaw can be controlled using yaw_angle OR yaw_rate.
When one is used, the other is ignored by Ardupilot.
thrust: 0 <= thrust <= 1, as a fraction of maximum vertical thrust.
Note that as of Copter 3.5, thrust = 0.5 triggers a special case in
the code for mai... | def send_attitude_target(roll_angle = 0.0, pitch_angle = 0.0,
yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False,
thrust = 0.5):
"""
use_yaw_rate: the yaw can be controlled using yaw_angle OR yaw_rate.
When one is used, the other is ignored... |
Note that from AC3.3 the message should be re-sent more often than every
second, as an ATTITUDE_TARGET order has a timeout of 1s.
In AC3.2.1 and earlier the specified attitude persists until it is canceled.
The code below should work on either version.
Sending the message multiple times is the recommend... | def set_attitude(roll_angle = 0.0, pitch_angle = 0.0,
yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False,
thrust = 0.5, duration = 0):
"""
Note that from AC3.3 the message should be re-sent more often than every
second, as an ATTITUDE_TARGET order has a timeout of 1s.
... |
Computes the normalized term frequency as explained in http://www.tfidf.com/ | def _compute_tf(self, sentences):
"""
Computes the normalized term frequency as explained in http://www.tfidf.com/
"""
content_words = self._get_all_content_words_in_doc(sentences)
content_words_count = len(content_words)
content_words_freq = self._compute_word_freq(conte... |
Convert degrees to quaternions | def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0):
"""
Convert degrees to quaternions
"""
t0 = math.cos(math.radians(yaw * 0.5))
t1 = math.sin(math.radians(yaw * 0.5))
t2 = math.cos(math.radians(roll * 0.5))
t3 = math.sin(math.radians(roll * 0.5))
t4 = math.cos(math.radians(pitch * 0... |
Computation of F-Score measure. It is computed as
F(E) = ( (W^2 + 1) * P(E) * R(E) ) / ( W^2 * P(E) + R(E) ), where:
- P(E) is precision metrics of extract E.
- R(E) is recall metrics of extract E.
- W is a weighting factor that favours P(E) metrics
when W > 1 and favours R(E) metrics when W < 1.... | def f_score(evaluated_sentences, reference_sentences, weight=1.0):
"""
Computation of F-Score measure. It is computed as
F(E) = ( (W^2 + 1) * P(E) * R(E) ) / ( W^2 * P(E) + R(E) ), where:
- P(E) is precision metrics of extract E.
- R(E) is recall metrics of extract E.
- W is a weighting factor ... |
Returns the length of the Longest Common Subsequence between sequences x
and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
:param x: sequence of words
:param y: sequence of words
:returns integer: Length of LCS between x and y | def _len_lcs(x, y):
"""
Returns the length of the Longest Common Subsequence between sequences x
and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
:param x: sequence of words
:param y: sequence of words
:returns integer: Length of LCS between x and y
"""
... |
Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
:param x: sequence of words
:param y: sequence of words
:returns sequence: LCS of x and y | def _recon_lcs(x, y):
"""
Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
:param x: sequence of words
:param y: sequence of words
:returns sequence: LCS of x and y
"""
table = _lcs(x, y)
def _recon(i, j):
... |
Computes the LCS-based F-measure score
Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
:param llcs: Length of LCS
:param m: number of words in reference summary
:param n: number of words in candidate summary
:returns float: LCS-based F-me... | def _f_lcs(llcs, m, n):
"""
Computes the LCS-based F-measure score
Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
:param llcs: Length of LCS
:param m: number of words in reference summary
:param n: number of words in candidate summar... |
Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)/n
F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)... | def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lc... |
Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence
between reference sentence ri and candidate summary C. For example, if
r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and
c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 is
... | def _union_lcs(evaluated_sentences, reference_sentence):
"""
Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence
between reference sentence ri and candidate summary C. For example, if
r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and
c2 = w1 ... |
Lenght/norm/magnitude of vector representation of document.
This is usually denoted by ||d||. | def magnitude(self):
"""
Lenght/norm/magnitude of vector representation of document.
This is usually denoted by ||d||.
"""
return math.sqrt(sum(t**2 for t in self._terms.values())) |
Returns ``count`` of terms sorted by their frequency
in descending order.
:parameter int count:
Max. number of returned terms. Value 0 means no limit (default). | def most_frequent_terms(self, count=0):
"""
Returns ``count`` of terms sorted by their frequency
in descending order.
:parameter int count:
Max. number of returned terms. Value 0 means no limit (default).
"""
# sort terms by number of occurrences in descendin... |
Returns normalized frequency of term in document.
http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
:parameter float smooth:
0.0 <= smooth <= 1.0, generally set to 0.4, although some
early work used the value 0.5. The term is a smoothing term
... | def normalized_term_frequency(self, term, smooth=0.0):
"""
Returns normalized frequency of term in document.
http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
:parameter float smooth:
0.0 <= smooth <= 1.0, generally set to 0.4, although some
... |
Counts number of bonus/stigma words.
:param iterable words:
Collection of words.
:returns pair:
Tuple with number of words (bonus words, stigma words). | def _count_words(self, words):
"""
Counts number of bonus/stigma words.
:param iterable words:
Collection of words.
:returns pair:
Tuple with number of words (bonus words, stigma words).
"""
bonus_words_count = 0
stigma_words_count = 0
... |
Decorator that converts a method into memoized property.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties. | def cached_property(getter):
"""
Decorator that converts a method into memoized property.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties.
"""
@wraps(getter)
def decorator(self):
key = "_cached_property_" + getter.__name__
... |
Computes cosine similarity of two text documents. Each document
has to be represented as TF model of non-empty document.
:returns float:
0 <= cos <= 1, where 0 means independence and 1 means
exactly the same. | def cosine_similarity(evaluated_model, reference_model):
"""
Computes cosine similarity of two text documents. Each document
has to be represented as TF model of non-empty document.
:returns float:
0 <= cos <= 1, where 0 means independence and 1 means
exactly the same.
"""
if no... |
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same. | def unit_overlap(evaluated_model, reference_model):
"""
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same.
"""
if not (isinstance... |
Creates mapping key = word, value = row index | def _create_dictionary(self, document):
"""Creates mapping key = word, value = row index"""
words = map(self.normalize_word, document.words)
unique_words = frozenset(self.stem_word(w) for w in words if w not in self._stop_words)
return dict((w, i) for i, w in enumerate(unique_words)) |
Creates matrix of shape |unique words|×|sentences| where cells
contains number of occurences of words (rows) in senteces (cols). | def _create_matrix(self, document, dictionary):
"""
Creates matrix of shape |unique words|×|sentences| where cells
contains number of occurences of words (rows) in senteces (cols).
"""
sentences = document.sentences
words_count = len(dictionary)
sentences_count =... |
Computes TF metrics for each sentence (column) in the given matrix.
You can read more about smoothing parameter at URL below:
http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html | def _compute_term_frequency(self, matrix, smooth=0.4):
"""
Computes TF metrics for each sentence (column) in the given matrix.
You can read more about smoothing parameter at URL below:
http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
"""
as... |
Create a stochastic matrix for TextRank.
Element at row i and column j of the matrix corresponds to the similarity of sentence i
and j, where the similarity is computed as the number of common words between them, divided
by their sum of logarithm of their lengths. After such matrix is created, ... | def _create_matrix(self, document):
"""Create a stochastic matrix for TextRank.
Element at row i and column j of the matrix corresponds to the similarity of sentence i
and j, where the similarity is computed as the number of common words between them, divided
by their sum of logarithm o... |
Computes the normalized term frequency as explained in http://www.tfidf.com/
:type sentences: [sumy.models.dom.Sentence] | def compute_tf(self, sentences):
"""
Computes the normalized term frequency as explained in http://www.tfidf.com/
:type sentences: [sumy.models.dom.Sentence]
"""
content_words = self._get_all_content_words_in_doc(sentences)
content_words_count = len(content_words)
... |
Note: Could import scipy.stats and use scipy.stats.entropy(doc_freq, summary_freq)
but this gives equivalent value without the import | def _kl_divergence(self, summary_freq, doc_freq):
"""
Note: Could import scipy.stats and use scipy.stats.entropy(doc_freq, summary_freq)
but this gives equivalent value without the import
"""
sum_val = 0
for w in summary_freq:
frequency = doc_freq.get(w)
... |
Removes trailing zeroes from indexable collection of numbers | def __remove_trailing_zeros(self, collection):
"""Removes trailing zeroes from indexable collection of numbers"""
index = len(collection) - 1
while index >= 0 and collection[index] == 0:
index -= 1
return collection[:index + 1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.