signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def worker_teardown(self, worker_ctx):
Called after a service worker has executed a task. Dependencies should do any post-processing here, raising exceptions in the event of failure. Example: a database session dependency may commit the session :Parameters: worker_ctx : WorkerContext See ``namek...
f7192:c2:m4
def wait_for_providers(self):
if self._providers_registered:<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>self._last_provider_unregistered.wait()<EOL>_log.debug('<STR_LIT>', self)<EOL><DEDENT>
Wait for any providers registered with the collector to have unregistered. Returns immediately if no providers were ever registered.
f7192:c3:m3
def stop(self):
self.wait_for_providers()<EOL>
Default `:meth:Extension.stop()` implementation for subclasses using `ProviderCollector` as a mixin.
f7192:c3:m4
def __init__(<EOL>self, expected_exceptions=(), sensitive_arguments=(), **kwargs<EOL>):
<EOL>sensitive_variables = kwargs.pop('<STR_LIT>', ())<EOL>if sensitive_variables:<EOL><INDENT>sensitive_arguments = sensitive_variables<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL><DEDENT>self.expected_exceptions = expected_exceptions<EOL>self.sensitive_arguments = sensi...
:Parameters: expected_exceptions : exception class or tuple of exception classes Specify exceptions that may be caused by the caller (e.g. by providing bad arguments). Saved on the entrypoint instance as ``entrypoint.expected_exceptions`` for later inspection by other extensions, for...
f7192:c4:m0
def bind(self, container, method_name):
instance = super(Entrypoint, self).bind(container)<EOL>instance.method_name = method_name<EOL>return instance<EOL>
Get an instance of this Entrypoint to bind to `container` with `method_name`.
f7192:c4:m1
def wait(self):
<EOL>if self.exception:<EOL><INDENT>raise self.exception<EOL><DEDENT>if self.queue_consumer.stopped:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if self.queue_consumer.connection.connected is False:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>try:<EOL><INDENT>...
Makes a blocking call to its queue_consumer until the message with the given correlation_id has been processed. By the time the blocking call exits, self.send() will have been called with the body of the received message (see :meth:`~nameko.rpc.ReplyListener.handle_message`). E...
f7193:c0:m3
def __getitem__(self, name):
return getattr(self, name)<EOL>
Enable dict-like access on the proxy.
f7193:c5:m2
def get_event_exchange(service_name):
exchange_name = "<STR_LIT>".format(service_name)<EOL>exchange = Exchange(<EOL>exchange_name, type='<STR_LIT>', durable=True, delivery_mode=PERSISTENT<EOL>)<EOL>return exchange<EOL>
Get an exchange for ``service_name`` events.
f7195:m0
def event_dispatcher(nameko_config, **kwargs):
amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY]<EOL>serializer, _ = serialization.setup(nameko_config)<EOL>serializer = kwargs.pop('<STR_LIT>', serializer)<EOL>ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY)<EOL>publisher = Publisher(amqp_uri, serializer=serializer, ssl=ssl, **kwargs)<EOL>def dispatch(service_name, event_ty...
Return a function that dispatches nameko events.
f7195:m1
def __init__(self, interval, eager=False, **kwargs):
self.interval = interval<EOL>self.eager = eager<EOL>self.should_stop = Event()<EOL>self.worker_complete = Event()<EOL>self.gt = None<EOL>super(Timer, self).__init__(**kwargs)<EOL>
Timer entrypoint. Fires every `interval` seconds or as soon as the previous worker completes if that took longer. The default behaviour is to wait `interval` seconds before firing for the first time. If you want the entrypoint to fire as soon as the service starts, pass `eager=True`. Example:: timer = Timer.deco...
f7196:c0:m0
def _run(self):
def get_next_interval():<EOL><INDENT>start_time = time.time()<EOL>start = <NUM_LIT:0> if self.eager else <NUM_LIT:1><EOL>for count in itertools.count(start=start):<EOL><INDENT>yield max(start_time + count * self.interval - time.time(), <NUM_LIT:0>)<EOL><DEDENT><DEDENT>interval = get_next_interval()<EOL>sleep_time = nex...
Runs the interval loop.
f7196:c0:m4
def __init__(self, exchange=None, queue=None, declare=None, **options):
self.exchange = exchange<EOL>self.options = options<EOL>self.declare = declare[:] if declare is not None else []<EOL>if self.exchange:<EOL><INDENT>self.declare.append(self.exchange)<EOL><DEDENT>if queue is not None:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT...
Provides an AMQP message publisher method via dependency injection. In AMQP, messages are published to *exchanges* and routed to bound *queues*. This dependency accepts the `exchange` to publish to and will ensure that it is declared before publishing. Optionally, you may use the `decl...
f7197:c2:m0
@property<EOL><INDENT>def serializer(self):<DEDENT>
return self.container.serializer<EOL>
Default serializer to use when publishing messages. Must be registered as a `kombu serializer <http://bit.do/kombu_serialization>`_.
f7197:c2:m2
def stop(self):
if not self._consumers_ready.ready():<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>stop_exc = QueueConsumerStopped()<EOL>self._gt.kill(stop_exc)<EOL><DEDENT>self.wait_for_providers()<EOL>try:<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>self._gt.wait()<EOL><DEDENT>except QueueConsumerStopped:<EOL><INDENT>pass<EOL><DE...
Stop the queue-consumer gracefully. Wait until the last provider has been unregistered and for the ConsumerMixin's greenthread to exit (i.e. until all pending messages have been acked or requeued and all consumers stopped).
f7197:c3:m6
def kill(self):
<EOL>if self._gt is not None and not self._gt.dead:<EOL><INDENT>self._providers = set()<EOL>self._pending_remove_providers = {}<EOL>self.should_stop = True<EOL>try:<EOL><INDENT>self._gt.wait()<EOL><DEDENT>except Exception as exc:<EOL><INDENT>_log.warn(<EOL>'<STR_LIT>', self, exc)<EOL><DEDENT>super(QueueConsumer, self)....
Kill the queue-consumer. Unlike `stop()` any pending message ack or requeue-requests, requests to remove providers, etc are lost and the consume thread is asked to terminate as soon as possible.
f7197:c3:m7
@property<EOL><INDENT>def connection(self):<DEDENT>
heartbeat = self.container.config.get(<EOL>HEARTBEAT_CONFIG_KEY, DEFAULT_HEARTBEAT<EOL>)<EOL>transport_options = self.container.config.get(<EOL>TRANSPORT_OPTIONS_CONFIG_KEY, DEFAULT_TRANSPORT_OPTIONS<EOL>)<EOL>ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY)<EOL>conn = Connection(self.amqp_uri,<EOL>transport_option...
Provide the connection parameters for kombu's ConsumerMixin. The `Connection` object is a declaration of connection parameters that is lazily evaluated. It doesn't represent an established connection to the broker at this point.
f7197:c3:m12
def get_consumers(self, consumer_cls, channel):
_log.debug('<STR_LIT>', self)<EOL>for provider in self._providers:<EOL><INDENT>callbacks = [partial(self.handle_message, provider)]<EOL>consumer = consumer_cls(<EOL>queues=[provider.queue],<EOL>callbacks=callbacks,<EOL>accept=self.accept<EOL>)<EOL>consumer.qos(prefetch_count=self.prefetch_count)<EOL>self._consumers[pro...
Kombu callback to set up consumers. Called after any (re)connection to the broker.
f7197:c3:m14
def on_iteration(self):
self._cancel_consumers_if_requested()<EOL>if len(self._consumers) == <NUM_LIT:0>:<EOL><INDENT>_log.debug('<STR_LIT>')<EOL>self.should_stop = True<EOL><DEDENT>
Kombu callback for each `drain_events` loop iteration.
f7197:c3:m15
def on_consume_ready(self, connection, channel, consumers, **kwargs):
if not self._consumers_ready.ready():<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>self._consumers_ready.send(None)<EOL><DEDENT>
Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker.
f7197:c3:m17
def __init__(self, queue, requeue_on_error=False, **kwargs):
self.queue = queue<EOL>self.requeue_on_error = requeue_on_error<EOL>super(Consumer, self).__init__(**kwargs)<EOL>
Decorates a method as a message consumer. Messages from the queue will be deserialized depending on their content type and passed to the the decorated method. When the consumer method returns without raising any exceptions, the message will automatically be acknowledged. If any exceptions are raised during the consump...
f7197:c4:m0
def stop(self):
if not self._providers_registered:<EOL><INDENT>self.queue_consumer.unregister_provider(self)<EOL>self._unregistered_from_queue_consumer.send(True)<EOL><DEDENT>
Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop.
f7198:c0:m2
def unregister_provider(self, provider):
self._unregistering_providers.add(provider)<EOL>remaining_providers = self._providers - self._unregistering_providers<EOL>if not remaining_providers:<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>self.queue_consumer.unregister_provider(self)<EOL>_log.debug('<STR_LIT>', self)<EOL>self._unregistered_from_queue_consumer.s...
Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister.
f7198:c0:m3
def __init__(<EOL>self, worker_ctx, service_name, method_name, reply_listener, **options<EOL>):
self.worker_ctx = worker_ctx<EOL>self.service_name = service_name<EOL>self.method_name = method_name<EOL>self.reply_listener = reply_listener<EOL>compat_attrs = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>for compat_attr in compat_attrs:<EOL><INDENT>if hasattr(self, compat_attr):<EOL><INDENT>warnings.warn(<EOL>"<STR_LI...
Note that mechanism which raises :class:`UnknownService` exceptions relies on publish confirms being enabled in the proxy.
f7198:c7:m0
@property<EOL><INDENT>def serializer(self):<DEDENT>
return self.container.config.get(<EOL>SERIALIZER_CONFIG_KEY, DEFAULT_SERIALIZER<EOL>)<EOL>
Default serializer to use when publishing message payloads. Must be registered as a `kombu serializer <http://bit.do/kombu_serialization>`_.
f7198:c7:m5
def publish(self, payload, **kwargs):
publish_kwargs = self.publish_kwargs.copy()<EOL>headers = publish_kwargs.pop('<STR_LIT>', {}).copy()<EOL>headers.update(kwargs.pop('<STR_LIT>', {}))<EOL>headers.update(kwargs.pop('<STR_LIT>', {}))<EOL>use_confirms = kwargs.pop('<STR_LIT>', self.use_confirms)<EOL>transport_options = kwargs.pop('<STR_LIT>',<EOL>self.tran...
Publish a message.
f7202:c1:m1
@contextmanager<EOL>def entrypoint_hook(container, method_name, context_data=None, timeout=<NUM_LIT:30>):
entrypoint = get_extension(container, Entrypoint, method_name=method_name)<EOL>if entrypoint is None:<EOL><INDENT>raise ExtensionNotFound(<EOL>"<STR_LIT>".format(<EOL>method_name, container))<EOL><DEDENT>def hook(*args, **kwargs):<EOL><INDENT>hook_result = event.Event()<EOL>def wait_for_entrypoint():<EOL><INDENT>try:<E...
Yield a function providing an entrypoint into a hosted service. The yielded function may be called as if it were the bare method defined in the service class. Intended to be used as an integration testing utility. :Parameters: container : ServiceContainer The container hosting the ...
f7206:m0
@contextmanager<EOL>def entrypoint_waiter(container, method_name, timeout=<NUM_LIT:30>, callback=None):
if not get_extension(container, Entrypoint, method_name=method_name):<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(<EOL>container.service_name, method_name))<EOL><DEDENT>class Result(WaitResult):<EOL><INDENT>worker_ctx = None<EOL>def send(self, worker_ctx, result, exc_info):<EOL><INDENT>self.worker_ctx = worker_ct...
Context manager that waits until an entrypoint has fired, and the generated worker has exited and been torn down. It yields a :class:`nameko.testing.waiting.WaitResult` object that can be used to get the result returned (exception raised) by the entrypoint after the waiter has exited. :Parameters:...
f7206:m1
def worker_factory(service_cls, **dependencies):
service = service_cls()<EOL>for name, attr in inspect.getmembers(service_cls):<EOL><INDENT>if isinstance(attr, DependencyProvider):<EOL><INDENT>try:<EOL><INDENT>dependency = dependencies.pop(name)<EOL><DEDENT>except KeyError:<EOL><INDENT>dependency = MagicMock()<EOL><DEDENT>setattr(service, name, dependency)<EOL><DEDEN...
Return an instance of ``service_cls`` with its injected dependencies replaced with :class:`~mock.MagicMock` objects, or as given in ``dependencies``. **Usage** The following example service proxies calls to a "maths" service via an ``RpcProxy`` dependency:: from nameko.rpc import RpcProxy...
f7206:m2
def replace_dependencies(container, *dependencies, **dependency_map):
if set(dependencies).intersection(dependency_map):<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>")<EOL><DEDENT>arg_replacements = OrderedDict((dep, MagicMock()) for dep in dependencies)<EOL>dependency_map.update(arg_replacements)<EOL>_replace_dependencies(container, **dependency_map)<EOL>res = (replacement for replace...
Replace the dependency providers on ``container`` with instances of :class:`MockDependencyProvider`. Dependencies named in *dependencies will be replaced with a :class:`MockDependencyProvider`, which injects a MagicMock instead of the dependency. Alternatively, you may use keyword arguments to nam...
f7206:m4
def restrict_entrypoints(container, *entrypoints):
if container.started:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>entrypoint_deps = list(container.entrypoints)<EOL>entrypoint_names = {ext.method_name for ext in entrypoint_deps}<EOL>missing = set(entrypoints) - entrypoint_names<EOL>if missing:<EOL><INDENT>raise ExtensionNotFound("<STR_LIT>...
Restrict the entrypoints on ``container`` to those named in ``entrypoints``. This method must be called before the container is started. **Usage** The following service definition has two entrypoints: .. code-block:: python class Service(object): name = "service" ...
f7206:m5
def get_extension(container, extension_cls, **match_attrs):
for ext in container.extensions:<EOL><INDENT>if isinstance(ext, extension_cls):<EOL><INDENT>if not match_attrs:<EOL><INDENT>return ext<EOL><DEDENT>def has_attribute(name, value):<EOL><INDENT>return getattr(ext, name) == value<EOL><DEDENT>if all([has_attribute(name, value)<EOL>for name, value in match_attrs.items()]):<E...
Inspect ``container.extensions`` and return the first item that is an instance of ``extension_cls``. Optionally also require that the instance has an attribute with a particular value as given in the ``match_attrs`` kwargs.
f7207:m0
def get_container(runner, service_cls):
for container in runner.containers:<EOL><INDENT>if container.service_cls == service_cls:<EOL><INDENT>return container<EOL><DEDENT><DEDENT>
Inspect ``runner.containers`` and return the first item that is hosting an instance of ``service_cls``.
f7207:m1
@contextmanager<EOL>def wait_for_call(timeout, mock_method):
with eventlet.Timeout(timeout):<EOL><INDENT>while not mock_method.called:<EOL><INDENT>eventlet.sleep()<EOL><DEDENT><DEDENT>yield mock_method<EOL>
Return a context manager that waits ``timeout`` seconds for ``mock_method`` to be called, yielding the mock if so. Raises an :class:`eventlet.Timeout` if the method was not called within ``timeout`` seconds.
f7207:m2
def wait_for_worker_idle(container, timeout=<NUM_LIT:10>):
warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning<EOL>)<EOL>with eventlet.Timeout(timeout):<EOL><INDENT>container._worker_pool.waitall()<EOL><DEDENT>
Blocks until ``container`` has no running workers. Raises an :class:`eventlet.Timeout` if the method was not called within ``timeout`` seconds.
f7207:m3
def assert_stops_raising(fn, exception_type=Exception, timeout=<NUM_LIT:10>,<EOL>interval=<NUM_LIT:0.1>):
with eventlet.Timeout(timeout):<EOL><INDENT>while True:<EOL><INDENT>try:<EOL><INDENT>fn()<EOL><DEDENT>except exception_type:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>eventlet.sleep(interval)<EOL><DEDENT><DEDENT>
Assert that ``fn`` returns successfully within ``timeout`` seconds, trying every ``interval`` seconds. If ``exception_type`` is provided, fail unless the exception thrown is an instance of ``exception_type``. If not specified, any `:class:`Exception` instance is allowed.
f7207:m4
def get_redacted_args(entrypoint, *args, **kwargs):
sensitive_arguments = entrypoint.sensitive_arguments<EOL>if isinstance(sensitive_arguments, six.string_types):<EOL><INDENT>sensitive_arguments = (sensitive_arguments,)<EOL><DEDENT>method = getattr(entrypoint.container.service_cls, entrypoint.method_name)<EOL>callargs = inspect.getcallargs(method, None, *args, **kwargs)...
Utility function for use with entrypoints that are marked with ``sensitive_arguments`` -- e.g. :class:`nameko.rpc.Rpc` and :class:`nameko.events.EventHandler`. :Parameters: entrypoint : :class:`~nameko.extensions.Entrypoint` The entrypoint that fired. args : tuple Po...
f7211:m0
def import_from_path(path):
if path is None:<EOL><INDENT>return<EOL><DEDENT>obj = locate(path)<EOL>if obj is None:<EOL><INDENT>raise ImportError(<EOL>"<STR_LIT>".format(path)<EOL>)<EOL><DEDENT>return obj<EOL>
Import and return the object at `path` if it exists. Raises an :exc:`ImportError` if the object is not found.
f7211:m1
def sanitize_url(url):
parts = urlparse(url)<EOL>if parts.password is None:<EOL><INDENT>return url<EOL><DEDENT>host_info = parts.netloc.rsplit('<STR_LIT:@>', <NUM_LIT:1>)[-<NUM_LIT:1>]<EOL>parts = parts._replace(netloc='<STR_LIT>'.format(<EOL>parts.username, REDACTED, host_info))<EOL>return parts.geturl()<EOL>
Redact password in urls.
f7211:m2
def fail_fast_imap(pool, call, items):
result_queue = LightQueue(maxsize=len(items))<EOL>spawned_threads = set()<EOL>def handle_result(finished_thread):<EOL><INDENT>try:<EOL><INDENT>thread_result = finished_thread.wait()<EOL>spawned_threads.remove(finished_thread)<EOL>result_queue.put((thread_result, None))<EOL><DEDENT>except Exception:<EOL><INDENT>spawned_...
Run a function against each item in a given list, yielding each function result in turn, where the function call is handled in a :class:`~eventlet.greenthread.GreenThread` spawned by the provided pool. If any function raises an exception, all other ongoing threads are killed, and the exception is raise...
f7212:m0
def __init__(self, items, abort_on_error=False):
self._items = items<EOL>self.abort_on_error = abort_on_error<EOL>
Wraps an iterable set of items such that a call on the returned SpawningProxy instance will spawn a call in a :class:`~eventlet.greenthread.GreenThread` for each item. Returns when every spawned thread has completed. :param items: Iterable item set to process :param abort_on_er...
f7212:c0:m0
def make_nameko_helper(config):
module = ModuleType('<STR_LIT>')<EOL>module.__doc__ =
Create a fake module that provides some convenient access to nameko standalone functionality for interactive shell usage.
f7216:m0
def make_timing_logger(logger, precision=<NUM_LIT:3>, level=logging.DEBUG):
@contextmanager<EOL>def log_time(msg, *args):<EOL><INDENT>"""<STR_LIT>"""<EOL>start_time = time.time()<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>message = "<STR_LIT>".format(msg, precision)<EOL>duration = time.time() - start_time<EOL>args = args + (duration,)<EOL>logger.log(level, message, *args)<EOL>...
Return a timing logger. Usage:: >>> logger = logging.getLogger('foobar') >>> log_time = make_timing_logger( ... logger, level=logging.INFO, precision=2) >>> >>> with log_time("hello %s", "world"): ... time.sleep(1) INFO:foobar:hello world in 1.00s
f7222:m0
def get_module_path(exc_type):
module = inspect.getmodule(exc_type)<EOL>return "<STR_LIT>".format(module.__name__, exc_type.__name__)<EOL>
Return the dotted module path of `exc_type`, including the class name. e.g.:: >>> get_module_path(MethodNotFound) >>> "nameko.exceptions.MethodNotFound"
f7223:m0
def safe_for_serialization(value):
if isinstance(value, six.string_types):<EOL><INDENT>return value<EOL><DEDENT>if isinstance(value, dict):<EOL><INDENT>return {<EOL>safe_for_serialization(key): safe_for_serialization(val)<EOL>for key, val in six.iteritems(value)<EOL>}<EOL><DEDENT>if isinstance(value, collections.Iterable):<EOL><INDENT>return list(map(sa...
Transform a value in preparation for serializing as json no-op for strings, mappings and iterables have their entries made safe, and all other values are stringified, with a fallback value if that fails
f7223:m1
def serialize(exc):
return {<EOL>'<STR_LIT>': type(exc).__name__,<EOL>'<STR_LIT>': get_module_path(type(exc)),<EOL>'<STR_LIT>': list(map(safe_for_serialization, exc.args)),<EOL>'<STR_LIT:value>': safe_for_serialization(exc),<EOL>}<EOL>
Serialize `self.exc` into a data dictionary representing it.
f7223:m2
def deserialize(data):
key = data.get('<STR_LIT>')<EOL>if key in registry:<EOL><INDENT>exc_args = data.get('<STR_LIT>', ())<EOL>return registry[key](*exc_args)<EOL><DEDENT>exc_type = data.get('<STR_LIT>')<EOL>value = data.get('<STR_LIT:value>')<EOL>return RemoteError(exc_type=exc_type, value=value)<EOL>
Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred.
f7223:m3
def deserialize_to_instance(exc_type):
key = get_module_path(exc_type)<EOL>registry[key] = exc_type<EOL>return exc_type<EOL>
Decorator that registers `exc_type` as deserializable back into an instance, rather than a :class:`RemoteError`. See :func:`deserialize`.
f7223:m4
def get_dependency(self, worker_ctx):
extra_headers = self.get_message_headers(worker_ctx)<EOL>def dispatch(event_type, event_data):<EOL><INDENT>self.publisher.publish(<EOL>event_data,<EOL>exchange=self.exchange,<EOL>routing_key=event_type,<EOL>extra_headers=extra_headers<EOL>)<EOL><DEDENT>return dispatch<EOL>
Inject a dispatch method onto the service instance
f7224:c1:m1
def __init__(self, source_service, event_type, handler_type=SERVICE_POOL,<EOL>reliable_delivery=True, requeue_on_error=False, **kwargs):
self.source_service = source_service<EOL>self.event_type = event_type<EOL>self.handler_type = handler_type<EOL>self.reliable_delivery = reliable_delivery<EOL>super(EventHandler, self).__init__(<EOL>queue=None, requeue_on_error=requeue_on_error, **kwargs<EOL>)<EOL>
r""" Decorate a method as a handler of ``event_type`` events on the service called ``source_service``. :Parameters: source_service : str Name of the service that dispatches the event event_type : str Type of the event to handle ...
f7224:c2:m0
@property<EOL><INDENT>def broadcast_identifier(self):<DEDENT>
if self.handler_type is not BROADCAST:<EOL><INDENT>return None<EOL><DEDENT>if self.reliable_delivery:<EOL><INDENT>raise EventHandlerConfigurationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return uuid.uuid4().hex<EOL>
A unique string to identify a service instance for `BROADCAST` type handlers. The `broadcast_identifier` is appended to the queue name when the `BROADCAST` handler type is used. It must uniquely identify service instances that receive broadcasts. The default `broadcast_identifi...
f7224:c2:m1
@contextmanager<EOL>def run_services(config, *services, **kwargs):
kill_on_exit = kwargs.pop('<STR_LIT>', False)<EOL>runner = ServiceRunner(config)<EOL>for service in services:<EOL><INDENT>runner.add_service(service)<EOL><DEDENT>runner.start()<EOL>yield runner<EOL>if kill_on_exit:<EOL><INDENT>runner.kill()<EOL><DEDENT>else:<EOL><INDENT>runner.stop()<EOL><DEDENT>
Serves a number of services for a contextual block. The caller can specify a number of service classes then serve them either stopping (default) or killing them on exiting the contextual block. Example:: with run_services(config, Foobar, Spam) as runner: # interact with services and s...
f7225:m0
def add_service(self, cls):
service_name = get_service_name(cls)<EOL>container = self.container_cls(cls, self.config)<EOL>self.service_map[service_name] = container<EOL>
Add a service class to the runner. There can only be one service class for a given service name. Service classes must be registered before calling start()
f7225:c0:m3
def start(self):
service_names = '<STR_LIT:U+002CU+0020>'.join(self.service_names)<EOL>_log.info('<STR_LIT>', service_names)<EOL>SpawningProxy(self.containers).start()<EOL>_log.debug('<STR_LIT>', service_names)<EOL>
Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine.
f7225:c0:m4
def stop(self):
service_names = '<STR_LIT:U+002CU+0020>'.join(self.service_names)<EOL>_log.info('<STR_LIT>', service_names)<EOL>SpawningProxy(self.containers).stop()<EOL>_log.debug('<STR_LIT>', service_names)<EOL>
Stop all running containers concurrently. The method blocks until all containers have stopped.
f7225:c0:m5
def kill(self):
service_names = '<STR_LIT:U+002CU+0020>'.join(self.service_names)<EOL>_log.info('<STR_LIT>', service_names)<EOL>SpawningProxy(self.containers).kill()<EOL>_log.debug('<STR_LIT>', service_names)<EOL>
Kill all running containers concurrently. The method will block until all containers have stopped.
f7225:c0:m6
def wait(self):
try:<EOL><INDENT>SpawningProxy(self.containers, abort_on_error=True).wait()<EOL><DEDENT>except Exception:<EOL><INDENT>self.stop()<EOL>raise<EOL><DEDENT>
Wait for all running containers to stop.
f7225:c0:m7
@property<EOL><INDENT>def interface(self):<DEDENT>
return self<EOL>
An interface to this container for use by extensions.
f7226:c1:m2
def start(self):
_log.debug('<STR_LIT>', self)<EOL>self.started = True<EOL>with _log_time('<STR_LIT>', self):<EOL><INDENT>self.extensions.all.setup()<EOL>self.extensions.all.start()<EOL><DEDENT>
Start a container by starting all of its extensions.
f7226:c1:m3
def stop(self):
if self._died.ready():<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>return<EOL><DEDENT>if self._being_killed:<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>try:<EOL><INDENT>self._died.wait()<EOL><DEDENT>except:<EOL><INDENT>pass <EOL><DEDENT>return<EOL><DEDENT>_log.debug('<STR_LIT>', self)<EOL>with _log_time('<STR_LIT...
Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have stopped. After all e...
f7226:c1:m4
def kill(self, exc_info=None):
if self._being_killed:<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>try:<EOL><INDENT>self._died.wait()<EOL><DEDENT>except:<EOL><INDENT>pass <EOL><DEDENT>return<EOL><DEDENT>self._being_killed = True<EOL>if self._died.ready():<EOL><INDENT>_log.debug('<STR_LIT>', self)<EOL>return<EOL><DEDENT>if exc_info is not None:<EOL...
Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be raised by :meth:`~wait``.
f7226:c1:m5
def wait(self):
return self._died.wait()<EOL>
Block until the container has been stopped. If the container was stopped due to an exception, ``wait()`` will raise it. Any unhandled exception raised in a managed thread or in the worker lifecycle (e.g. inside :meth:`DependencyProvider.worker_setup`) results in the container b...
f7226:c1:m6
def spawn_worker(self, entrypoint, args, kwargs,<EOL>context_data=None, handle_result=None):
if self._being_killed:<EOL><INDENT>_log.info("<STR_LIT>")<EOL>raise ContainerBeingKilled()<EOL><DEDENT>service = self.service_cls()<EOL>worker_ctx = WorkerContext(<EOL>self, service, entrypoint, args, kwargs, data=context_data<EOL>)<EOL>_log.debug('<STR_LIT>', worker_ctx)<EOL>gt = self._worker_pool.spawn(<EOL>self._run...
Spawn a worker thread for running the service method decorated by `entrypoint`. ``args`` and ``kwargs`` are used as parameters for the service method. ``context_data`` is used to initialize a ``WorkerContext``. ``handle_result`` is an optional function which may be passed in b...
f7226:c1:m7
def spawn_managed_thread(self, fn, identifier=None):
if identifier is None:<EOL><INDENT>identifier = getattr(fn, '<STR_LIT>', "<STR_LIT>")<EOL><DEDENT>gt = eventlet.spawn(fn)<EOL>self._managed_threads[gt] = identifier<EOL>gt.link(self._handle_managed_thread_exited, identifier)<EOL>return gt<EOL>
Spawn a managed thread to run ``fn`` on behalf of an extension. The passed `identifier` will be included in logs related to this thread, and otherwise defaults to `fn.__name__`, if it is set. Any uncaught errors inside ``fn`` cause the container to be killed. It is the caller's respons...
f7226:c1:m8
def _kill_worker_threads(self):
num_workers = len(self._worker_threads)<EOL>if num_workers:<EOL><INDENT>_log.warning('<STR_LIT>', num_workers)<EOL>for worker_ctx, gt in list(self._worker_threads.items()):<EOL><INDENT>_log.warning('<STR_LIT>', worker_ctx)<EOL>gt.kill()<EOL><DEDENT><DEDENT>
Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker`
f7226:c1:m14
def _kill_managed_threads(self):
num_threads = len(self._managed_threads)<EOL>if num_threads:<EOL><INDENT>_log.warning('<STR_LIT>', num_threads)<EOL>for gt, identifier in list(self._managed_threads.items()):<EOL><INDENT>_log.warning('<STR_LIT>', identifier)<EOL>gt.kill()<EOL><DEDENT><DEDENT>
Kill any currently executing managed threads. See :meth:`ServiceContainer.spawn_managed_thread`
f7226:c1:m15
def get_wsgi_app(self):
return WsgiApp(self)<EOL>
Get the WSGI application used to process requests. This method can be overriden to apply WSGI middleware or replace the WSGI application all together.
f7227:c1:m5
def get_wsgi_server(<EOL>self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False<EOL>):
return wsgi.Server(<EOL>sock,<EOL>sock.getsockname(),<EOL>wsgi_app,<EOL>protocol=protocol,<EOL>debug=debug,<EOL>log=getLogger(__name__)<EOL>)<EOL>
Get the WSGI server used to process requests.
f7227:c1:m6
def get_subscriptions(self, socket_id):
con = self._get_connection(socket_id, create=False)<EOL>if con is None:<EOL><INDENT>return []<EOL><DEDENT>return sorted(con.subscriptions)<EOL>
Returns a list of all the subscriptions of a socket.
f7229:c3:m2
def subscribe(self, socket_id, channel):
con = self._get_connection(socket_id)<EOL>self.subscriptions.setdefault(channel, set()).add(socket_id)<EOL>con.subscriptions.add(channel)<EOL>
Subscribes a socket to a channel.
f7229:c3:m3
def unsubscribe(self, socket_id, channel):
con = self._get_connection(socket_id, create=False)<EOL>if con is not None:<EOL><INDENT>con.subscriptions.discard(channel)<EOL><DEDENT>try:<EOL><INDENT>self.subscriptions[channel].discard(socket_id)<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>
Unsubscribes a socket from a channel.
f7229:c3:m4
def broadcast(self, channel, event, data):
payload = self._server.serialize_event(event, data)<EOL>for socket_id in self.subscriptions.get(channel, ()):<EOL><INDENT>rv = self._server.sockets.get(socket_id)<EOL>if rv is not None:<EOL><INDENT>rv.socket.send(payload)<EOL><DEDENT><DEDENT>
Broadcasts an event to all sockets listening on a channel.
f7229:c3:m5
def unicast(self, socket_id, event, data):
payload = self._server.serialize_event(event, data)<EOL>rv = self._server.sockets.get(socket_id)<EOL>if rv is not None:<EOL><INDENT>rv.socket.send(payload)<EOL>return True<EOL><DEDENT>return False<EOL>
Sends an event to a single socket. Returns `True` if that worked or `False` if not.
f7229:c3:m6
@receive('<STR_LIT>')<EOL><INDENT>def handle_sqs_message(self, body):<DEDENT>
print(body)<EOL>return body<EOL>
This method is called by the `receive` entrypoint whenever a message sent to the given SQS queue.
f7231:c0:m0
@rpc<EOL><INDENT>def add_to_basket(self, item_code):<DEDENT>
stock_level = self.stock_rpc.check_stock(item_code)<EOL>if stock_level > <NUM_LIT:0>:<EOL><INDENT>self.user_basket.add(item_code)<EOL>self.fire_event("<STR_LIT>", item_code)<EOL>return item_code<EOL><DEDENT>raise ItemOutOfStockError(item_code)<EOL>
Add item identified by ``item_code`` to the shopping basket. This is a toy example! Ignore the obvious race condition.
f7247:c4:m0
@rpc<EOL><INDENT>def checkout(self):<DEDENT>
total_price = sum(self.stock_rpc.check_price(item)<EOL>for item in self.user_basket)<EOL>invoice = self.invoice_rpc.prepare_invoice(total_price)<EOL>self.payment_rpc.take_payment(invoice)<EOL>checkout_event_data = {<EOL>'<STR_LIT>': invoice,<EOL>'<STR_LIT>': list(self.user_basket)<EOL>}<EOL>self.fire_event("<STR_LIT>",...
Take payment for all items in the shopping basket.
f7247:c4:m1
@rpc<EOL><INDENT>def check_price(self, item_code):<DEDENT>
try:<EOL><INDENT>return self.warehouse[item_code]['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ItemDoesNotExistError(item_code)<EOL><DEDENT>
Check the price of an item.
f7247:c6:m0
@rpc<EOL><INDENT>def check_stock(self, item_code):<DEDENT>
try:<EOL><INDENT>return self.warehouse[item_code]['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ItemDoesNotExistError(item_code)<EOL><DEDENT>
Check the stock level of an item.
f7247:c6:m1
@rpc<EOL><INDENT>@timer(<NUM_LIT:100>)<EOL>def monitor_stock(self):<DEDENT>
raise NotImplementedError()<EOL>
Periodic stock monitoring method. Can also be triggered manually over RPC. This is an expensive process that we don't want to exercise during integration testing...
f7247:c6:m2
@event_handler('<STR_LIT>', "<STR_LIT>")<EOL><INDENT>def dispatch_items(self, event_data):<DEDENT>
raise NotImplementedError()<EOL>
Dispatch items from stock on successful checkouts. This is an expensive process that we don't want to exercise during integration testing...
f7247:c6:m3
@rpc<EOL><INDENT>def prepare_invoice(self, amount):<DEDENT>
address = self.get_user_details().get('<STR_LIT:address>')<EOL>fullname = self.get_user_details().get('<STR_LIT>')<EOL>username = self.get_user_details().get('<STR_LIT:username>')<EOL>msg = "<STR_LIT>".format(fullname, amount)<EOL>invoice = {<EOL>'<STR_LIT:message>': msg,<EOL>'<STR_LIT>': amount,<EOL>'<STR_LIT>': usern...
Prepare an invoice for ``amount`` for the current user.
f7247:c8:m0
@rpc<EOL><INDENT>def take_payment(self, invoice):<DEDENT>
raise NotImplementedError()<EOL>
Take payment from a customer according to ``invoice``. This is an expensive process that we don't want to exercise during integration testing...
f7247:c9:m0
@task<EOL>def develop_link(options, info):
project_dir = ph.path(__file__).realpath().parent<EOL>info('<STR_LIT>')<EOL>version_info = ch.conda_version_info('<STR_LIT>')<EOL>if version_info.get('<STR_LIT>') is not None:<EOL><INDENT>info('<STR_LIT>')<EOL>ch.conda_exec('<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>verbose=True)<EOL><DEDENT>else:<EOL><INDENT>info('<ST...
Prepare development environment. Perform the following steps: - Uninstall ``dmf_control_board_firmware`` if installed as Conda package. - Install build and run-time Conda dependencies. - Link working ``.pioenvs`` directory into Conda ``Library`` directory to make development versions of compiled firmware binari...
f7262:m5
@task<EOL>def develop_unlink(options, info):
project_dir = ph.path(__file__).realpath().parent<EOL>info('<STR_LIT>')<EOL>pio_bin_dir = pioh.conda_bin_path()<EOL>fw_bin_dir = pio_bin_dir.joinpath('<STR_LIT>')<EOL>if fw_bin_dir.exists():<EOL><INDENT>fw_config_ini = fw_bin_dir.joinpath('<STR_LIT>')<EOL>if fw_config_ini.exists():<EOL><INDENT>fw_config_ini.unlink()<EO...
Prepare development environment. Perform the following steps: - Unlink working ``.pioenvs`` directory into Conda ``Library`` directory. - Unlink ``dmf_control_board_firmware`` Python package from site packages directory. See Also -------- :func:`develop_link`
f7262:m6
def disttar_string(target, source, env):
return '<STR_LIT>' % target[<NUM_LIT:0>]<EOL>
This is what gets printed on the console. We'll strip out the list or source files, since it tends to get very long. If you want to see the contents, the easiest way is to uncomment the line 'Adding to TAR file' below.
f7265:m2
def disttar(target, source, env):
import tarfile<EOL>env_dict = env.Dictionary()<EOL>if env_dict.get("<STR_LIT>") in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>tar_format = env_dict["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>tar_format = "<STR_LIT>"<EOL><DEDENT>base_name = str(target[<NUM_LIT:0>]).split('<STR_LIT>')[<NUM_LIT:0>]<EOL>(target_dir, dir_name)...
tar archive builder
f7265:m3
def disttar_suffix(env, sources):
env_dict = env.Dictionary()<EOL>if env_dict.has_key("<STR_LIT>") and env_dict["<STR_LIT>"] in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>return "<STR_LIT>" + env_dict["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>
tar archive suffix generator
f7265:m4
def generate(env):
disttar_action=SCons.Action.Action(disttar, disttar_string)<EOL>env['<STR_LIT>']['<STR_LIT>'] = Builder(<EOL>action=disttar_action<EOL>, emitter=disttar_emitter<EOL>, suffix = disttar_suffix<EOL>, target_factory = env.fs.Entry<EOL>)<EOL>env.AppendUnique(<EOL>DISTTAR_FORMAT = '<STR_LIT>'<EOL>)<EOL>
Add builders and construction variables for the DistTar builder.
f7265:m5
def exists(env):
try:<EOL><INDENT>import os<EOL>import tarfile<EOL><DEDENT>except ImportError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
Make sure this tool exists.
f7265:m6
def fit_fb_calibration(df, calibration):
<EOL>R_fb = pd.Series([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>C_fb = pd.Series(len(calibration.C_fb) * [<NUM_LIT>])<EOL>def error(p0, df, calibration):<EOL><INDENT>Z = <NUM_LIT><EOL>R_fb = p0[<NUM_LIT:0>]<EOL>if len(p0) == <NUM_LIT:2>:<EOL><INDENT>C_fb = p0[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDEN...
Fit feedback calibration data to solve for values of `C_fb[:]` and `R_fb[:]`. Returns a `pandas.DataFrame` indexed by the feedback resistor/capacitance index, and with the following columns: - Model: Either with parasitic capacitance term or not. - N: Number of samples used for fit. - F: F-value - p-value: p-value...
f7270:m2
def apply_calibration(df, calibration_df, calibration):
from dmf_control_board_firmware import FeedbackResults<EOL>for i, (fb_resistor, R_fb, C_fb) in calibration_df[['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']].iterrows():<EOL><INDENT>calibration.R_fb[int(fb_resistor)] = R_fb<EOL>calibration.C_fb[int(fb_resistor)] = C_fb<EOL><DEDENT>cleaned_df = df.dropna()<EOL>grouped = cleane...
Apply calibration values from `fit_fb_calibration` result to `calibration` object.
f7270:m3
def swap_default(mode, equation, symbol_names, default, **kwargs):
if mode == '<STR_LIT>':<EOL><INDENT>swap_f = _subs<EOL>default_swap_f = _subs<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>swap_f = _limit<EOL>default_swap_f = _subs<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>swap_f = _subs<EOL>default_swap_f = _limit<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('''<STR_L...
Given a `sympy` equation or equality, along with a list of symbol names, substitute the specified default value for each symbol for which a value is not provided through a keyword argument. For example, consider the following equality: >>> sp.pprint(H) V₂ Z₂ ── = ── V₁ Z₁ Let us substitute a default value of 1 f...
f7271:m4
def z_transfer_functions():
<EOL>V1, V2, Z1, Z2 = sp.symbols('<STR_LIT>')<EOL>xfer_funcs = pd.Series([sp.Eq(V2 / Z2, V1 / (Z1 + Z2)),<EOL>sp.Eq(V2 / V1, Z2 / Z1)],<EOL>index=[<NUM_LIT:1>, <NUM_LIT:2>])<EOL>xfer_funcs.index.name = '<STR_LIT>'<EOL>return xfer_funcs<EOL>
r''' Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits. According to the figure below, the transfer function describes the following relationship:: # Hardware V1 # # Hardware V2 #...
f7271:m5
def rc_transfer_function(eq, Zs=None):
if Zs is None:<EOL><INDENT>Zs = [s.name for s in eq.atoms(sp.Symbol) if s.name.startswith('<STR_LIT>')]<EOL><DEDENT>result = eq<EOL>cre_Z = re.compile(r'<STR_LIT>')<EOL>sub_params = [(z, sp.symbols('<STR_LIT>' % (s, s)))<EOL>for z, s in [(Z, cre_Z.match(Z).group('<STR_LIT>'))<EOL>for Z in Zs]]<EOL>for Z, (R, C, omega) ...
Substitute resistive and capacitive components for all ``Zs`` terms _(all terms starting with ``Z`` by default)_ in the provided equation, where $Z$ is equivalent to parallel resistive and capacitive impedances, as shown below. .. code-block:: none Z_C ┌───┐ ...
f7271:m6
@lru_cache(maxsize=<NUM_LIT>)<EOL>def get_transfer_function(hardware_major_version, solve_for=None, Zs=None):
xfer_func = z_transfer_functions()[hardware_major_version]<EOL>symbols = OrderedDict([(s.name, s)<EOL>for s in xfer_func.atoms(sp.Symbol)])<EOL>if Zs is None:<EOL><INDENT>Zs = [s for s in symbols if s != solve_for and s.startswith('<STR_LIT>')]<EOL><DEDENT>H = rc_transfer_function(xfer_func, Zs)<EOL>if solve_for is Non...
Parameters ---------- hardware_major_version : int Major version of control board hardware *(1 or 2)*. solve_for : str, optional Rearrange equality with ``solve_for`` symbol as LHS. Zs : list List of impedance (i.e., ``Z``) to substitute with resistive and capacitive terms. By default, all ``Z`` terms ar...
f7271:m7
def compute_from_transfer_function(hardware_major_version, solve_for,<EOL>**kwargs):
symbolic = kwargs.pop('<STR_LIT>', False)<EOL>Zs = tuple([s for s in kwargs if s != solve_for and s.startswith('<STR_LIT>')])<EOL>if not Zs:<EOL><INDENT>Zs = None<EOL><DEDENT>result = get_transfer_function(hardware_major_version, solve_for=solve_for,<EOL>Zs=Zs)<EOL>Rs = set([s.name for s in result.atoms(sp.Symbol)<EOL>...
Conventions: - Symbols starting with ``Z`` are assumed to be impedance terms. - Symbols starting with ``R`` are assumed to be resistive impedance terms. - Symbols starting with ``C`` are assumed to be capacitive impedance terms. - ``omega`` is assumed to be an angular frequency term. - ``f`` is assumed to be a...
f7271:m8
def plot_stat_summary(df, fig=None):
if fig is None:<EOL><INDENT>fig = plt.figure(figsize=(<NUM_LIT:8>, <NUM_LIT:8>))<EOL><DEDENT>grid = GridSpec(<NUM_LIT:3>, <NUM_LIT:2>)<EOL>stats = calculate_stats(df, groupby=['<STR_LIT>',<EOL>'<STR_LIT>']).dropna()<EOL>for i, stat in enumerate(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>axis = fig.add_subplo...
Plot stats grouped by test capacitor load _and_ frequency. In other words, we calculate the mean of all samples in the data frame for each test capacitance and frequency pairing, plotting the following stats: - Root mean squared error - Coefficient of variation - Bias ## [Coefficient of variation][1] ## > In pro...
f7272:m7
def measure_board_rms(control_board, n_samples=<NUM_LIT:10>, sampling_ms=<NUM_LIT:10>,<EOL>delay_between_samples_ms=<NUM_LIT:0>):
try:<EOL><INDENT>results = control_board.measure_impedance(n_samples, sampling_ms,<EOL>delay_between_samples_ms,<EOL>True, True, [])<EOL><DEDENT>except RuntimeError:<EOL><INDENT>logger.warning('<STR_LIT>'<EOL>'<STR_LIT>', exc_info=True)<EOL>data = pd.DataFrame(None, columns=['<STR_LIT>',<EOL>'<STR_LIT>'])<EOL><DEDENT>e...
Read RMS voltage samples from control board high-voltage feedback circuit.
f7275:m0
def find_good(control_board, actuation_steps, resistor_index, start_index,<EOL>end_index):
lower = start_index<EOL>upper = end_index<EOL>while lower < upper - <NUM_LIT:1>:<EOL><INDENT>index = lower + (upper - lower) / <NUM_LIT:2><EOL>v = actuation_steps[index]<EOL>control_board.set_waveform_voltage(v)<EOL>data = measure_board_rms(control_board)<EOL>valid_data = data[data['<STR_LIT>'] >= <NUM_LIT:0>]<EOL>if (...
Use a binary search over the range of provided actuation_steps to find the maximum actuation voltage that is measured by the board feedback circuit using the specified feedback resistor.
f7275:m1
def resistor_max_actuation_readings(control_board, frequencies,<EOL>oscope_reading_func):
<EOL>control_board.set_waveform_voltage(<NUM_LIT:0>)<EOL>control_board.auto_adjust_amplifier_gain = False<EOL>control_board.amplifier_gain = <NUM_LIT:1.><EOL>target_voltage = <NUM_LIT:0.1><EOL>control_board.set_waveform_voltage(target_voltage)<EOL>oscope_rms = oscope_reading_func()<EOL>estimated_amplifier_gain = oscope...
For each resistor in the high-voltage feedback resistor bank, read the board measured voltage and the oscilloscope measured voltage for an actuation voltage that nearly saturates the feedback resistor. By searching for an actuation voltage near saturation, the signal-to-noise ratio is minimized.
f7275:m2
def fit_feedback_params(calibration, max_resistor_readings):
R1 = <NUM_LIT><EOL>def fit_resistor_params(x):<EOL><INDENT>resistor_index = x['<STR_LIT>'].values[<NUM_LIT:0>]<EOL>p0 = [calibration.R_hv[resistor_index],<EOL>calibration.C_hv[resistor_index]]<EOL>def error(p, df, R1):<EOL><INDENT>v1 = compute_from_transfer_function(calibration.hw_version.major,<EOL>'<STR_LIT>',<EOL>V2...
Fit model of control board high-voltage feedback resistor and parasitic capacitance values based on measured voltage readings.
f7275:m3