INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Wait for the vehicle to reach the specified altitude.
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.
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 ).
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.
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 ).
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.
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.
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 ).
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 ).
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.
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.
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.
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.
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.
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.
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 maintaining current altitude.
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 recommended way.
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. ...
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...
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...
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:
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
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
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
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
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 “w1 w2” and the...
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.
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
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.
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.
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.
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.
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/
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]
Creates matrix of shape |sentences|×|sentences|.
def _create_matrix(self, sentences, threshold, tf_metrics, idf_metrics): """ Creates matrix of shape |sentences|×|sentences|. """ # create matrix |sentences|×|sentences| filled with zeroes sentences_count = len(sentences) matrix = numpy.zeros((sentences_count, sentences_c...
We compute idf - modified - cosine ( sentence1 sentence2 ) here. It s cosine similarity of these two sentences ( vectors ) A B computed as cos ( x y ) = A. B/ ( |A|. |B| ) Sentences are represented as vector TF * IDF metrics.
def cosine_similarity(sentence1, sentence2, tf1, tf2, idf_metrics): """ We compute idf-modified-cosine(sentence1, sentence2) here. It's cosine similarity of these two sentences (vectors) A, B computed as cos(x, y) = A . B / (|A| . |B|) Sentences are represented as vector TF*IDF metrics. ...
Decorator for unicode compatible classes. Method __unicode__ has to be implemented to work decorator as expected.
def unicode_compatible(cls): """ Decorator for unicode compatible classes. Method ``__unicode__`` has to be implemented to work decorator as expected. """ if PY3: cls.__str__ = cls.__unicode__ cls.__bytes__ = lambda self: self.__str__().encode("utf-8") else: cls.__str__ =...
Summary
def to_weld_type(weld_type, dim): """Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """ for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type
Summary
def evaluate(self, verbose=True, decode=True, passes=None, num_threads=1, apply_experimental_transforms=False): """Summary Args: verbose (bool, optional): Description decode (bool, optional): Description Returns: TYPE: Description ""...
Generating a new weldarray from a given arr for self.
def _gen_weldobj(self, arr): ''' Generating a new weldarray from a given arr for self. @arr: weldarray or ndarray. - weldarray: Just update the weldobject with the context from the weldarray. - ndarray: Add the given array to the context of the weldobject. ...
Helper function for __array_ufunc__ that deals with the input/ output checks and determines if this should be relegated to numpy s implementation or not. @input_args: args to __array_ufunc__ @outputs: specified outputs.
def _process_ufunc_inputs(self, input_args, outputs): ''' Helper function for __array_ufunc__ that deals with the input/output checks and determines if this should be relegated to numpy's implementation or not. @input_args: args to __array_ufunc__ @outputs: specified outputs. ...
relegate responsibility of executing ufunc to numpy.
def _handle_numpy(self, ufunc, method, input_args, outputs, kwargs): ''' relegate responsibility of executing ufunc to numpy. ''' # Relegating the work to numpy. If input arg is weldarray, evaluate it, # and convert to ndarray before passing to super() for i, arg_ in enum...
TODO: add description
def _handle_call(self, ufunc, input_args, outputs): ''' TODO: add description ''' # if output is not None, choose the first one - since we don't support any ops with # multiple outputs. if outputs: output = outputs[0] else: output = None # check for suppo...
TODO: describe. TODO: For multi - dimensional case might need extra work here if the reduction is being performed only along a certain axis. We force evaluation at the end of the reduction - weird errors if we don t. This seems safer anyway. np supports reduce only for binary ops.
def _handle_reduce(self, ufunc, input_args, outputs): ''' TODO: describe. TODO: For multi-dimensional case, might need extra work here if the reduction is being performed only along a certain axis. We force evaluation at the end of the reduction - weird errors if we don't. This s...
TODO: support for multidimensional arrays.
def _reduce_op(self, op, result=None): ''' TODO: support for multidimensional arrays. ''' template = 'result(for({arr},merger[{type}, {op}], |b, i, e| merge(b, e)))' self.weldobj.weld_code = template.format(arr = self.weldobj.weld_code, ...
Creating a new result weldarray from self. If self is view into a weldarray then evaluate the parent first as self would not be storing the ops that have been registered to it ( only base_array would store those ).
def _get_result(self): ''' Creating a new result weldarray from self. If self is view into a weldarray, then evaluate the parent first as self would not be storing the ops that have been registered to it (only base_array would store those). ''' if self._weldarray_view: ...
@unop: str weld IR for the given function. @result: output array.
def _unary_op(self, unop, result=None): ''' @unop: str, weld IR for the given function. @result: output array. Create a new array, and updates weldobj.weld_code with the code for unop. ''' def _update_array_unary_op(res, unop): ''' @res: w...
Helper function for _binary_op.
def _scalar_binary_op(self, other, binop, result): ''' Helper function for _binary_op. @other, scalar values (i32, i64, f32, f64). @result: weldarray to store results in. ''' template = 'map({arr}, |z: {type}| z {binop} {other}{suffix})' weld_type = result._weld_t...
@result: weldarray that is being updated @other: weldarray or scalar. ( result binop other ) @binop: str operation to perform.
def _update_views_binary(self, result, other, binop): ''' @result: weldarray that is being updated @other: weldarray or scalar. (result binop other) @binop: str, operation to perform. FIXME: the common indexing pattern for parent/child in _update_view might be too expensive ...
Summary
def _get_column_names(self): """Summary Returns: TYPE: Description """ column_names = set() for column in self.df: column_names.add(column) for column in self.unmaterialized_cols: column_names.add(column) return list(column_nam...
Summary
def filter(self, predicates): """Summary Args: grouping_column_name (TYPE): Description Returns: TYPE: Description """ tys = [] for col_name, raw_column in self.raw_columns.items(): dtype = str(raw_column.dtype) if dtype =...
Summary
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ if self.is_pivot: index, pivot, columns = LazyOpResult( self.expr, self.weld_type, 0 ).evaluate(verbose=verbose, p...
Sorts the values of this series
def sort_values(self, ascending=False): """ Sorts the values of this series """ if self.index_type is not None: index_expr = grizzly_impl.get_field(self.expr, 0) column_expr = grizzly_impl.get_field(self.expr, 1) zip_expr = grizzly_impl.zip_columns([index_exp...
Summary
def unique(self): """Summary Returns: TYPE: Description """ return SeriesWeld( grizzly_impl.unique( self.expr, self.weld_type ), self.weld_type, self.df, self.column_name )
Summary
def lower(self): """Summary Returns: TYPE: Description """ # TODO : Bug in nested map operating on strings # TODO : Check that self.weld_type is a string type vectype = self.weld_type if isinstance(vectype, WeldVec): elem_type = vectype.el...
Summary
def contains(self, string): """Summary Returns: TYPE: Description """ # Check that self.weld_type is a string type vectype = self.weld_type if isinstance(vectype, WeldVec): elem_type = vectype.elemType if isinstance(elem_type, WeldChar): ...
Summary
def prod(self): """Summary Returns: TYPE: Description """ return LazyOpResult( grizzly_impl.aggr( self.expr, "*", 1, self.weld_type ), self.weld_type, 0 )
Summary
def sum(self): """Summary Returns: TYPE: Description """ return LazyOpResult( grizzly_impl.aggr( self.expr, "+", 0, self.weld_type ), self.weld_type, 0 )
Summary
def count(self): """Summary Returns: TYPE: Description """ return LazyOpResult( grizzly_impl.count( self.expr, self.weld_type ), WeldInt(), 0 )
Summary
def mask(self, predicates, new_value): """Summary Args: predicates (TYPE): Description new_value (TYPE): Description Returns: TYPE: Description """ if isinstance(predicates, SeriesWeld): predicates = predicates.expr return...
Summary
def add(self, other): """Summary Args: other (TYPE): Description Returns: TYPE: Description """ if isinstance(other, SeriesWeld): other = other.expr return SeriesWeld( grizzly_impl.element_wise_op( self.exp...
Summary
def slice(self, start, size): """Summary Args: start (TYPE): Description size (TYPE): Description Returns: TYPE: Description """ return SeriesWeld( grizzly_impl.slice( self.expr, start, ...
Update this context. if value is another context the names from that context are added into this one. Otherwise a new name is assigned and returned.
def update(self, value, tys=None, override=True): """ Update this context. if value is another context, the names from that context are added into this one. Otherwise, a new name is assigned and returned. TODO tys for inputs. """ if isinstance(value, WeldObject):...
Summary
def sum(self): """Summary Returns: TYPE: Description """ return GroupedDataFrameWeld( grizzly_impl.groupby_sum( self.columns, self.column_types, self.grouping_columns, self.grouping_column_types ...
Summary
def sort_values(self, by, ascending=True): """Summary Returns: TYPE: Description """ if len(self.column_types) == 1: vec_type = [WeldVec(self.column_types[0])] else: vec_type = [WeldVec(WeldStruct(self.column_types))] if len(self.colu...
Returns the sizes of the groups as series.
def size(self): """Returns the sizes of the groups as series. Returns: TYPE: Description """ if len(self.grouping_column_types) > 1: index_type = WeldStruct([self.grouping_column_types]) # Figure out what to use for multi-key index name # ...
Summary
def get_column(self, column_name, column_type, index, verbose=True): """Summary Args: column_name (TYPE): Description column_type (TYPE): Description index (TYPE): Description Returns: TYPE: Description """ return LazyOpResult( ...
Flattens the grouped data structure.
def reset_index(self, inplace=True, drop=True): """ Flattens the grouped data structure. #TODO: The parameters here are meaningless Flattens the grouped data structure. What is returned is a DataFrameWeld object. """ if len(self.column_types) == 1: vectype =...
Summary
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ i = 0 exprs = [] for column_name in self.column_names: if len(self.column_names) > 1: index = "1.$%d" % i else: in...
Standard deviation
def std(self): """Standard deviation Note that is by default normalizd by n - 1 # TODO, what does pandas do for multiple grouping columns? # Currently we are just going to use one grouping column """ std_expr = grizzly_impl.groupby_std( [self.column], ...
WeldContext is currently hidden from the Python API. We create a new context per Weld run and give ownership of it to the resulting value.
def run(self, conf, arg, err): """ WeldContext is currently hidden from the Python API. We create a new context per Weld run and give ownership of it to the resulting value. NOTE: This can leak the context if the result of the Weld run is an error. """ weld_conte...
Computes the aggregate of elements in the array.
def aggr(array, op, initial_value, ty): """ Computes the aggregate of elements in the array. Args: array (WeldObject / Numpy.ndarray): Input array to aggregate op (str): Op string used to aggregate the array (+ / *) initial_value (int): Initial value for aggregation ty (Weld...
Computes the dot product between a matrix and a vector.
def dot(matrix, vector, matrix_ty, vector_ty): """ Computes the dot product between a matrix and a vector. Args: matrix (WeldObject / Numpy.ndarray): 2-d input matrix vector (WeldObject / Numpy.ndarray): 1-d input vector ty (WeldType): Type of each element in the input matrix and ve...
Computes the per - element exponenet of the passed - in array.
def exp(array, ty): """ Computes the per-element exponenet of the passed-in array. Args: array (WeldObject / Numpy.ndarray): Input array ty (WeldType): Type of each element in the input array Returns: A WeldObject representing this computation """ weld_obj = WeldObject(...
Checks the base address of the given arrays to figure out if child and par have overlapping memory regions.
def is_view_child(view, par): ''' Checks the base address of the given arrays to figure out if child and par have overlapping memory regions. ''' if par.base is None: # par is the base array. return view.base is par else: # par is a view of another array as well! ...
Returns a dictionary of the Weld supported binary ops with values being their Weld symbol.
def get_supported_binary_ops(): ''' Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. ''' binary_ops = {} binary_ops[np.add.__name__] = '+' binary_ops[np.subtract.__name__] = '-' binary_ops[np.multiply.__name__] = '*' binary_ops[np.divide.__name_...
Returns a dictionary of the Weld supported unary ops with values being their Weld symbol.
def get_supported_unary_ops(): ''' Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol. ''' unary_ops = {} unary_ops[np.exp.__name__] = 'exp' unary_ops[np.log.__name__] = 'log' unary_ops[np.sqrt.__name__] = 'sqrt' return unary_ops
Summary
def ctype_class(self): """Summary Returns: TYPE: Description """ def vec_factory(elemType): """Summary Args: elemType (TYPE): Description Returns: TYPE: Description """ class Vec(St...
Summary
def ctype_class(self): """Summary Returns: TYPE: Description """ def struct_factory(field_types): """Summary Args: field_types (TYPE): Description Returns: TYPE: Description """ cla...
Fetch a field from a struct expr
def get_field(expr, field): """ Fetch a field from a struct expr """ weld_obj = WeldObject(encoder_, decoder_) struct_var = weld_obj.update(expr) if isinstance(expr, WeldObject): struct_var = expr.obj_id weld_obj.dependencies[struct_var] = expr weld_template = """ %(stru...
Returns a new array with each element in the original array satisfying the passed - in predicate set to new_value
def mask(array, predicates, new_value, ty): """ Returns a new array, with each element in the original array satisfying the passed-in predicate set to `new_value` Args: array (WeldObject / Numpy.ndarray): Input array predicates (WeldObject / Numpy.ndarray<bool>): Predicate set n...
Returns a new array with each element in the original array satisfying the passed - in predicate set to new_value
def filter(array, predicates, ty=None): """ Returns a new array, with each element in the original array satisfying the passed-in predicate set to `new_value` Args: array (WeldObject / Numpy.ndarray): Input array predicates (WeldObject / Numpy.ndarray<bool>): Predicate set ty (W...
Returns a new array with each element in the original array satisfying the passed - in predicate set to new_value
def pivot_filter(pivot_array, predicates, ty=None): """ Returns a new array, with each element in the original array satisfying the passed-in predicate set to `new_value` Args: array (WeldObject / Numpy.ndarray): Input array predicates (WeldObject / Numpy.ndarray<bool>): Predicate set ...
Operation of series and other element - wise ( binary operator add )
def element_wise_op(array, other, op, ty): """ Operation of series and other, element-wise (binary operator add) Args: array (WeldObject / Numpy.ndarray): Input array other (WeldObject / Numpy.ndarray): Second Input array op (str): Op string used to compute element-wise operation (+...
Zip together multiple columns.
def unzip_columns(expr, column_types): """ Zip together multiple columns. Args: columns (WeldObject / Numpy.ndarray): lust of columns Returns: A WeldObject representing this computation """ weld_obj = WeldObject(encoder_, decoder_) column_appenders = [] struct_fields = ...
Sorts the vector. If the field parameter is provided then the sort operators on a vector of structs where the sort key is the field of the struct.
def sort(expr, field = None, keytype=None, ascending=True): """ Sorts the vector. If the field parameter is provided then the sort operators on a vector of structs where the sort key is the field of the struct. Args: expr (WeldObject) field (Int) """ weld_obj = WeldObject(en...
Slices the vector.
def slice_vec(expr, start, stop): """ Slices the vector. Args: expr (WeldObject) start (Long) stop (Long) """ weld_obj = WeldObject(encoder_, decoder_) expr_var = weld_obj.update(expr) if isinstance(expr, WeldObject): expr_var = expr.obj_id weld_obj.depend...
Zip together multiple columns.
def zip_columns(columns): """ Zip together multiple columns. Args: columns (WeldObject / Numpy.ndarray): lust of columns Returns: A WeldObject representing this computation """ weld_obj = WeldObject(encoder_, decoder_) column_vars = [] for column in columns: col...