sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run_friedman_smooth(x, y, span): """Run the FORTRAN smoother.""" N = len(x) weight = numpy.ones(N) results = numpy.zeros(N) residuals = numpy.zeros(N) mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals) return results, residuals
Run the FORTRAN smoother.
entailment
def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument """Run the FORTRAN SMOTHR.""" N = len(x) weight = numpy.ones(N) results = numpy.zeros(N) flags = numpy.zeros((N, 7)) mace.smothr(1, x, y, weight, results, flags) return results
Run the FORTRAN SMOTHR.
entailment
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
Sort the data.
entailment
def compute(self): """Run smoother.""" self.smooth_result, self.cross_validated_residual = run_friedman_smooth( self.x, self.y, self._span )
Run smoother.
entailment
def compute(self): """Run SuperSmoother.""" self.smooth_result = run_freidman_supsmu(self.x, self.y) self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result)))
Run SuperSmoother.
entailment
def _get_conn(self, host, port): """Get or create a connection to a broker using host and port""" host_key = (host, port) if host_key not in self.conns: self.conns[host_key] = KafkaConnection( host, port, timeout=self.timeout ) return self.conns[host_key]
Get or create a connection to a broker using host and port
entailment
def _get_coordinator_for_group(self, group): """ Returns the coordinator broker for a consumer group. ConsumerCoordinatorNotAvailableCode will be raised if the coordinator does not currently exist for the group. OffsetsLoadInProgressCode is raised if the coordinator is available but is still loading offsets from the internal topic """ resp = self.send_consumer_metadata_request(group) # If there's a problem with finding the coordinator, raise the # provided error kafka_common.check_error(resp) # Otherwise return the BrokerMetadata return BrokerMetadata(resp.nodeId, resp.host, resp.port)
Returns the coordinator broker for a consumer group. ConsumerCoordinatorNotAvailableCode will be raised if the coordinator does not currently exist for the group. OffsetsLoadInProgressCode is raised if the coordinator is available but is still loading offsets from the internal topic
entailment
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn): """ Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed. """ for (host, port) in self.hosts: requestId = self._next_id() log.debug('Request %s: %s', requestId, payloads) try: conn = self._get_conn(host, port) request = encoder_fn(client_id=self.client_id, correlation_id=requestId, payloads=payloads) conn.send(requestId, request) response = conn.recv(requestId) decoded = decoder_fn(response) log.debug('Response %s: %s', requestId, decoded) return decoded except Exception: log.exception('Error sending request [%s] to server %s:%s, ' 'trying next server', requestId, host, port) raise KafkaUnavailableError('All servers failed to process request')
Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed.
entailment
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn): """ Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like entities with a topic (str) and partition (int) attribute; payloads with duplicate topic-partitions are not supported. encode_fn: a method to encode the list of payloads to a request body, must accept client_id, correlation_id, and payloads as keyword arguments decode_fn: a method to decode a response body into response objects. The response objects must be object-like and have topic and partition attributes Returns: List of response objects in the same order as the supplied payloads """ # encoders / decoders do not maintain ordering currently # so we need to keep this so we can rebuild order before returning original_ordering = [(p.topic, p.partition) for p in payloads] # Group the requests by topic+partition brokers_for_payloads = [] payloads_by_broker = collections.defaultdict(list) responses = {} for payload in payloads: try: leader = self._get_leader_for_partition(payload.topic, payload.partition) payloads_by_broker[leader].append(payload) brokers_for_payloads.append(leader) except KafkaUnavailableError as e: log.warning('KafkaUnavailableError attempting to send request ' 'on topic %s partition %d', payload.topic, payload.partition) topic_partition = (payload.topic, payload.partition) responses[topic_partition] = FailedPayloadsError(payload) # For each broker, send the list of request payloads # and collect the responses and errors broker_failures = [] # For each KafkaConnection keep the real socket so that we can use # a select to perform unblocking I/O connections_by_socket = {} for broker, payloads in payloads_by_broker.items(): requestId = self._next_id() log.debug('Request %s to %s: %s', requestId, broker, payloads) request = encoder_fn(client_id=self.client_id, correlation_id=requestId, payloads=payloads) # Send the request, recv the response try: conn = self._get_conn(broker.host.decode('utf-8'), broker.port) conn.send(requestId, request) except ConnectionError as e: broker_failures.append(broker) log.warning('ConnectionError attempting to send request %s ' 'to server %s: %s', requestId, broker, e) for payload in payloads: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = FailedPayloadsError(payload) # No exception, try to get response else: # decoder_fn=None signal that the server is expected to not # send a response. This probably only applies to # ProduceRequest w/ acks = 0 if decoder_fn is None: log.debug('Request %s does not expect a response ' '(skipping conn.recv)', requestId) for payload in payloads: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = None continue else: connections_by_socket[conn.get_connected_socket()] = (conn, broker, requestId) conn = None while connections_by_socket: sockets = connections_by_socket.keys() rlist, _, _ = select.select(sockets, [], [], None) conn, broker, requestId = connections_by_socket.pop(rlist[0]) try: response = conn.recv(requestId) except ConnectionError as e: broker_failures.append(broker) log.warning('ConnectionError attempting to receive a ' 'response to request %s from server %s: %s', requestId, broker, e) for payload in payloads_by_broker[broker]: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = FailedPayloadsError(payload) else: _resps = [] for payload_response in decoder_fn(response): topic_partition = (payload_response.topic, payload_response.partition) responses[topic_partition] = payload_response _resps.append(payload_response) log.debug('Response %s: %s', requestId, _resps) # Connection errors generally mean stale metadata # although sometimes it means incorrect api request # Unfortunately there is no good way to tell the difference # so we'll just reset metadata on all errors to be safe if broker_failures: self.reset_all_metadata() # Return responses in the same order as provided return [responses[tp] for tp in original_ordering]
Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like entities with a topic (str) and partition (int) attribute; payloads with duplicate topic-partitions are not supported. encode_fn: a method to encode the list of payloads to a request body, must accept client_id, correlation_id, and payloads as keyword arguments decode_fn: a method to decode a response body into response objects. The response objects must be object-like and have topic and partition attributes Returns: List of response objects in the same order as the supplied payloads
entailment
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn): """ Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. OffsetFetchRequest), all payloads must be for a single group. Arguments: group: the name of the consumer group (str) the payloads are for payloads: list of object-like entities with topic (str) and partition (int) attributes; payloads with duplicate topic+partition are not supported. encode_fn: a method to encode the list of payloads to a request body, must accept client_id, correlation_id, and payloads as keyword arguments decode_fn: a method to decode a response body into response objects. The response objects must be object-like and have topic and partition attributes Returns: List of response objects in the same order as the supplied payloads """ # encoders / decoders do not maintain ordering currently # so we need to keep this so we can rebuild order before returning original_ordering = [(p.topic, p.partition) for p in payloads] broker = self._get_coordinator_for_group(group) # Send the list of request payloads and collect the responses and # errors responses = {} requestId = self._next_id() log.debug('Request %s to %s: %s', requestId, broker, payloads) request = encoder_fn(client_id=self.client_id, correlation_id=requestId, payloads=payloads) # Send the request, recv the response try: conn = self._get_conn(broker.host.decode('utf-8'), broker.port) conn.send(requestId, request) except ConnectionError as e: log.warning('ConnectionError attempting to send request %s ' 'to server %s: %s', requestId, broker, e) for payload in payloads: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = FailedPayloadsError(payload) # No exception, try to get response else: # decoder_fn=None signal that the server is expected to not # send a response. This probably only applies to # ProduceRequest w/ acks = 0 if decoder_fn is None: log.debug('Request %s does not expect a response ' '(skipping conn.recv)', requestId) for payload in payloads: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = None return [] try: response = conn.recv(requestId) except ConnectionError as e: log.warning('ConnectionError attempting to receive a ' 'response to request %s from server %s: %s', requestId, broker, e) for payload in payloads: topic_partition = (payload.topic, payload.partition) responses[topic_partition] = FailedPayloadsError(payload) else: _resps = [] for payload_response in decoder_fn(response): topic_partition = (payload_response.topic, payload_response.partition) responses[topic_partition] = payload_response _resps.append(payload_response) log.debug('Response %s: %s', requestId, _resps) # Return responses in the same order as provided return [responses[tp] for tp in original_ordering]
Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. OffsetFetchRequest), all payloads must be for a single group. Arguments: group: the name of the consumer group (str) the payloads are for payloads: list of object-like entities with topic (str) and partition (int) attributes; payloads with duplicate topic+partition are not supported. encode_fn: a method to encode the list of payloads to a request body, must accept client_id, correlation_id, and payloads as keyword arguments decode_fn: a method to decode a response body into response objects. The response objects must be object-like and have topic and partition attributes Returns: List of response objects in the same order as the supplied payloads
entailment
def copy(self): """ Create an inactive copy of the client object, suitable for passing to a separate thread. Note that the copied connections are not initialized, so reinit() must be called on the returned copy. """ c = copy.deepcopy(self) for key in c.conns: c.conns[key] = self.conns[key].copy() return c
Create an inactive copy of the client object, suitable for passing to a separate thread. Note that the copied connections are not initialized, so reinit() must be called on the returned copy.
entailment
def load_metadata_for_topics(self, *topics): """ Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: *topics (optional): If a list of topics is provided, the metadata refresh will be limited to the specified topics only. Exceptions: ---------- If the broker is configured to not auto-create topics, expect UnknownTopicOrPartitionError for topics that don't exist If the broker is configured to auto-create topics, expect LeaderNotAvailableError for new topics until partitions have been initialized. Exceptions *will not* be raised in a full refresh (i.e. no topic list) In this case, error codes will be logged as errors Partition-level errors will also not be raised here (a single partition w/o a leader, for example) """ topics = [kafka_bytestring(t) for t in topics] if topics: for topic in topics: self.reset_topic_metadata(topic) else: self.reset_all_metadata() resp = self.send_metadata_request(topics) log.debug('Updating broker metadata: %s', resp.brokers) log.debug('Updating topic metadata: %s', resp.topics) self.brokers = dict([(broker.nodeId, broker) for broker in resp.brokers]) for topic_metadata in resp.topics: topic = topic_metadata.topic partitions = topic_metadata.partitions # Errors expected for new topics try: kafka_common.check_error(topic_metadata) except (UnknownTopicOrPartitionError, LeaderNotAvailableError) as e: # Raise if the topic was passed in explicitly if topic in topics: raise # Otherwise, just log a warning log.error('Error loading topic metadata for %s: %s', topic, type(e)) continue self.topic_partitions[topic] = {} for partition_metadata in partitions: partition = partition_metadata.partition leader = partition_metadata.leader self.topic_partitions[topic][partition] = partition_metadata # Populate topics_to_brokers dict topic_part = TopicAndPartition(topic, partition) # Check for partition errors try: kafka_common.check_error(partition_metadata) # If No Leader, topics_to_brokers topic_partition -> None except LeaderNotAvailableError: log.error('No leader for topic %s partition %d', topic, partition) self.topics_to_brokers[topic_part] = None continue # If one of the replicas is unavailable -- ignore # this error code is provided for admin purposes only # we never talk to replicas, only the leader except ReplicaNotAvailableError: log.debug('Some (non-leader) replicas not available for topic %s partition %d', topic, partition) # If Known Broker, topic_partition -> BrokerMetadata if leader in self.brokers: self.topics_to_brokers[topic_part] = self.brokers[leader] # If Unknown Broker, fake BrokerMetadata so we dont lose the id # (not sure how this could happen. server could be in bad state) else: self.topics_to_brokers[topic_part] = BrokerMetadata( leader, None, None )
Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: *topics (optional): If a list of topics is provided, the metadata refresh will be limited to the specified topics only. Exceptions: ---------- If the broker is configured to not auto-create topics, expect UnknownTopicOrPartitionError for topics that don't exist If the broker is configured to auto-create topics, expect LeaderNotAvailableError for new topics until partitions have been initialized. Exceptions *will not* be raised in a full refresh (i.e. no topic list) In this case, error codes will be logged as errors Partition-level errors will also not be raised here (a single partition w/o a leader, for example)
entailment
def _partition(self): """Consume messages from kafka Consume messages from kafka using the Kazoo SetPartitioner to allow multiple consumer processes to negotiate access to the kafka partitions """ # KazooClient and SetPartitioner objects need to be instantiated after # the consumer process has forked. Instantiating prior to forking # gives the appearance that things are working but after forking the # connection to zookeeper is lost and no state changes are visible if not self._kazoo_client: self._kazoo_client = KazooClient(hosts=self._zookeeper_url) self._kazoo_client.start() state_change_event = threading.Event() self._set_partitioner = ( SetPartitioner(self._kazoo_client, path=self._zookeeper_path, set=self._consumer.fetch_offsets.keys(), state_change_event=state_change_event, identifier=str(datetime.datetime.now()))) try: while 1: if self._set_partitioner.failed: raise Exception("Failed to acquire partition") elif self._set_partitioner.release: log.info("Releasing locks on partition set {} " "for topic {}".format(self._partitions, self._kafka_topic)) self._set_partitioner.release_set() self._partitions = [] elif self._set_partitioner.acquired: if not self._partitions: self._partitions = [p for p in self._set_partitioner] if not self._partitions: log.info("Not assigned any partitions on topic {}," " waiting for a Partitioner state change" .format(self._kafka_topic)) state_change_event.wait() state_change_event.clear() continue log.info("Acquired locks on partition set {} " "for topic {}".format(self._partitions, self._kafka_topic)) # Reconstruct the kafka consumer object because the # consumer has no API that allows the set of partitons # to be updated outside of construction. self._consumer.stop() self._consumer = self._create_kafka_consumer(self._partitions) return elif self._set_partitioner.allocating: log.info("Waiting to acquire locks on partition set") self._set_partitioner.wait_for_acquire() except Exception: log.exception('KafkaConsumer encountered fatal exception ' 'processing messages.') raise
Consume messages from kafka Consume messages from kafka using the Kazoo SetPartitioner to allow multiple consumer processes to negotiate access to the kafka partitions
entailment
def drive(self, speed, rotation_speed, tm_diff): """Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. You can either calculate the speed & rotation manually, or you can use the predefined functions in :mod:`pyfrc.physics.drivetrains`. The outputs of the `drivetrains.*` functions should be passed to this function. .. note:: The simulator currently only allows 2D motion :param speed: Speed of robot in ft/s :param rotation_speed: Clockwise rotational speed in radians/s :param tm_diff: Amount of time speed was traveled (this is the same value that was passed to update_sim) """ # if the robot is disabled, don't do anything if not self.robot_enabled: return distance = speed * tm_diff angle = rotation_speed * tm_diff x = distance * math.cos(angle) y = distance * math.sin(angle) self.distance_drive(x, y, angle)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. You can either calculate the speed & rotation manually, or you can use the predefined functions in :mod:`pyfrc.physics.drivetrains`. The outputs of the `drivetrains.*` functions should be passed to this function. .. note:: The simulator currently only allows 2D motion :param speed: Speed of robot in ft/s :param rotation_speed: Clockwise rotational speed in radians/s :param tm_diff: Amount of time speed was traveled (this is the same value that was passed to update_sim)
entailment
def vector_drive(self, vx, vy, vw, tm_diff): """Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation speed. :param vx: Speed in x direction relative to robot in ft/s :param vy: Speed in y direction relative to robot in ft/s :param vw: Clockwise rotational speed in rad/s :param tm_diff: Amount of time speed was traveled """ # if the robot is disabled, don't do anything if not self.robot_enabled: return angle = vw * tm_diff vx = vx * tm_diff vy = vy * tm_diff x = vx * math.sin(angle) + vy * math.cos(angle) y = vx * math.cos(angle) + vy * math.sin(angle) self.distance_drive(x, y, angle)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation speed. :param vx: Speed in x direction relative to robot in ft/s :param vy: Speed in y direction relative to robot in ft/s :param vw: Clockwise rotational speed in rad/s :param tm_diff: Amount of time speed was traveled
entailment
def distance_drive(self, x, y, angle): """Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot some relative distance and angle from its current position. :param x: Feet to move the robot in the x direction :param y: Feet to move the robot in the y direction :param angle: Radians to turn the robot """ with self._lock: self.vx += x self.vy += y self.angle += angle c = math.cos(self.angle) s = math.sin(self.angle) self.x += x * c - y * s self.y += x * s + y * c self._update_gyros(angle)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot some relative distance and angle from its current position. :param x: Feet to move the robot in the x direction :param y: Feet to move the robot in the y direction :param angle: Radians to turn the robot
entailment
def get_position(self): """ :returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians """ with self._lock: return self.x, self.y, self.angle
:returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians
entailment
def get_offset(self, x, y): """ Computes how far away and at what angle a coordinate is located. Distance is returned in feet, angle is returned in degrees :returns: distance,angle offset of the given x,y coordinate .. versionadded:: 2018.1.7 """ with self._lock: dx = self.x - x dy = self.y - y distance = math.hypot(dx, dy) angle = math.atan2(dy, dx) return distance, math.degrees(angle)
Computes how far away and at what angle a coordinate is located. Distance is returned in feet, angle is returned in degrees :returns: distance,angle offset of the given x,y coordinate .. versionadded:: 2018.1.7
entailment
def _check_sleep(self, idx): """This ensures that the robot code called Wait() at some point""" # TODO: There are some cases where it would be ok to do this... if not self.fake_time.slept[idx]: errstr = ( "%s() function is not calling wpilib.Timer.delay() in its loop!" % self.mode_map[self.mode] ) raise RuntimeError(errstr) self.fake_time.slept[idx] = False
This ensures that the robot code called Wait() at some point
entailment
def linear_deadzone(deadzone: float) -> DeadzoneCallable: """ Real motors won't actually move unless you give them some minimum amount of input. This computes an output speed for a motor and causes it to 'not move' if the input isn't high enough. Additionally, the output is adjusted linearly to compensate. Example: For a deadzone of 0.2: * Input of 0.0 will result in 0.0 * Input of 0.2 will result in 0.0 * Input of 0.3 will result in ~0.12 * Input of 1.0 will result in 1.0 This returns a function that computes the deadzone. You should pass the returned function to one of the drivetrain simulation functions as the ``deadzone`` parameter. :param motor_input: The motor input (between -1 and 1) :param deadzone: Minimum input required for the motor to move (between 0 and 1) """ assert 0.0 < deadzone < 1.0 scale_param = 1.0 - deadzone def _linear_deadzone(motor_input): abs_motor_input = abs(motor_input) if abs_motor_input < deadzone: return 0.0 else: return math.copysign( (abs_motor_input - deadzone) / scale_param, motor_input ) return _linear_deadzone
Real motors won't actually move unless you give them some minimum amount of input. This computes an output speed for a motor and causes it to 'not move' if the input isn't high enough. Additionally, the output is adjusted linearly to compensate. Example: For a deadzone of 0.2: * Input of 0.0 will result in 0.0 * Input of 0.2 will result in 0.0 * Input of 0.3 will result in ~0.12 * Input of 1.0 will result in 1.0 This returns a function that computes the deadzone. You should pass the returned function to one of the drivetrain simulation functions as the ``deadzone`` parameter. :param motor_input: The motor input (between -1 and 1) :param deadzone: Minimum input required for the motor to move (between 0 and 1)
entailment
def two_motor_drivetrain(l_motor, r_motor, x_wheelbase=2, speed=5, deadzone=None): """ .. deprecated:: 2018.2.0 Use :class:`TwoMotorDrivetrain` instead """ return TwoMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector(l_motor, r_motor)
.. deprecated:: 2018.2.0 Use :class:`TwoMotorDrivetrain` instead
entailment
def four_motor_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, speed=5, deadzone=None ): """ .. deprecated:: 2018.2.0 Use :class:`FourMotorDrivetrain` instead """ return FourMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector( lr_motor, rr_motor, lf_motor, rf_motor )
.. deprecated:: 2018.2.0 Use :class:`FourMotorDrivetrain` instead
entailment
def mecanum_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, y_wheelbase=3, speed=5, deadzone=None, ): """ .. deprecated:: 2018.2.0 Use :class:`MecanumDrivetrain` instead """ return MecanumDrivetrain(x_wheelbase, y_wheelbase, speed, deadzone).get_vector( lr_motor, rr_motor, lf_motor, rf_motor )
.. deprecated:: 2018.2.0 Use :class:`MecanumDrivetrain` instead
entailment
def four_motor_swerve_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, lr_angle, rr_angle, lf_angle, rf_angle, x_wheelbase=2, y_wheelbase=2, speed=5, deadzone=None, ): """ Four motors that can be rotated in any direction If any motors are inverted, then you will need to multiply that motor's value by -1. :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); 1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :param lr_angle: Left rear motor angle in degrees (0 to 360 measured clockwise from forward position) :param rr_angle: Right rear motor angle in degrees (0 to 360 measured clockwise from forward position) :param lf_angle: Left front motor angle in degrees (0 to 360 measured clockwise from forward position) :param rf_angle: Right front motor angle in degrees (0 to 360 measured clockwise from forward position) :param x_wheelbase: The distance in feet between right and left wheels. :param y_wheelbase: The distance in feet between forward and rear wheels. :param speed: Speed of robot in feet per second (see above) :param deadzone: A function that adjusts the output of the motor (see :func:`linear_deadzone`) :returns: Speed of robot in x (ft/s), Speed of robot in y (ft/s), clockwise rotation of robot (radians/s) """ if deadzone: lf_motor = deadzone(lf_motor) lr_motor = deadzone(lr_motor) rf_motor = deadzone(rf_motor) rr_motor = deadzone(rr_motor) # Calculate speed of each wheel lr = lr_motor * speed rr = rr_motor * speed lf = lf_motor * speed rf = rf_motor * speed # Calculate angle in radians lr_rad = math.radians(lr_angle) rr_rad = math.radians(rr_angle) lf_rad = math.radians(lf_angle) rf_rad = math.radians(rf_angle) # Calculate wheelbase radius wheelbase_radius = math.hypot(x_wheelbase / 2.0, y_wheelbase / 2.0) # Calculates the Vx and Vy components # Sin an Cos inverted because forward is 0 on swerve wheels Vx = ( (math.sin(lr_rad) * lr) + (math.sin(rr_rad) * rr) + (math.sin(lf_rad) * lf) + (math.sin(rf_rad) * rf) ) Vy = ( (math.cos(lr_rad) * lr) + (math.cos(rr_rad) * rr) + (math.cos(lf_rad) * lf) + (math.cos(rf_rad) * rf) ) # Adjusts the angle corresponding to a diameter that is perpendicular to the radius (add or subtract 45deg) lr_rad = (lr_rad + (math.pi / 4)) % (2 * math.pi) rr_rad = (rr_rad - (math.pi / 4)) % (2 * math.pi) lf_rad = (lf_rad - (math.pi / 4)) % (2 * math.pi) rf_rad = (rf_rad + (math.pi / 4)) % (2 * math.pi) # Finds the rotational velocity by finding the torque and adding them up Vw = wheelbase_radius * ( (math.cos(lr_rad) * lr) + (math.cos(rr_rad) * -rr) + (math.cos(lf_rad) * lf) + (math.cos(rf_rad) * -rf) ) Vx *= 0.25 Vy *= 0.25 Vw *= 0.25 return Vx, Vy, Vw
Four motors that can be rotated in any direction If any motors are inverted, then you will need to multiply that motor's value by -1. :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); 1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :param lr_angle: Left rear motor angle in degrees (0 to 360 measured clockwise from forward position) :param rr_angle: Right rear motor angle in degrees (0 to 360 measured clockwise from forward position) :param lf_angle: Left front motor angle in degrees (0 to 360 measured clockwise from forward position) :param rf_angle: Right front motor angle in degrees (0 to 360 measured clockwise from forward position) :param x_wheelbase: The distance in feet between right and left wheels. :param y_wheelbase: The distance in feet between forward and rear wheels. :param speed: Speed of robot in feet per second (see above) :param deadzone: A function that adjusts the output of the motor (see :func:`linear_deadzone`) :returns: Speed of robot in x (ft/s), Speed of robot in y (ft/s), clockwise rotation of robot (radians/s)
entailment
def get_vector(self, l_motor: float, r_motor: float) -> typing.Tuple[float, float]: """ Given motor values, retrieves the vector of (distance, speed) for your robot :param l_motor: Left motor value (-1 to 1); -1 is forward :param r_motor: Right motor value (-1 to 1); 1 is forward :returns: speed of robot (ft/s), clockwise rotation of robot (radians/s) """ if self.deadzone: l_motor = self.deadzone(l_motor) r_motor = self.deadzone(r_motor) l = -l_motor * self.speed r = r_motor * self.speed # Motion equations fwd = (l + r) * 0.5 rcw = (l - r) / float(self.x_wheelbase) self.l_speed = l self.r_speed = r return fwd, rcw
Given motor values, retrieves the vector of (distance, speed) for your robot :param l_motor: Left motor value (-1 to 1); -1 is forward :param r_motor: Right motor value (-1 to 1); 1 is forward :returns: speed of robot (ft/s), clockwise rotation of robot (radians/s)
entailment
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float]: """ :param lr_motor: Left rear motor value (-1 to 1); -1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); -1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :returns: speed of robot (ft/s), clockwise rotation of robot (radians/s) """ if self.deadzone: lf_motor = self.deadzone(lf_motor) lr_motor = self.deadzone(lr_motor) rf_motor = self.deadzone(rf_motor) rr_motor = self.deadzone(rr_motor) l = -(lf_motor + lr_motor) * 0.5 * self.speed r = (rf_motor + rr_motor) * 0.5 * self.speed # Motion equations fwd = (l + r) * 0.5 rcw = (l - r) / float(self.x_wheelbase) self.l_speed = l self.r_speed = r return fwd, rcw
:param lr_motor: Left rear motor value (-1 to 1); -1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); -1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :returns: speed of robot (ft/s), clockwise rotation of robot (radians/s)
entailment
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float, float]: """ Given motor values, retrieves the vector of (distance, speed) for your robot :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); 1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :returns: Speed of robot in x (ft/s), Speed of robot in y (ft/s), clockwise rotation of robot (radians/s) """ # # From http://www.chiefdelphi.com/media/papers/download/2722 pp7-9 # [F] [omega](r) = [V] # # F is # .25 .25 .25 .25 # -.25 .25 -.25 .25 # -.25k -.25k .25k .25k # # omega is # [lf lr rr rf] if self.deadzone: lf_motor = self.deadzone(lf_motor) lr_motor = self.deadzone(lr_motor) rf_motor = self.deadzone(rf_motor) rr_motor = self.deadzone(rr_motor) # Calculate speed of each wheel lr = lr_motor * self.speed rr = rr_motor * self.speed lf = lf_motor * self.speed rf = rf_motor * self.speed # Calculate K k = abs(self.x_wheelbase / 2.0) + abs(self.y_wheelbase / 2.0) # Calculate resulting motion Vy = 0.25 * (lf + lr + rr + rf) Vx = 0.25 * (lf + -lr + rr + -rf) Vw = (0.25 / k) * (lf + lr + -rr + -rf) self.lr_speed = lr self.rr_speed = rr self.lf_speed = lf self.rf_speed = rf return Vx, Vy, Vw
Given motor values, retrieves the vector of (distance, speed) for your robot :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); 1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward :returns: Speed of robot in x (ft/s), Speed of robot in y (ft/s), clockwise rotation of robot (radians/s)
entailment
def connect_mysql(host, port, user, password, database): """Connect to MySQL with retries.""" return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
Connect to MySQL with retries.
entailment
def main(): """Start main part of the wait script.""" logger.info('Waiting for database: `%s`', MYSQL_DB) connect_mysql( host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DB ) logger.info('Database `%s` found', MYSQL_DB)
Start main part of the wait script.
entailment
def unsort_vector(data, indices_of_increasing): """Upermutate 1-D data that is sorted by indices_of_increasing.""" return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])
Upermutate 1-D data that is sorted by indices_of_increasing.
entailment
def plot_transforms(ace_model, fname='ace_transforms.png'): """Plot the transforms.""" if not plt: raise ImportError('Cannot plot without the matplotlib package') plt.rcParams.update({'font.size': 8}) plt.figure() num_cols = len(ace_model.x) / 2 + 1 for i in range(len(ace_model.x)): plt.subplot(num_cols, 2, i + 1) plt.plot(ace_model.x[i], ace_model.x_transforms[i], '.', label='Phi {0}'.format(i)) plt.xlabel('x{0}'.format(i)) plt.ylabel('phi{0}'.format(i)) plt.subplot(num_cols, 2, i + 2) # pylint: disable=undefined-loop-variable plt.plot(ace_model.y, ace_model.y_transform, '.', label='Theta') plt.xlabel('y') plt.ylabel('theta') plt.tight_layout() if fname: plt.savefig(fname) return None return plt
Plot the transforms.
entailment
def plot_input(ace_model, fname='ace_input.png'): """Plot the transforms.""" if not plt: raise ImportError('Cannot plot without the matplotlib package') plt.rcParams.update({'font.size': 8}) plt.figure() num_cols = len(ace_model.x) / 2 + 1 for i in range(len(ace_model.x)): plt.subplot(num_cols, 2, i + 1) plt.plot(ace_model.x[i], ace_model.y, '.') plt.xlabel('x{0}'.format(i)) plt.ylabel('y') plt.tight_layout() if fname: plt.savefig(fname) else: plt.show()
Plot the transforms.
entailment
def specify_data_set(self, x_input, y_input): """ Define input to ACE. Parameters ---------- x_input : list list of iterables, one for each independent variable y_input : array the dependent observations """ self.x = x_input self.y = y_input
Define input to ACE. Parameters ---------- x_input : list list of iterables, one for each independent variable y_input : array the dependent observations
entailment
def solve(self): """Run the ACE calculational loop.""" self._initialize() while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS: print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._outer_iters, self._last_outer_error)) self._iterate_to_update_x_transforms() self._update_y_transform() self._outer_iters += 1
Run the ACE calculational loop.
entailment
def _initialize(self): """Set up and normalize initial data once input data is specified.""" self.y_transform = self.y - numpy.mean(self.y) self.y_transform /= numpy.std(self.y_transform) self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x] self._compute_sorted_indices()
Set up and normalize initial data once input data is specified.
entailment
def _compute_sorted_indices(self): """ The smoothers need sorted data. This sorts it from the perspective of each column. if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8 We only have to sort the data once. """ sorted_indices = [] for to_sort in [self.y] + self.x: data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)] data_w_indices.sort() sorted_indices.append([i for val, i in data_w_indices]) # save in meaningful variable names self._yi_sorted = sorted_indices[0] # list (like self.y) self._xi_sorted = sorted_indices[1:]
The smoothers need sorted data. This sorts it from the perspective of each column. if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8 We only have to sort the data once.
entailment
def _outer_error_is_decreasing(self): """True if outer iteration error is decreasing.""" is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error) return is_decreasing
True if outer iteration error is decreasing.
entailment
def _error_is_decreasing(self, last_error): """True if current error is less than last_error.""" current_error = self._compute_error() is_decreasing = current_error < last_error return is_decreasing, current_error
True if current error is less than last_error.
entailment
def _compute_error(self): """Compute unexplained error.""" sum_x = sum(self.x_transforms) err = sum((self.y_transform - sum_x) ** 2) / len(sum_x) return err
Compute unexplained error.
entailment
def _iterate_to_update_x_transforms(self): """Perform the inner iteration.""" self._inner_iters = 0 self._last_inner_error = float('inf') while self._inner_error_is_decreasing(): print(' Starting inner iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._inner_iters, self._last_inner_error)) self._update_x_transforms() self._inner_iters += 1
Perform the inner iteration.
entailment
def _update_x_transforms(self): """ Compute a new set of x-transform functions phik. phik(xk) = theta(y) - sum of phii(xi) over i!=k This is the first of the eponymous conditional expectations. The conditional expectations are computed using the SuperSmoother. """ # start by subtracting all transforms theta_minus_phis = self.y_transform - numpy.sum(self.x_transforms, axis=0) # add one transform at a time so as to exclude it from the subtracted sum for xtransform_index in range(len(self.x_transforms)): xtransform = self.x_transforms[xtransform_index] sorted_data_indices = self._xi_sorted[xtransform_index] xk_sorted = sort_vector(self.x[xtransform_index], sorted_data_indices) xtransform_sorted = sort_vector(xtransform, sorted_data_indices) theta_minus_phis_sorted = sort_vector(theta_minus_phis, sorted_data_indices) # minimize sums by just adding in the phik where i!=k here. to_smooth = theta_minus_phis_sorted + xtransform_sorted smoother = perform_smooth(xk_sorted, to_smooth, smoother_cls=self._smoother_cls) updated_x_transform_smooth = smoother.smooth_result updated_x_transform_smooth -= numpy.mean(updated_x_transform_smooth) # store updated transform in the order of the original data unsorted_xt = unsort_vector(updated_x_transform_smooth, sorted_data_indices) self.x_transforms[xtransform_index] = unsorted_xt # update main expession with new smooth. This was done in the original FORTRAN tmp_unsorted = unsort_vector(to_smooth, sorted_data_indices) theta_minus_phis = tmp_unsorted - unsorted_xt
Compute a new set of x-transform functions phik. phik(xk) = theta(y) - sum of phii(xi) over i!=k This is the first of the eponymous conditional expectations. The conditional expectations are computed using the SuperSmoother.
entailment
def _update_y_transform(self): """ Update the y-transform (theta). y-transform theta is forced to have mean = 0 and stddev = 1. This is the second conditional expectation """ # sort all phis wrt increasing y. sorted_data_indices = self._yi_sorted sorted_xtransforms = [] for xt in self.x_transforms: sorted_xt = sort_vector(xt, sorted_data_indices) sorted_xtransforms.append(sorted_xt) sum_of_x_transformations_choppy = numpy.sum(sorted_xtransforms, axis=0) y_sorted = sort_vector(self.y, sorted_data_indices) smooth = perform_smooth(y_sorted, sum_of_x_transformations_choppy, smoother_cls=self._smoother_cls) sum_of_x_transformations_smooth = smooth.smooth_result sum_of_x_transformations_smooth -= numpy.mean(sum_of_x_transformations_smooth) sum_of_x_transformations_smooth /= numpy.std(sum_of_x_transformations_smooth) # unsort to save in the original data self.y_transform = unsort_vector(sum_of_x_transformations_smooth, sorted_data_indices)
Update the y-transform (theta). y-transform theta is forced to have mean = 0 and stddev = 1. This is the second conditional expectation
entailment
def write_input_to_file(self, fname='ace_input.txt'): """Write y and x values used in this run to a space-delimited txt file.""" self._write_columns(fname, self.x, self.y)
Write y and x values used in this run to a space-delimited txt file.
entailment
def write_transforms_to_file(self, fname='ace_transforms.txt'): """Write y and x transforms used in this run to a space-delimited txt file.""" self._write_columns(fname, self.x_transforms, self.y_transform)
Write y and x transforms used in this run to a space-delimited txt file.
entailment
def build_sample_smoother_problem_friedman82(N=200): """Sample problem from supersmoother publication.""" x = numpy.random.uniform(size=N) err = numpy.random.standard_normal(N) y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err return x, y
Sample problem from supersmoother publication.
entailment
def run_friedman82_basic(): """Run Friedman's test of fixed-span smoothers from Figure 2b.""" x, y = build_sample_smoother_problem_friedman82() plt.figure() # plt.plot(x, y, '.', label='Data') for span in smoother.DEFAULT_SPANS: smooth = smoother.BasicFixedSpanSmoother() smooth.specify_data_set(x, y, sort_data=True) smooth.set_span(span) smooth.compute() plt.plot(x, smooth.smooth_result, '.', label='span = {0}'.format(span)) plt.legend(loc='upper left') plt.grid(color='0.7') plt.xlabel('x') plt.ylabel('y') plt.title('Demo of fixed-span smoothers from Friedman 82') plt.savefig('sample_friedman82.png') return smooth
Run Friedman's test of fixed-span smoothers from Figure 2b.
entailment
def add_moving_element(self, element): """Add elements to the board""" element.initialize(self.canvas) self.elements.append(element)
Add elements to the board
entailment
def on_key_pressed(self, event): """ likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet """ return # TODO if event.keysym == "Up": self.manager.set_joystick(0.0, -1.0, 0) elif event.keysym == "Down": self.manager.set_joystick(0.0, 1.0, 0) elif event.keysym == "Left": self.manager.set_joystick(-1.0, 0.0, 0) elif event.keysym == "Right": self.manager.set_joystick(1.0, 0.0, 0) elif event.char == " ": mode = self.manager.get_mode() if mode == self.manager.MODE_DISABLED: self.manager.set_mode(self.manager.MODE_OPERATOR_CONTROL) else: self.manager.set_mode(self.manager.MODE_DISABLED)
likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet
entailment
def _load_config(robot_path): """ Used internally by pyfrc, don't call this directly. Loads a json file from sim/config.json and makes the information available to simulation/testing code. """ from . import config config_obj = config.config_obj sim_path = join(robot_path, "sim") config_file = join(sim_path, "config.json") if exists(config_file): with open(config_file, "r") as fp: config_obj.update(json.load(fp)) else: logger.warning("sim/config.json not found, using default simulation parameters") config_obj["simpath"] = sim_path # setup defaults config_obj.setdefault("pyfrc", {}) config_obj["pyfrc"].setdefault("robot", {}) config_obj["pyfrc"]["robot"].setdefault("w", 2) # switched from 'h' to 'l' in 2018, but keeping it there for legacy reasons l = config_obj["pyfrc"]["robot"].get("h", 3) config_obj["pyfrc"]["robot"].setdefault("l", l) config_obj["pyfrc"]["robot"].setdefault("starting_x", 0) config_obj["pyfrc"]["robot"].setdefault("starting_y", 0) config_obj["pyfrc"]["robot"].setdefault("starting_angle", 0) # list of dictionaries of x=, y=, angle=, name= config_obj["pyfrc"]["robot"].setdefault("start_positions", []) field = config_obj["pyfrc"].setdefault("field", {}) force_defaults = False # The rules here are complex because of backwards compat # -> if you specify a particular season, then it will override w/h/px # -> if you specify objects then you will get your own stuff # -> if you don't specify anything then it override w/h/px # -> if you add your own, it will warn you unless you specify an image # backwards compat if "season" in config_obj["pyfrc"]["field"]: season = config_obj["pyfrc"]["field"]["season"] defaults = _field_defaults.get(str(season), _field_defaults["default"]) force_defaults = True elif "objects" in config_obj["pyfrc"]["field"]: defaults = _field_defaults["default"] else: if "image" not in field: force_defaults = True defaults = _field_defaults[_default_year] if force_defaults: if "w" in field or "h" in field or "px_per_ft" in field: logger.warning("Ignoring field w/h/px_per_ft settings") field["w"] = defaults["w"] field["h"] = defaults["h"] field["px_per_ft"] = defaults["px_per_ft"] config_obj["pyfrc"]["field"].setdefault("objects", []) config_obj["pyfrc"]["field"].setdefault("w", defaults["w"]) config_obj["pyfrc"]["field"].setdefault("h", defaults["h"]) config_obj["pyfrc"]["field"].setdefault("px_per_ft", defaults["px_per_ft"]) img = config_obj["pyfrc"]["field"].setdefault("image", defaults["image"]) config_obj["pyfrc"].setdefault( "game_specific_messages", defaults.get("game_specific_messages", []) ) config_obj["pyfrc"]["field"].setdefault( "auto_joysticks", defaults.get("auto_joysticks", False) ) assert isinstance(config_obj["pyfrc"]["game_specific_messages"], (list, type(None))) if img and not isabs(config_obj["pyfrc"]["field"]["image"]): config_obj["pyfrc"]["field"]["image"] = abspath(join(sim_path, img)) config_obj["pyfrc"].setdefault("analog", {}) config_obj["pyfrc"].setdefault("CAN", {}) config_obj["pyfrc"].setdefault("dio", {}) config_obj["pyfrc"].setdefault("pwm", {}) config_obj["pyfrc"].setdefault("relay", {}) config_obj["pyfrc"].setdefault("solenoid", {}) config_obj["pyfrc"].setdefault("joysticks", {}) for i in range(6): config_obj["pyfrc"]["joysticks"].setdefault(str(i), {}) config_obj["pyfrc"]["joysticks"][str(i)].setdefault("axes", {}) config_obj["pyfrc"]["joysticks"][str(i)].setdefault("buttons", {}) config_obj["pyfrc"]["joysticks"][str(i)]["buttons"].setdefault("1", "Trigger") config_obj["pyfrc"]["joysticks"][str(i)]["buttons"].setdefault("2", "Top")
Used internally by pyfrc, don't call this directly. Loads a json file from sim/config.json and makes the information available to simulation/testing code.
entailment
def perform_smooth(x_values, y_values, span=None, smoother_cls=None): """ Convenience function to run the basic smoother. Parameters ---------- x_values : iterable List of x value observations y_ values : iterable list of y value observations span : float, optional Fraction of data to use as the window smoother_cls : Class The class of smoother to use to smooth the data Returns ------- smoother : object The smoother object with results stored on it. """ if smoother_cls is None: smoother_cls = DEFAULT_BASIC_SMOOTHER smoother = smoother_cls() smoother.specify_data_set(x_values, y_values) smoother.set_span(span) smoother.compute() return smoother
Convenience function to run the basic smoother. Parameters ---------- x_values : iterable List of x value observations y_ values : iterable list of y value observations span : float, optional Fraction of data to use as the window smoother_cls : Class The class of smoother to use to smooth the data Returns ------- smoother : object The smoother object with results stored on it.
entailment
def add_data_point_xy(self, x, y): """Add a new data point to the data set to be smoothed.""" self.x.append(x) self.y.append(y)
Add a new data point to the data set to be smoothed.
entailment
def specify_data_set(self, x_input, y_input, sort_data=False): """ Fully define data by lists of x values and y values. This will sort them by increasing x but remember how to unsort them for providing results. Parameters ---------- x_input : iterable list of floats that represent x y_input : iterable list of floats that represent y(x) for each x sort_data : bool, optional If true, the data will be sorted by increasing x values. """ if sort_data: xy = sorted(zip(x_input, y_input)) x, y = zip(*xy) x_input_list = list(x_input) self._original_index_of_xvalue = [x_input_list.index(xi) for xi in x] if len(set(self._original_index_of_xvalue)) != len(x): raise RuntimeError('There are some non-unique x-values') else: x, y = x_input, y_input self.x = x self.y = y
Fully define data by lists of x values and y values. This will sort them by increasing x but remember how to unsort them for providing results. Parameters ---------- x_input : iterable list of floats that represent x y_input : iterable list of floats that represent y(x) for each x sort_data : bool, optional If true, the data will be sorted by increasing x values.
entailment
def plot(self, fname=None): """ Plot the input data and resulting smooth. Parameters ---------- fname : str, optional name of file to produce. If none, will show interactively. """ plt.figure() xy = sorted(zip(self.x, self.smooth_result)) x, y = zip(*xy) plt.plot(x, y, '-') plt.plot(self.x, self.y, '.') if fname: plt.savefig(fname) else: plt.show() plt.close()
Plot the input data and resulting smooth. Parameters ---------- fname : str, optional name of file to produce. If none, will show interactively.
entailment
def _store_unsorted_results(self, smooth, residual): """Convert sorted smooth/residual back to as-input order.""" if self._original_index_of_xvalue: # data was sorted. Unsort it here. self.smooth_result = numpy.zeros(len(self.y)) self.cross_validated_residual = numpy.zeros(len(residual)) original_x = numpy.zeros(len(self.y)) for i, (xval, smooth_val, residual_val) in enumerate(zip(self.x, smooth, residual)): original_index = self._original_index_of_xvalue[i] original_x[original_index] = xval self.smooth_result[original_index] = smooth_val self.cross_validated_residual[original_index] = residual_val self.x = original_x else: # no sorting was done. just apply results self.smooth_result = smooth self.cross_validated_residual = residual
Convert sorted smooth/residual back to as-input order.
entailment
def compute(self): """Perform the smoothing operations.""" self._compute_window_size() smooth = [] residual = [] x, y = self.x, self.y # step through x and y data with a window window_size wide. self._update_values_in_window() self._update_mean_in_window() self._update_variance_in_window() for i, (xi, yi) in enumerate(zip(x, y)): if ((i - self._neighbors_on_each_side) > 0.0 and (i + self._neighbors_on_each_side) < len(x)): self._advance_window() smooth_here = self._compute_smooth_during_construction(xi) residual_here = self._compute_cross_validated_residual_here(xi, yi, smooth_here) smooth.append(smooth_here) residual.append(residual_here) self._store_unsorted_results(smooth, residual)
Perform the smoothing operations.
entailment
def _compute_window_size(self): """Determine characteristics of symmetric neighborhood with J/2 values on each side.""" self._neighbors_on_each_side = int(len(self.x) * self._span) // 2 self.window_size = self._neighbors_on_each_side * 2 + 1 if self.window_size <= 1: # cannot do averaging with 1 point in window. Force >=2 self.window_size = 2
Determine characteristics of symmetric neighborhood with J/2 values on each side.
entailment
def _update_values_in_window(self): """Update which values are in the current window.""" window_bound_upper = self._window_bound_lower + self.window_size self._x_in_window = self.x[self._window_bound_lower:window_bound_upper] self._y_in_window = self.y[self._window_bound_lower:window_bound_upper]
Update which values are in the current window.
entailment
def _update_mean_in_window(self): """ Compute mean in window the slow way. useful for first step. Considers all values in window See Also -------- _add_observation_to_means : fast update of mean for single observation addition _remove_observation_from_means : fast update of mean for single observation removal """ self._mean_x_in_window = numpy.mean(self._x_in_window) self._mean_y_in_window = numpy.mean(self._y_in_window)
Compute mean in window the slow way. useful for first step. Considers all values in window See Also -------- _add_observation_to_means : fast update of mean for single observation addition _remove_observation_from_means : fast update of mean for single observation removal
entailment
def _update_variance_in_window(self): """ Compute variance and covariance in window using all values in window (slow). See Also -------- _add_observation_to_variances : fast update for single observation addition _remove_observation_from_variances : fast update for single observation removal """ self._covariance_in_window = sum([(xj - self._mean_x_in_window) * (yj - self._mean_y_in_window) for xj, yj in zip(self._x_in_window, self._y_in_window)]) self._variance_in_window = sum([(xj - self._mean_x_in_window) ** 2 for xj in self._x_in_window])
Compute variance and covariance in window using all values in window (slow). See Also -------- _add_observation_to_variances : fast update for single observation addition _remove_observation_from_variances : fast update for single observation removal
entailment
def _advance_window(self): """Update values in current window and the current window means and variances.""" x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0] self._window_bound_lower += 1 self._update_values_in_window() x_to_add, y_to_add = self._x_in_window[-1], self._y_in_window[-1] self._remove_observation(x_to_remove, y_to_remove) self._add_observation(x_to_add, y_to_add)
Update values in current window and the current window means and variances.
entailment
def _remove_observation(self, x_to_remove, y_to_remove): """Remove observation from window, updating means/variance efficiently.""" self._remove_observation_from_variances(x_to_remove, y_to_remove) self._remove_observation_from_means(x_to_remove, y_to_remove) self.window_size -= 1
Remove observation from window, updating means/variance efficiently.
entailment
def _add_observation(self, x_to_add, y_to_add): """Add observation to window, updating means/variance efficiently.""" self._add_observation_to_means(x_to_add, y_to_add) self._add_observation_to_variances(x_to_add, y_to_add) self.window_size += 1
Add observation to window, updating means/variance efficiently.
entailment
def _add_observation_to_means(self, xj, yj): """Update the means without recalculating for the addition of one observation.""" self._mean_x_in_window = ((self.window_size * self._mean_x_in_window + xj) / (self.window_size + 1.0)) self._mean_y_in_window = ((self.window_size * self._mean_y_in_window + yj) / (self.window_size + 1.0))
Update the means without recalculating for the addition of one observation.
entailment
def _remove_observation_from_means(self, xj, yj): """Update the means without recalculating for the deletion of one observation.""" self._mean_x_in_window = ((self.window_size * self._mean_x_in_window - xj) / (self.window_size - 1.0)) self._mean_y_in_window = ((self.window_size * self._mean_y_in_window - yj) / (self.window_size - 1.0))
Update the means without recalculating for the deletion of one observation.
entailment
def _add_observation_to_variances(self, xj, yj): """ Quickly update the variance and co-variance for the addition of one observation. See Also -------- _update_variance_in_window : compute variance considering full window """ term1 = (self.window_size + 1.0) / self.window_size * (xj - self._mean_x_in_window) self._covariance_in_window += term1 * (yj - self._mean_y_in_window) self._variance_in_window += term1 * (xj - self._mean_x_in_window)
Quickly update the variance and co-variance for the addition of one observation. See Also -------- _update_variance_in_window : compute variance considering full window
entailment
def _compute_smooth_during_construction(self, xi): """ Evaluate value of smooth at x-value xi. Parameters ---------- xi : float Value of x where smooth value is desired Returns ------- smooth_here : float Value of smooth s(xi) """ if self._variance_in_window: beta = self._covariance_in_window / self._variance_in_window alpha = self._mean_y_in_window - beta * self._mean_x_in_window value_of_smooth_here = beta * (xi) + alpha else: value_of_smooth_here = 0.0 return value_of_smooth_here
Evaluate value of smooth at x-value xi. Parameters ---------- xi : float Value of x where smooth value is desired Returns ------- smooth_here : float Value of smooth s(xi)
entailment
def _compute_cross_validated_residual_here(self, xi, yi, smooth_here): """ Compute cross validated residual. This is the absolute residual from Eq. 9. in [1] """ denom = (1.0 - 1.0 / self.window_size - (xi - self._mean_x_in_window) ** 2 / self._variance_in_window) if denom == 0.0: # can happen with small data sets return 1.0 return abs((yi - smooth_here) / denom)
Compute cross validated residual. This is the absolute residual from Eq. 9. in [1]
entailment
def build_sample_ace_problem_breiman85(N=200): """Sample problem from Breiman 1985.""" x_cubed = numpy.random.standard_normal(N) x = scipy.special.cbrt(x_cubed) noise = numpy.random.standard_normal(N) y = numpy.exp((x ** 3.0) + noise) return [x], y
Sample problem from Breiman 1985.
entailment
def build_sample_ace_problem_breiman2(N=500): """Build sample problem y(x) = exp(sin(x)).""" x = numpy.linspace(0, 1, N) # x = numpy.random.uniform(0, 1, size=N) noise = numpy.random.standard_normal(N) y = numpy.exp(numpy.sin(2 * numpy.pi * x)) + 0.0 * noise return [x], y
Build sample problem y(x) = exp(sin(x)).
entailment
def run_breiman85(): """Run Breiman 85 sample.""" x, y = build_sample_ace_problem_breiman85(200) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: ace.plot_transforms(ace_solver, 'sample_ace_breiman85.png') except ImportError: pass return ace_solver
Run Breiman 85 sample.
entailment
def run_breiman2(): """Run Breiman's other sample problem.""" x, y = build_sample_ace_problem_breiman2(500) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: plt = ace.plot_transforms(ace_solver, None) except ImportError: pass plt.subplot(1, 2, 1) phi = numpy.sin(2.0 * numpy.pi * x[0]) plt.plot(x[0], phi, label='analytic') plt.legend() plt.subplot(1, 2, 2) y = numpy.exp(phi) plt.plot(y, phi, label='analytic') plt.legend(loc='lower right') # plt.show() plt.savefig('no_noise_linear_x.png') return ace_solver
Run Breiman's other sample problem.
entailment
def publish(self, topic, messages, key=None): """Takes messages and puts them on the supplied kafka topic """ if not isinstance(messages, list): messages = [messages] first = True success = False if key is None: key = int(time.time() * 1000) messages = [encodeutils.to_utf8(m) for m in messages] key = bytes(str(key), 'utf-8') if PY3 else str(key) while not success: try: self._producer.send_messages(topic, key, *messages) success = True except Exception: if first: # This is a warning because of all the other warning and # error messages that are logged in this case. This way # someone looking at the log file can see the retry log.warn("Failed send on topic {}, clear metadata and retry" .format(topic)) # If Kafka is running in Kubernetes, the cached metadata # contains the IP Address of the Kafka pod. If the Kafka # pod has restarted, the IP Address will have changed # which would have caused the first publish to fail. So, # clear the cached metadata and retry the publish self._kafka.reset_topic_metadata(topic) first = False continue log.exception('Error publishing to {} topic.'.format(topic)) raise
Takes messages and puts them on the supplied kafka topic
entailment
def create_gzip_message(payloads, key=None, compresslevel=None): """ Construct a Gzipped Message containing multiple Messages The given payloads will be encoded, compressed, and sent as a single atomic message to Kafka. Arguments: payloads: list(bytes), a list of payload to send be sent to Kafka key: bytes, a key used for partition routing (optional) """ message_set = KafkaProtocol._encode_message_set( [create_message(payload, pl_key) for payload, pl_key in payloads]) gzipped = gzip_encode(message_set, compresslevel=compresslevel) codec = ATTRIBUTE_CODEC_MASK & CODEC_GZIP return Message(0, 0x00 | codec, key, gzipped)
Construct a Gzipped Message containing multiple Messages The given payloads will be encoded, compressed, and sent as a single atomic message to Kafka. Arguments: payloads: list(bytes), a list of payload to send be sent to Kafka key: bytes, a key used for partition routing (optional)
entailment
def _encode_message(cls, message): """ Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero Format ====== Message => Crc MagicByte Attributes Key Value Crc => int32 MagicByte => int8 Attributes => int8 Key => bytes Value => bytes """ if message.magic == 0: msg = b''.join([ struct.pack('>BB', message.magic, message.attributes), write_int_string(message.key), write_int_string(message.value) ]) crc = crc32(msg) msg = struct.pack('>I%ds' % len(msg), crc, msg) else: raise ProtocolError("Unexpected magic number: %d" % message.magic) return msg
Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero Format ====== Message => Crc MagicByte Attributes Key Value Crc => int32 MagicByte => int8 Attributes => int8 Key => bytes Value => bytes
entailment
def _decode_message_set_iter(cls, data): """ Iteratively decode a MessageSet Reads repeated elements of (offset, message), calling decode_message to decode a single message. Since compressed messages contain futher MessageSets, these two methods have been decoupled so that they may recurse easily. """ cur = 0 read_message = False while cur < len(data): try: ((offset, ), cur) = relative_unpack('>q', data, cur) (msg, cur) = read_int_string(data, cur) for (offset, message) in KafkaProtocol._decode_message(msg, offset): read_message = True yield OffsetAndMessage(offset, message) except BufferUnderflowError: # NOTE: Not sure this is correct error handling: # Is it possible to get a BUE if the message set is somewhere # in the middle of the fetch response? If so, we probably have # an issue that's not fetch size too small. # Aren't we ignoring errors if we fail to unpack data by # raising StopIteration()? # If _decode_message() raises a ChecksumError, couldn't that # also be due to the fetch size being too small? if read_message is False: # If we get a partial read of a message, but haven't # yielded anything there's a problem raise ConsumerFetchSizeTooSmall() else: raise StopIteration()
Iteratively decode a MessageSet Reads repeated elements of (offset, message), calling decode_message to decode a single message. Since compressed messages contain futher MessageSets, these two methods have been decoupled so that they may recurse easily.
entailment
def _decode_message(cls, data, offset): """ Decode a single Message The only caller of this method is decode_message_set_iter. They are decoupled to support nested messages (compressed MessageSets). The offset is actually read from decode_message_set_iter (it is part of the MessageSet payload). """ ((crc, magic, att), cur) = relative_unpack('>IBB', data, 0) if crc != crc32(data[4:]): raise ChecksumError("Message checksum failed") (key, cur) = read_int_string(data, cur) (value, cur) = read_int_string(data, cur) codec = att & ATTRIBUTE_CODEC_MASK if codec == CODEC_NONE: yield (offset, Message(magic, att, key, value)) elif codec == CODEC_GZIP: gz = gzip_decode(value) for (offset, msg) in KafkaProtocol._decode_message_set_iter(gz): yield (offset, msg) elif codec == CODEC_SNAPPY: snp = snappy_decode(value) for (offset, msg) in KafkaProtocol._decode_message_set_iter(snp): yield (offset, msg)
Decode a single Message The only caller of this method is decode_message_set_iter. They are decoupled to support nested messages (compressed MessageSets). The offset is actually read from decode_message_set_iter (it is part of the MessageSet payload).
entailment
def encode_produce_request(cls, client_id, correlation_id, payloads=None, acks=1, timeout=1000): """ Encode some ProduceRequest structs Arguments: client_id: string correlation_id: int payloads: list of ProduceRequest acks: How "acky" you want the request to be 0: immediate response 1: written to disk by the leader 2+: waits for this many number of replicas to sync -1: waits for all replicas to be in sync timeout: Maximum time the server will wait for acks from replicas. This is _not_ a socket timeout """ payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.PRODUCE_KEY)) message.append(struct.pack('>hii', acks, timeout, len(grouped_payloads))) for topic, topic_payloads in grouped_payloads.items(): message.append(struct.pack('>h%dsi' % len(topic), len(topic), topic, len(topic_payloads))) for partition, payload in topic_payloads.items(): msg_set = KafkaProtocol._encode_message_set(payload.messages) message.append(struct.pack('>ii%ds' % len(msg_set), partition, len(msg_set), msg_set)) msg = b''.join(message) return struct.pack('>i%ds' % len(msg), len(msg), msg)
Encode some ProduceRequest structs Arguments: client_id: string correlation_id: int payloads: list of ProduceRequest acks: How "acky" you want the request to be 0: immediate response 1: written to disk by the leader 2+: waits for this many number of replicas to sync -1: waits for all replicas to be in sync timeout: Maximum time the server will wait for acks from replicas. This is _not_ a socket timeout
entailment
def decode_produce_response(cls, data): """ Decode bytes to a ProduceResponse Arguments: data: bytes to decode """ ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): ((strlen,), cur) = relative_unpack('>h', data, cur) topic = data[cur:cur + strlen] cur += strlen ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _ in range(num_partitions): ((partition, error, offset), cur) = relative_unpack('>ihq', data, cur) yield ProduceResponse(topic, partition, error, offset)
Decode bytes to a ProduceResponse Arguments: data: bytes to decode
entailment
def encode_fetch_request(cls, client_id, correlation_id, payloads=None, max_wait_time=100, min_bytes=4096): """ Encodes some FetchRequest structs Arguments: client_id: string correlation_id: int payloads: list of FetchRequest max_wait_time: int, how long to block waiting on min_bytes of data min_bytes: int, the minimum number of bytes to accumulate before returning the response """ payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.FETCH_KEY)) # -1 is the replica id message.append(struct.pack('>iiii', -1, max_wait_time, min_bytes, len(grouped_payloads))) for topic, topic_payloads in grouped_payloads.items(): message.append(write_short_string(topic)) message.append(struct.pack('>i', len(topic_payloads))) for partition, payload in topic_payloads.items(): message.append(struct.pack('>iqi', partition, payload.offset, payload.max_bytes)) msg = b''.join(message) return struct.pack('>i%ds' % len(msg), len(msg), msg)
Encodes some FetchRequest structs Arguments: client_id: string correlation_id: int payloads: list of FetchRequest max_wait_time: int, how long to block waiting on min_bytes of data min_bytes: int, the minimum number of bytes to accumulate before returning the response
entailment
def decode_fetch_response(cls, data): """ Decode bytes to a FetchResponse Arguments: data: bytes to decode """ ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for j in range(num_partitions): ((partition, error, highwater_mark_offset), cur) = \ relative_unpack('>ihq', data, cur) (message_set, cur) = read_int_string(data, cur) yield FetchResponse( topic, partition, error, highwater_mark_offset, KafkaProtocol._decode_message_set_iter(message_set))
Decode bytes to a FetchResponse Arguments: data: bytes to decode
entailment
def decode_offset_response(cls, data): """ Decode bytes to an OffsetResponse Arguments: data: bytes to decode """ ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _ in range(num_partitions): ((partition, error, num_offsets,), cur) = \ relative_unpack('>ihi', data, cur) offsets = [] for k in range(num_offsets): ((offset,), cur) = relative_unpack('>q', data, cur) offsets.append(offset) yield OffsetResponse(topic, partition, error, tuple(offsets))
Decode bytes to an OffsetResponse Arguments: data: bytes to decode
entailment
def encode_metadata_request(cls, client_id, correlation_id, topics=None, payloads=None): """ Encode a MetadataRequest Arguments: client_id: string correlation_id: int topics: list of strings """ if payloads is None: topics = [] if topics is None else topics else: topics = payloads message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.METADATA_KEY)) message.append(struct.pack('>i', len(topics))) for topic in topics: message.append(struct.pack('>h%ds' % len(topic), len(topic), topic)) msg = b''.join(message) return write_int_string(msg)
Encode a MetadataRequest Arguments: client_id: string correlation_id: int topics: list of strings
entailment
def decode_metadata_response(cls, data): """ Decode bytes to a MetadataResponse Arguments: data: bytes to decode """ ((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0) # Broker info brokers = [] for _ in range(numbrokers): ((nodeId, ), cur) = relative_unpack('>i', data, cur) (host, cur) = read_short_string(data, cur) ((port,), cur) = relative_unpack('>i', data, cur) brokers.append(BrokerMetadata(nodeId, host, port)) # Topic info ((num_topics,), cur) = relative_unpack('>i', data, cur) topic_metadata = [] for _ in range(num_topics): ((topic_error,), cur) = relative_unpack('>h', data, cur) (topic_name, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) partition_metadata = [] for _ in range(num_partitions): ((partition_error_code, partition, leader, numReplicas), cur) = \ relative_unpack('>hiii', data, cur) (replicas, cur) = relative_unpack( '>%di' % numReplicas, data, cur) ((num_isr,), cur) = relative_unpack('>i', data, cur) (isr, cur) = relative_unpack('>%di' % num_isr, data, cur) partition_metadata.append( PartitionMetadata(topic_name, partition, leader, replicas, isr, partition_error_code) ) topic_metadata.append( TopicMetadata(topic_name, topic_error, partition_metadata) ) return MetadataResponse(brokers, topic_metadata)
Decode bytes to a MetadataResponse Arguments: data: bytes to decode
entailment
def encode_offset_commit_request(cls, client_id, correlation_id, group, payloads): """ Encode some OffsetCommitRequest structs Arguments: client_id: string correlation_id: int group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequest """ grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.OFFSET_COMMIT_KEY)) message.append(write_short_string(group)) message.append(struct.pack('>i', len(grouped_payloads))) for topic, topic_payloads in grouped_payloads.items(): message.append(write_short_string(topic)) message.append(struct.pack('>i', len(topic_payloads))) for partition, payload in topic_payloads.items(): message.append(struct.pack('>iq', partition, payload.offset)) message.append(write_short_string(payload.metadata)) msg = b''.join(message) return struct.pack('>i%ds' % len(msg), len(msg), msg)
Encode some OffsetCommitRequest structs Arguments: client_id: string correlation_id: int group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequest
entailment
def decode_offset_commit_response(cls, data): """ Decode bytes to an OffsetCommitResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in xrange(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _ in xrange(num_partitions): ((partition, error), cur) = relative_unpack('>ih', data, cur) yield OffsetCommitResponse(topic, partition, error)
Decode bytes to an OffsetCommitResponse Arguments: data: bytes to decode
entailment
def encode_offset_fetch_request(cls, client_id, correlation_id, group, payloads, from_kafka=False): """ Encode some OffsetFetchRequest structs. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request for Kafka offsets. Arguments: client_id: string correlation_id: int group: string, the consumer group you are fetching offsets for payloads: list of OffsetFetchRequest from_kafka: bool, default False, set True for Kafka-committed offsets """ grouped_payloads = group_by_topic_and_partition(payloads) message = [] reqver = 1 if from_kafka else 0 message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.OFFSET_FETCH_KEY, version=reqver)) message.append(write_short_string(group)) message.append(struct.pack('>i', len(grouped_payloads))) for topic, topic_payloads in grouped_payloads.items(): message.append(write_short_string(topic)) message.append(struct.pack('>i', len(topic_payloads))) for partition, payload in topic_payloads.items(): message.append(struct.pack('>i', partition)) msg = b''.join(message) return struct.pack('>i%ds' % len(msg), len(msg), msg)
Encode some OffsetFetchRequest structs. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request for Kafka offsets. Arguments: client_id: string correlation_id: int group: string, the consumer group you are fetching offsets for payloads: list of OffsetFetchRequest from_kafka: bool, default False, set True for Kafka-committed offsets
entailment
def decode_offset_fetch_response(cls, data): """ Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _ in range(num_partitions): ((partition, offset), cur) = relative_unpack('>iq', data, cur) (metadata, cur) = read_short_string(data, cur) ((error,), cur) = relative_unpack('>h', data, cur) yield OffsetFetchResponse(topic, partition, offset, metadata, error)
Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode
entailment
def _get_module(target): """Import a named class, module, method or function. Accepts these formats: ".../file/path|module_name:Class.method" ".../file/path|module_name:Class" ".../file/path|module_name:function" "module_name:Class" "module_name:function" "module_name:Class.function" If a fully qualified directory is specified, it implies the directory is not already on the Python Path, in which case it will be added. For example, if I import /home/foo (and /home/foo is not in the python path) as "/home/foo|mycode:MyClass.mymethod" then /home/foo will be added to the python path and the module loaded as normal. """ filepath, sep, namespace = target.rpartition('|') if sep and not filepath: raise BadDirectory("Path to file not supplied.") module, sep, class_or_function = namespace.rpartition(':') if (sep and not module) or (filepath and not module): raise MissingModule("Need a module path for %s (%s)" % (namespace, target)) if filepath and filepath not in sys.path: if not os.path.isdir(filepath): raise BadDirectory("No such directory: '%s'" % filepath) sys.path.append(filepath) if not class_or_function: raise MissingMethodOrFunction( "No Method or Function specified in '%s'" % target) if module: try: __import__(module) except ImportError as e: raise ImportFailed("Failed to import '%s'. " "Error: %s" % (module, e)) klass, sep, function = class_or_function.rpartition('.') return module, klass, function
Import a named class, module, method or function. Accepts these formats: ".../file/path|module_name:Class.method" ".../file/path|module_name:Class" ".../file/path|module_name:function" "module_name:Class" "module_name:function" "module_name:Class.function" If a fully qualified directory is specified, it implies the directory is not already on the Python Path, in which case it will be added. For example, if I import /home/foo (and /home/foo is not in the python path) as "/home/foo|mycode:MyClass.mymethod" then /home/foo will be added to the python path and the module loaded as normal.
entailment
def load(target, source_module=None): """Get the actual implementation of the target.""" module, klass, function = _get_module(target) if not module and source_module: module = source_module if not module: raise MissingModule( "No module name supplied or source_module provided.") actual_module = sys.modules[module] if not klass: return getattr(actual_module, function) class_object = getattr(actual_module, klass) if function: return getattr(class_object, function) return class_object
Get the actual implementation of the target.
entailment
def process_child(node): """This function changes class references to not have the intermediate module name by hacking at the doctree""" # Edit descriptions to be nicer if isinstance(node, sphinx.addnodes.desc_addname): if len(node.children) == 1: child = node.children[0] text = child.astext() if text.startswith("wpilib.") and text.endswith("."): # remove the last element text = ".".join(text.split(".")[:-2]) + "." node.children[0] = docutils.nodes.Text(text) # Edit literals to be nicer elif isinstance(node, docutils.nodes.literal): child = node.children[0] text = child.astext() # Remove the imported module name if text.startswith("wpilib."): stext = text.split(".") text = ".".join(stext[:-2] + [stext[-1]]) node.children[0] = docutils.nodes.Text(text) for child in node.children: process_child(child)
This function changes class references to not have the intermediate module name by hacking at the doctree
entailment
def commit(self, partitions=None): """Commit stored offsets to Kafka via OffsetCommitRequest (v0) Keyword Arguments: partitions (list): list of partitions to commit, default is to commit all of them Returns: True on success, False on failure """ # short circuit if nothing happened. This check is kept outside # to prevent un-necessarily acquiring a lock for checking the state if self.count_since_commit == 0: return with self.commit_lock: # Do this check again, just in case the state has changed # during the lock acquiring timeout if self.count_since_commit == 0: return reqs = [] if partitions is None: # commit all partitions partitions = list(self.offsets.keys()) log.debug('Committing new offsets for %s, partitions %s', self.topic, partitions) for partition in partitions: offset = self.offsets[partition] log.debug('Commit offset %d in SimpleConsumer: ' 'group=%s, topic=%s, partition=%s', offset, self.group, self.topic, partition) reqs.append(OffsetCommitRequest(self.topic, partition, offset, None)) try: self.client.send_offset_commit_request(self.group, reqs) except KafkaError as e: log.error('%s saving offsets: %s', e.__class__.__name__, e) return False else: self.count_since_commit = 0 return True
Commit stored offsets to Kafka via OffsetCommitRequest (v0) Keyword Arguments: partitions (list): list of partitions to commit, default is to commit all of them Returns: True on success, False on failure
entailment
def read_column_data_from_txt(fname): """ Read data from a simple text file. Format should be just numbers. First column is the dependent variable. others are independent. Whitespace delimited. Returns ------- x_values : list List of x columns y_values : list list of y values """ datafile = open(fname) datarows = [] for line in datafile: datarows.append([float(li) for li in line.split()]) datacols = list(zip(*datarows)) x_values = datacols[1:] y_values = datacols[0] return x_values, y_values
Read data from a simple text file. Format should be just numbers. First column is the dependent variable. others are independent. Whitespace delimited. Returns ------- x_values : list List of x columns y_values : list list of y values
entailment
def build_model_from_txt(self, fname): """ Construct the model and perform regressions based on data in a txt file. Parameters ---------- fname : str The name of the file to load. """ x_values, y_values = read_column_data_from_txt(fname) self.build_model_from_xy(x_values, y_values)
Construct the model and perform regressions based on data in a txt file. Parameters ---------- fname : str The name of the file to load.
entailment
def build_model_from_xy(self, x_values, y_values): """Construct the model and perform regressions based on x, y data.""" self.init_ace(x_values, y_values) self.run_ace() self.build_interpolators()
Construct the model and perform regressions based on x, y data.
entailment
def build_interpolators(self): """Compute 1-D interpolation functions for all the transforms so they're continuous..""" self.phi_continuous = [] for xi, phii in zip(self.ace.x, self.ace.x_transforms): self.phi_continuous.append(interp1d(xi, phii)) self.inverse_theta_continuous = interp1d(self.ace.y_transform, self.ace.y)
Compute 1-D interpolation functions for all the transforms so they're continuous..
entailment
def eval(self, x_values): """ Evaluate the ACE regression at any combination of independent variable values. Parameters ---------- x_values : iterable a float x-value for each independent variable, e.g. (1.5, 2.5) """ if len(x_values) != len(self.phi_continuous): raise ValueError('x_values must have length equal to the number of independent variables ' '({0}) rather than {1}.'.format(len(self.phi_continuous), len(x_values))) sum_phi = sum([phi(xi) for phi, xi in zip(self.phi_continuous, x_values)]) return float(self.inverse_theta_continuous(sum_phi))
Evaluate the ACE regression at any combination of independent variable values. Parameters ---------- x_values : iterable a float x-value for each independent variable, e.g. (1.5, 2.5)
entailment
def yesno(prompt): """Returns True if user answers 'y' """ prompt += " [y/n]" a = "" while a not in ["y", "n"]: a = input(prompt).lower() return a == "y"
Returns True if user answers 'y'
entailment
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL, check_exceptions=()): """Retry decorator.""" def decorator(func): """Decorator.""" def f_retry(*args, **kwargs): """Retry running function on exception after delay.""" for i in range(1, retries + 1): try: return func(*args, **kwargs) # pylint: disable=W0703 # We want to catch all exceptions here to retry. except check_exceptions + (Exception,) as exc: if i < retries: logger.info('Connection attempt %d of %d failed', i, retries) if isinstance(exc, check_exceptions): logger.debug('Caught known exception, retrying...', exc_info=True) else: logger.warn( 'Caught unknown exception, retrying...', exc_info=True) else: logger.exception('Failed after %d attempts', retries) raise # No exception so wait before retrying time.sleep(delay) return f_retry return decorator
Retry decorator.
entailment
def check_topics(client, req_topics): """Check for existence of provided topics in Kafka.""" client.update_cluster() logger.debug('Found topics: %r', client.topics.keys()) for req_topic in req_topics: if req_topic not in client.topics.keys(): err_topic_not_found = 'Topic not found: {}'.format(req_topic) logger.warning(err_topic_not_found) raise TopicNotFound(err_topic_not_found) topic = client.topics[req_topic] if not topic.partitions: err_topic_no_part = 'Topic has no partitions: {}'.format(req_topic) logger.warning(err_topic_no_part) raise TopicNoPartition(err_topic_no_part) logger.info('Topic is ready: %s', req_topic)
Check for existence of provided topics in Kafka.
entailment
def main(): """Start main part of the wait script.""" logger.info('Checking for available topics: %r', repr(REQUIRED_TOPICS)) client = connect_kafka(hosts=KAFKA_HOSTS) check_topics(client, REQUIRED_TOPICS)
Start main part of the wait script.
entailment