code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# type: (Hook) -> None try: func, args_gen = self.hooked[type(hook)] except (KeyError, TypeError): return else: hook(func, args_gen())
def on_hook(self, hook)
Takes a hook, and optionally calls hook.run on a function
6.259832
7.048492
0.888109
# type: (str, str) -> bool assert initial_state in self._allowed, \ "%s is not in %s" % (initial_state, list(self._allowed)) return target_state in self._allowed[initial_state]
def transition_allowed(self, initial_state, target_state)
Check if a transition between two states is allowed
2.938083
3.045439
0.964748
# type: (str, *str) -> None allowed_states = list(allowed_states) self._allowed.setdefault(initial_state, set()).update(allowed_states) for state in allowed_states + [initial_state]: if state not in self.possible_states: self.possible_states.append(st...
def set_allowed(self, initial_state, *allowed_states)
Add an allowed transition from initial_state to allowed_states
2.789681
2.705711
1.031034
# type: (AName, ACmd) -> ADefine value = subprocess.check_output(cmd, shell=True).rstrip("\n") return Define(name, value)
def cmd_string(name, cmd)
Define a string parameter coming from a shell command to be used within this YAML file. Trailing newlines will be stripped.
8.581947
7.966574
1.077244
# type: (AEnvName, AEnvValue) -> ADefine os.environ[name] = value return Define(name, value)
def export_env_string(name, value)
Exports an environment variable with the given value
8.572281
9.974096
0.859454
# type: (AModuleName, AModulePath) -> ADefine define = Define(name, path) assert os.path.isdir(path), "%r doesn't exist" % path name = "malcolm.modules.%s" % name import_package_from_path(name, path) return define
def module_path(name, path)
Load an external malcolm module (e.g. ADCore/etc/malcolm)
7.305158
7.04708
1.036622
# Called in tornado loop try: self.log.debug("Got message %s", message) d = json_decode(message) response = deserialize_object(d, Response) if isinstance(response, (Return, Error)): request = self._request_lookup.pop(response.id) ...
def on_message(self, message)
Pass response from server to process receive queue Args: message(str): Received message
6.020989
6.116374
0.984405
# Send a root Subscribe to the server subscribe = Subscribe(path=[mri], delta=True) done_queue = Queue() def handle_response(response): # Called from tornado if not isinstance(response, Delta): # Return or Error is the end of our subscrip...
def sync_proxy(self, mri, block)
Abstract method telling the ClientComms to sync this proxy Block with its remote counterpart. Should wait until it is connected Args: mri (str): The mri for the remote block block (BlockModel): The local proxy Block to keep in sync
8.068145
8.517938
0.947195
q = Queue() request = Put( path=[mri, attribute_name, "value"], value=value) request.set_callback(q.put) IOLoopHelper.call(self._send_request, request) response = q.get() if isinstance(response, Error): raise response.message ...
def send_put(self, mri, attribute_name, value)
Abstract method to dispatch a Put to the server Args: mri (str): The mri of the Block attribute_name (str): The name of the Attribute within the Block value: The value to put
4.268103
4.724199
0.903455
q = Queue() request = Post( path=[mri, method_name], parameters=params) request.set_callback(q.put) IOLoopHelper.call(self._send_request, request) response = q.get() if isinstance(response, Error): raise response.message ...
def send_post(self, mri, method_name, **params)
Abstract method to dispatch a Post to the server Args: mri (str): The mri of the Block method_name (str): The name of the Method within the Block params: The parameters to send Returns: The return results from the server
4.680954
5.256094
0.890577
# type: (Type[T], PartInfo) -> Dict[str, List[T]] filtered = OrderedDict() for part_name, info_list in part_info.items(): if info_list is None or isinstance(info_list, Exception): continue info_list = [i for i in info_list if isinstance(i, cls)] ...
def filter_parts(cls, part_info)
Filter the part_info dict looking for instances of our class Args: part_info (dict): {part_name: [Info] or None} as returned from Controller.run_hook() Returns: dict: {part_name: [info]} where info is a subclass of cls
2.654097
3.156587
0.840812
# type: (Type[T], PartInfo) -> List[T] filtered = [] for info_list in cls.filter_parts(part_info).values(): filtered += info_list return filtered
def filter_values(cls, part_info)
Filter the part_info dict list looking for instances of our class Args: part_info (dict): {part_name: [Info] or None} as returned from Controller.run_hook() Returns: list: [info] where info is a subclass of cls
4.598463
8.274275
0.555754
# type: (Type[T], PartInfo, str) -> T filtered = cls.filter_values(part_info) if len(filtered) != 1: if error_msg is None: error_msg = "Expected a single %s, got %s of them" % \ (cls.__name__, len(filtered)) raise BadVa...
def filter_single_value(cls, part_info, error_msg=None)
Filter the part_info dict list looking for a single instance of our class Args: part_info (dict): {part_name: [Info] or None} as returned from Controller.run_hook() error_msg (str, optional): Specific error message to show if there isn't a single ...
2.890009
4.101336
0.70465
# type: (List[str]) -> None for mri in mris: for pv in self._pvs.pop(mri, {}).values(): # Close pv with force destroy on, this will call # onLastDisconnect pv.close(destroy=True, sync=True, timeout=1.0)
def disconnect_pv_clients(self, mris)
Disconnect anyone listening to any of the given mris
7.747232
8.06942
0.960073
new_tags = [t for t in tags if not t.startswith("sourcePort:")] new_tags.append(self.source_port_tag(connected_value)) return new_tags
def with_source_port_tag(self, tags, connected_value)
Add a Source Port tag to the tags list, removing any other Source Ports
3.026642
3.104641
0.974877
# type: (Sequence[str]) -> Union[Tuple[bool, Port, str], None] for tag in tags: match = port_tag_re.match(tag) if match: source_sink, port, extra = match.groups() return source_sink == "source", cls(port), extra
def port_tag_details(cls, tags)
Search tags for port info, returning it Args: tags: A list of tags to check Returns: None or (is_source, port, connected_value|disconnected_value) where port is one of the Enum entries of Port
4.699965
5.640651
0.833231
with self.changes_squashed: initial_state = self.state.value if self.state_set.transition_allowed( initial_state=initial_state, target_state=state): self.log.debug( "%s: Transitioning from %s to %s", sel...
def transition(self, state, message="")
Change to a new state if the transition is allowed Args: state (str): State to transition to message (str): Message if the transition is to a fault state
4.325396
4.286952
1.008968
done_queue = Queue() self._queues[mri] = done_queue update_fields = set() def callback(value=None): if isinstance(value, Exception): # Disconnect or Cancelled or RemoteError if isinstance(value, Disconnected): # We...
def sync_proxy(self, mri, block)
Abstract method telling the ClientComms to sync this proxy Block with its remote counterpart. Should wait until it is connected Args: mri (str): The mri for the remote block block (BlockModel): The local proxy Block to keep in sync
6.677158
6.902632
0.967335
path = attribute_name + ".value" typ, value = convert_to_type_tuple_value(serialize_object(value)) if isinstance(typ, tuple): # Structure, make into a Value _, typeid, fields = typ value = Value(Type(fields, typeid), value) try: se...
def send_put(self, mri, attribute_name, value)
Abstract method to dispatch a Put to the server Args: mri (str): The mri of the Block attribute_name (str): The name of the Attribute within the Block value: The value to put
11.331691
11.271976
1.005298
typ, parameters = convert_to_type_tuple_value(serialize_object(params)) uri = NTURI(typ[2]) uri = uri.wrap( path="%s.%s" % (mri, method_name), kws=parameters, scheme="pva" ) value = self._ctxt.rpc(mri, uri, timeout=None) retur...
def send_post(self, mri, method_name, **params)
Abstract method to dispatch a Post to the server Args: mri (str): The mri of the Block method_name (str): The name of the Method within the Block params: The parameters to send Returns: The return results from the server
12.351474
13.995219
0.88255
# type: (Context, Model, str) -> Any with self._lock: child = data[child_name] child_view = make_view(self, context, child) return child_view
def make_view(self, context, data, child_name)
Make a child View of data[child_name]
4.910954
4.480222
1.096141
# type: (Get) -> CallbackResponses data = self._block for i, endpoint in enumerate(request.path[1:]): try: data = data[endpoint] except KeyError: if hasattr(data, "typeid"): typ = data.typeid el...
def _handle_get(self, request)
Called with the lock taken
6.793257
6.792539
1.000106
# type: (Put) -> CallbackResponses attribute_name = request.path[1] attribute = self._block[attribute_name] assert isinstance(attribute, AttributeModel), \ "Cannot Put to %s which is a %s" % (attribute.path, type(attribute)) self.check_field_writeable(attrib...
def _handle_put(self, request)
Called with the lock taken
7.047996
7.057737
0.99862
# type: (Post) -> CallbackResponses method_name = request.path[1] method = self._block[method_name] assert isinstance(method, MethodModel), \ "Cannot Post to %s which is a %s" % (method.path, type(method)) self.check_field_writeable(method) post_fun...
def _handle_post(self, request)
Called with the lock taken
7.984484
7.934143
1.006345
context.when_matches( [mri, "state", "value"], StatefulStates.READY, bad_values=[StatefulStates.FAULT, StatefulStates.DISABLED], timeout=timeout)
def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT)
Wait until a Block backed by a StatefulController has initialized Args: context (Context): The context to use to make the child block mri (str): The mri of the child block timeout (float): The maximum time to wait
13.074094
14.352221
0.910946
if self._state == self.RUNNING: self._context.wait_all_futures([self], timeout) return self.__get_result()
def result(self, timeout=None)
Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. ...
9.328039
10.605557
0.879543
if self._state == self.RUNNING: self._context.wait_all_futures([self], timeout) return self._exception
def exception(self, timeout=None)
Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn't done. If None, then there is no limit on the wait time. Returns: The exception raised by the ca...
9.477594
10.929092
0.86719
self._result = result self._state = self.FINISHED
def set_result(self, result)
Sets the return value of work associated with the future. Should only be used by Task and unit tests.
7.958906
7.051369
1.128704
assert isinstance(exception, Exception), \ "%r should be an Exception" % exception self._exception = exception self._state = self.FINISHED
def set_exception(self, exception)
Sets the result of the future as being the given exception. Should only be used by Task and unit tests.
4.901731
4.656266
1.052717
names = [self.__module__, self.__class__.__name__] for field, value in sorted(fields.items()): names.append(value) # names should be something like this for one field: # ["malcolm.modules.scanning.controllers.runnablecontroller", # "RunnableController", ...
def set_logger(self, **fields)
Change the name of the logger that log.* should call Args: **fields: Extra fields to be logged. Logger name will be: ".".join([<module_name>, <cls_name>] + fields_sorted_on_key)
6.268492
5.503864
1.138926
# type: (Any) -> Tuple[Callback, Return] response = Return(id=self.id, value=value) return self.callback, response
def return_response(self, value=None)
Create a Return Response object to signal a return value
7.70317
8.197108
0.939742
# type: (Exception) -> Tuple[Callback, Error] response = Error(id=self.id, message=exception) log.exception("Exception raised for request %s", self) return self.callback, response
def error_response(self, exception)
Create an Error Response object to signal an error
7.352543
8.170385
0.899902
# type: (Controller, Context, Any) -> Any if isinstance(data, BlockModel): # Make an Block View view = _make_view_subclass(Block, controller, context, data) elif isinstance(data, AttributeModel): # Make an Attribute View view = Attribute(controller, context, data) el...
def make_view(controller, context, data)
Make a View subclass containing properties specific for given data Args: controller (Controller): The child controller that hosts the data context (Context): The context the parent has made that the View should use for manipulating the data data (Model): The actual data that con...
2.572921
2.744723
0.937407
self._context.put(self._data.path + ["value"], value, timeout=timeout)
def put_value(self, value, timeout=None)
Put a value to the Attribute and wait for completion
11.15112
10.295312
1.083126
# type: (float) -> float exposure = duration - self.frequency_accuracy * duration / 1000000.0 - \ self.readout_time assert exposure > 0.0, \ "Exposure time %s too small when deadtime taken into account" % ( exposure,) return exposur...
def calculate_exposure(self, duration)
Calculate the exposure to set the detector to given the duration of the frame and the readout_time and frequency_accuracy
7.979671
6.560277
1.216362
# type: (Union[Notifier, DummyNotifier], List[str]) -> None # This function should either change from the DummyNotifier or to # the DummyNotifier, never between two valid notifiers assert self.notifier is Model.notifier or notifier is Model.notifier, \ "Already have ...
def set_notifier_path(self, notifier, path)
Sets the notifier, and the path from the path from block root Args: notifier (Notifier): The Notifier to tell when endpoint data changes path (list): The absolute path to get to this object
4.568337
4.741
0.963581
# type: (List[str], Any) -> None if len(path) > 1: # This is for a child self[path[0]].apply_change(path[1:], *args) else: # This is for us assert len(path) == 1 and len(args) == 1, \ "Cannot process change %s" % ([self.pat...
def apply_change(self, path, *args)
Take a single change from a Delta and apply it to this model
3.530807
3.582433
0.985589
# type: (Any) -> AttributeModel attr = self.attribute_class(meta=self, value=initial_value) return attr
def create_attribute_model(self, initial_value=None)
Make an AttributeModel instance of the correct type for this Meta Args: initial_value: The initial value the Attribute should take Returns: AttributeModel: The created attribute model instance
6.041494
9.01438
0.670206
# type: (Anno, bool, **Any) -> VMeta ret = cls(description=anno.description, writeable=writeable, **kwargs) widget = ret.default_widget() if widget != Widget.NONE: ret.set_tags([widget.tag()]) return ret
def from_annotype(cls, anno, writeable, **kwargs)
Return an instance of this class from an Anno
7.45753
7.672043
0.97204
# type: (Union[Sequence[type], type], bool, bool) -> Any if not isinstance(types, Sequence): types = [types] def decorator(subclass): for typ in types: cls._annotype_lookup[(typ, is_array, is_mapping)] = subclass return subclass ...
def register_annotype_converter(cls, types, is_array=False, is_mapping=False)
Register this class as a converter for Anno instances
3.127639
3.395081
0.921227
# type: (Anno) -> Type[VMeta] if hasattr(anno.typ, "__bases__"): # This is a proper type bases = inspect.getmro(anno.typ) else: # This is a numpy dtype bases = [anno.typ] for typ in bases: key = (typ, bool(anno.is_array...
def lookup_annotype_converter(cls, anno)
Look up a vmeta based on an Anno
4.496309
3.845541
1.169227
# type: (Any, bool, Alarm, TimeStamp) -> Any value = self.meta.validate(value) if set_alarm_ts: if alarm is None: alarm = Alarm.ok else: alarm = deserialize_object(alarm, Alarm) if ts is None: ts = TimeS...
def set_value(self, value, set_alarm_ts=True, alarm=None, ts=None)
Set value, calculating alarm and ts if requested
3.29024
3.189674
1.031529
# type: (Any, Alarm, TimeStamp) -> None with self.notifier.changes_squashed: # Assume they are of the right format self.value = value self.notifier.add_squashed_change(self.path + ["value"], value) if alarm is not self.alarm: self....
def set_value_alarm_ts(self, value, alarm, ts)
Set value with pre-validated alarm and timeStamp
3.845447
3.702192
1.038695
# type: (AName, ASleep) -> AGreeting print("Manufacturing greeting...") sleep_for(sleep) greeting = "Hello %s" % name return greeting
def greet(self, name, sleep=0)
Optionally sleep <sleep> seconds, then return a greeting to <name>
10.406839
9.925767
1.048467
VERSION_FILE = '../malcolm/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError( 'Unable to find version string in {0}.'.format(VERSION_FILE))
def get_version()
Extracts the version number from the version.py file.
2.376271
2.224155
1.068392
# create the axes dimensions attribute, a comma separated list giving size # of the axis dimensions padded with . for the detector dimensions and # multidimensional dimensions pad_dims = [] for d in generator.dimensions: if len(d.axes) == 1: pad_dims.append("%s_set" % d.axe...
def add_nexus_nodes(generator, vds_file_path)
Add in the additional information to make this into a standard nexus format file:- (a) create the standard structure under the 'entry' group with a subgroup for each dataset. 'set_bases' lists the data sets we make here. (b) save a dataset for each axis in each of the dimensions of the scan represen...
4.812738
4.491046
1.07163
response_queue = self.send(message) response = self.recv(response_queue, timeout) return response
def send_recv(self, message, timeout=10.0)
Send a message to a PandABox and wait for the response Args: message (str): The message to send timeout (float): How long to wait before raising queue.Empty Returns: str: The response
4.371173
6.144516
0.711394
while True: message, response_queue = self._send_queue.get() if message is self.STOP: break try: self._response_queues.put(response_queue) self._socket.send(message) except Exception: # pylint:disable=broad...
def _send_loop(self)
Service self._send_queue, sending requests to server
3.63375
3.354136
1.083364
response_queue = self._response_queues.get(timeout=0.1) response_queue.put(resp) self._completed_response_lines = [] self._is_multiline = None
def _respond(self, resp)
Respond to the person waiting
7.622832
7.862885
0.96947
self._completed_response_lines = [] self._is_multiline = None lines_iterator = self._get_lines() while True: try: line = next(lines_iterator) if self._is_multiline is None: self._is_multiline = line.startswith("!") ...
def _recv_loop(self)
Service socket recv, returning responses to the correct queue
3.175354
3.052706
1.040177
response_queues = OrderedDict() for parameter in parameter_list: response_queues[parameter] = self.send(request % parameter) return response_queues
def parameterized_send(self, request, parameter_list)
Send batched requests for a list of parameters Args: request (str): Request to send, like "%s.*?\n" parameter_list (list): parameters to format with, like ["TTLIN", "TTLOUT"] Returns: dict: {parameter: response_queue}
5.087246
3.672064
1.385391
child.exposure.put_value(duration) child.acquirePeriod.put_value(duration) readout_time = child.acquirePeriod.value - child.exposure.value # It seems that the difference between acquirePeriod and exposure # doesn't tell the whole story, we seem to need an additional bit ...
def get_readout_time(self, child, duration)
Calculate the readout time of the detector from the EPICS driver: - Set exposure and acquire period to same value - Acquire period will be set to lowest acceptable value - Difference will be readout time (this value is affected by detector settings)
6.684188
5.727947
1.166943
# type: (Request) -> None if isinstance(request, Put) and request.path[0] == self.mri: # This means the context we were passed has just made a Put request # so mark the field as "we_modified" so it doesn't screw up the # modified led attribute_nam...
def notify_dispatch_request(self, request)
Will be called when a context passed to a hooked function is about to dispatch a request
9.774898
10.277311
0.951114
# type: (AContext, APortMap, str) -> None # Find the Source Ports to connect to if connected_to: # Calculate a lookup of the Source Port "name" to type source_port_lookup = self._source_port_lookup( ports.get(connected_to, [])) else: ...
def sever_sink_ports(self, context, ports, connected_to=None)
Conditionally sever Sink Ports of the child. If connected_to is then None then sever all, otherwise restrict to connected_to's Source Ports Args: context (Context): The context to use ports (dict): {part_name: [PortInfo]} connected_to (str): Restrict severing...
4.866657
4.952299
0.982707
# type: (APortMap) -> None # Calculate a lookup of Source Port connected_value to part_name source_port_lookup = {} for part_name, port_infos in SourcePortInfo.filter_parts(ports).items(): for port_info in port_infos: source_port_lookup[port_info.conn...
def calculate_part_visibility(self, ports)
Calculate what is connected to what Args: ports: {part_name: [PortInfo]} from other ports
3.40332
3.509213
0.969824
# type: (Subscribe) -> CallbackResponses ret = self._tree.handle_subscribe(request, request.path[1:]) self._subscription_keys[request.generate_key()] = request return ret
def handle_subscribe(self, request)
Handle a Subscribe request from outside. Called with lock taken
11.824522
13.045299
0.90642
# type: (Unsubscribe) -> CallbackResponses subscribe = self._subscription_keys.pop(request.generate_key()) ret = self._tree.handle_unsubscribe(subscribe, subscribe.path[1:]) return ret
def handle_unsubscribe(self, request)
Handle a Unsubscribe request from outside. Called with lock taken
14.835044
15.8172
0.937906
# type: (List[str], Any) -> None assert self._squashed_count, "Called while not squashing changes" self._squashed_changes.append([path[1:], data])
def add_squashed_change(self, path, data)
Register a squashed change to a particular path Args: path (list): The path of what has changed, relative from Block data (object): The new data
6.203625
11.265969
0.550652
# type: (List[List]) -> CallbackResponses ret = [] child_changes = {} for change in changes: # Add any changes that our children need to know about self._add_child_change(change, child_changes) # If we have update subscribers, serialize at this l...
def notify_changes(self, changes)
Set our data and notify anyone listening Args: changes (list): [[path, optional data]] where path is the path to what has changed, and data is the unserialized object that has changed Returns: list: [(callback, Response)] that need to be called
3.874648
4.067752
0.952528
# type: (Any) -> Dict[str, List] self.data = data child_change_dict = {} # Reflect change of data to children for name in self.children: child_data = getattr(data, name, None) if child_data is None: # Deletion child...
def _update_data(self, data)
Set our data and notify any subscribers of children what has changed Args: data (object): The new data Returns: dict: {child_name: [path_list, optional child_data]} of the change that needs to be passed to a child as a result of this
4.059129
3.783309
1.072904
# type: (Subscribe, List[str]) -> CallbackResponses ret = [] if path: # Recurse down name = path[0] if name not in self.children: self.children[name] = NotifierNode( getattr(self.data, name, None), self) ...
def handle_subscribe(self, request, path)
Add to the list of request to notify, and notify the initial value of the data held Args: request (Subscribe): The subscribe request path (list): The relative path from ourself Returns: list: [(callback, Response)] that need to be called
4.752551
4.833102
0.983334
# type: (Subscribe, List[str]) -> CallbackResponses ret = [] if path: # Recurse down name = path[0] child = self.children[name] ret += child.handle_unsubscribe(request, path[1:]) if not child.children and not child.update_reque...
def handle_unsubscribe(self, request, path)
Remove from the notifier list and send a return Args: request (Subscribe): The original subscribe request path (list): The relative path from ourself Returns: list: [(callback, Response)] that need to be called
3.738715
3.836564
0.974496
# type: (AName, ADescription, AStringDefault) -> AAnno args = common_args(name, default) return Anno(description, typ=str, **args)
def string(name, description, default=None)
Add a string parameter to be passed when instantiating this YAML file
11.537047
14.268586
0.808563
# type: (AName, ADescription, AFloat64Default) -> AAnno args = common_args(name, default) return Anno(description, typ=float, **args)
def float64(name, description, default=None)
Add a float64 parameter to be passed when instantiating this YAML file
10.033057
12.558155
0.798928
# type: (AName, ADescription, AInt32Default) -> AAnno args = common_args(name, default) return Anno(description, typ=int, **args)
def int32(name, description, default=None)
Add an int32 parameter to be passed when instantiating this YAML file
10.122073
12.479377
0.811104
# type: (str, str) -> Callable[..., List[Controller]] sections, yamlname, docstring = Section.from_yaml(yaml_path, filename) yamldir = os.path.dirname(yaml_path) # Check we have only one controller controller_sections = [s for s in sections if s.section == "controllers"] assert len(control...
def make_block_creator(yaml_path, filename=None)
Make a collection function that will create a list of blocks Args: yaml_path (str): File path to YAML file, or a file in the same dir filename (str): If give, use this filename as the last element in the yaml_path (so yaml_path can be __file__) Returns: function: A collecti...
4.686965
5.067832
0.924846
param_dict = self.substitute_params(substitutions) pkg, ident = self.name.rsplit(".", 1) pkg = "malcolm.modules.%s" % pkg try: ob = importlib.import_module(pkg) except ImportError as e: raise_with_traceback( ImportError("\n%s:%d:\n...
def instantiate(self, substitutions)
Keep recursing down from base using dotted name, then call it with self.params and args Args: substitutions (dict): Substitutions to make to self.param_dict Returns: The found object called with (*args, map_from_d) E.g. if ob is malcolm.parts, and name is "ca.C...
2.920048
2.963283
0.98541
if filename: # different filename to support passing __file__ yaml_path = os.path.join(os.path.dirname(yaml_path), filename) assert yaml_path.endswith(".yaml"), \ "Expected a/path/to/<yamlname>.yaml, got %r" % yaml_path yamlname = os.path.basename(yam...
def from_yaml(cls, yaml_path, filename=None)
Split a dictionary into parameters controllers parts blocks defines Args: yaml_path (str): File path to YAML file, or a file in the same dir filename (str): If give, use this filename as the last element in the yaml_path (so yaml_path can be __file__) Returns: ...
4.352071
3.975188
1.094809
param_dict = {} # TODO: this should be yaml.add_implicit_resolver() for k, v in self.param_dict.items(): param_dict[k] = replace_substitutions(v, substitutions) return param_dict
def substitute_params(self, substitutions)
Substitute param values in our param_dict from params Args: substitutions (Map or dict): Values to substitute. E.g. Map of {"name": "me"} E.g. if self.param_dict is: {"name": "$(name):pos", "exposure": 1.0} And substitutions is: {"name": "me"...
4.259785
4.231594
1.006662
# The time taken to ramp from v1 to pad_velocity t1 = self.acceleration_time(v1, pad_velocity) # Then on to v2 t2 = self.acceleration_time(pad_velocity, v2) # The distance during the pad tp = total_time - t1 - t2 # Yield the points yield t1, pad_v...
def _make_padded_ramp(self, v1, v2, pad_velocity, total_time)
Makes a ramp that looks like this: v1 \______ pad_velocity | |\ | | \v2 t1 tp t2 Such that whole section takes total_time
4.240659
4.066552
1.042814
if min_time > 0: # We are trying to meet time constraints # Solve quadratic to give vm b = v1 + v2 + min_time * acceleration c = distance * acceleration + (v1*v1 + v2*v2) / 2 op = b*b - 4 * c if np.isclose(op, 0): #...
def _make_hat(self, v1, v2, acceleration, distance, min_time)
Make a hat that looks like this: ______ vm v1 /| | \ d1| dm|d2\ v2 | | t1 tm t2 Such that the area under the graph (d1+d2+d3) is distance and t1+t2+t3 >= min_time
3.905376
3.821874
1.021848
# Take off the settle time and distance if min_time > 0: min_time -= self.velocity_settle distance -= self.velocity_settle * v2 # The ramp time and distance of a continuous ramp from v1 to v2 ramp_time = self.acceleration_time(v1, v2) ramp_distance = ...
def make_velocity_profile(self, v1, v2, distance, min_time)
Calculate PVT points that will perform the move within motor params Args: v1 (float): Starting velocity in EGUs/s v2 (float): Ending velocity in EGUs/s distance (float): Relative distance to travel in EGUs min_time (float): The minimum time the move should take ...
2.732194
2.780425
0.982653
# type: (...) -> Tuple[str, Dict[str, MotorInfo]] cs_ports = set() # type: Set[str] axis_mapping = {} # type: Dict[str, MotorInfo] for motor_info in cls.filter_values(part_info): if motor_info.scannable in axes_to_move: assert motor_info.cs_axis in ...
def cs_axis_mapping(cls, part_info, # type: Dict[str, Optional[Sequence]] axes_to_move # type: Sequence[str] )
Given the motor infos for the parts, filter those with scannable names in axes_to_move, check they are all in the same CS, and return the cs_port and mapping of cs_axis to MotorInfo
3.099205
2.688817
1.152628
# Can't do this with changes_squashed as it will call update_modified # from another thread and deadlock. Need RLock.is_owned() from update_* part_info = self.run_hooks( LayoutHook(p, c, self.port_info, value) for p, c in self.create_part_contexts(only_visible=Fa...
def set_layout(self, value)
Set the layout table value. Called on attribute put
6.080414
5.937319
1.024101
# type: (ASaveDesign) -> None self.try_stateful_function( ss.SAVING, ss.READY, self.do_save, designName)
def save(self, designName="")
Save the current design to file
21.133207
20.692057
1.02132
dir_name = self._make_config_dir() filename = os.path.join(dir_name, name.split(".json")[0] + ".json") return filename
def _validated_config_filename(self, name)
Make config dir and return full file path and extension Args: name (str): Filename without dir or extension Returns: str: Full path including extension
4.014728
4.104994
0.978011
# type: (str, bool) -> None if design: filename = self._validated_config_filename(design) with open(filename, "r") as f: text = f.read() structure = json_decode(text) else: structure = {} # Attributes and Children u...
def do_load(self, design, init=False)
Load a design name, running the child LoadHooks. Args: design: Name of the design json file, without extension init: Passed to the LoadHook to tell the children if this is being run at Init or not
4.321133
4.401826
0.981668
# type: (...) -> MethodModel if name is None: name = func.__name__ method = MethodModel.from_callable(func, description) self._add_field(owner, name, method, func) return method
def add_method_model(self, func, # type: Callable name=None, # type: Optional[str] description=None, # type: Optional[str] owner=None, # type: object )
Register a function to be added to the block
3.949174
4.626916
0.853522
# type: (...) -> MethodModel return self._field_registry.add_method_model( func, name, description, self._part)
def add_method_model(self, func, # type: Callable name=None, # type: Optional[str] description=None, # type: Optional[str] )
Register a function to be added to the Block as a MethodModel
7.663483
8.563643
0.894886
# type: (...) -> AttributeModel return self._field_registry.add_attribute_model( name, attr, writeable_func, self._part)
def add_attribute_model(self, name, # type: str attr, # type: AttributeModel writeable_func=None, # type: Optional[Callable] )
Register a pre-existing AttributeModel to be added to the Block
6.512339
8.597579
0.757462
if self.ideal and self.nadir: return self.ideal, self.nadir raise NotImplementedError( "Ideal and nadir value calculation is not yet implemented" )
def objective_bounds(self)
Return objective bounds Returns ------- lower : list of floats Lower boundaries for the objectives Upper : list of floats Upper boundaries for the objectives
7.14355
8.085835
0.883465
if isinstance(variables, Variable): addvars = copy.deepcopy([variables]) else: addvars = copy.deepcopy(variables) if index is None: self.variables.extend(addvars) else: self.variables[index:index] = addvars
def add_variables( self, variables: Union[List["Variable"], "Variable"], index: int = None ) -> None
Parameters ---------- variable : list of variables or single variable Add variables as problem variables index : int Location to add variables, if None add to the end
2.763579
2.805632
0.985011
k_means = KMeans(n_clusters=n_clusters) k_means.fit(points) closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points) return list(map(list, np.array(points)[closest.tolist()]))
def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]
Return n_clusters centroids of points
2.752652
2.67324
1.029706
# Initial wector space as per # Miettinen, K. Nonlinear Multiobjective Optimization # Kluwer Academic Publishers, 1999 wspace = 50 * nobj while wspace < nweight: wspace *= 2 weights = np.random.rand(wspace, nobj) return _centroids(nobj, weights)
def random_weights(nobj: int, nweight: int) -> List[List[float]]
Generatate nw random weight vectors for nof objectives as per Tchebycheff method [SteCho83]_ .. [SteCho83] Steuer, R. E. & Choo, E.-U. An interactive weighted Tchebycheff procedure for multiple objective programming, Mathematical programming, Springer, 1983, 26, 326-344 Parameters ---------- nobj: ...
9.593456
10.271955
0.933946
from desdeo.preference.direct import DirectSpecification points = [] nof = factory.optimization_method.optimization_problem.problem.nof_objectives() if not weights: weights = random_weights(nof, 50 * nof) for pref in map( lambda w: DirectSpecification(factory.optimization_metho...
def new_points( factory: IterationPointFactory, solution, weights: List[List[float]] = None ) -> List[Tuple[np.ndarray, List[float]]]
Generate approximate set of points Generate set of Pareto optimal solutions projecting from the Pareto optimal solution using weights to determine the direction. Parameters ---------- factory: IterationPointFactory with suitable optimization problem solution: Current solutio...
8.506451
9.389501
0.905953
return [v * -1. if m else v for v, m in zip(values, maximized)]
def as_minimized(values: List[float], maximized: List[bool]) -> List[float]
Return vector values as minimized
3.934039
3.806908
1.033395
class MockDocument: def __init__(self, text): self.text = text if HAS_INPUT: ret = prompt(message, default=default, validator=validator) else: ret = sys.stdin.readline().strip() print(message, ret) if validator: validator.validate(MockD...
def _prompt_wrapper(message, default=None, validator=None)
Handle references piped from file
4.686713
4.686631
1.000017
print("Preference elicitation options:") print("\t1 - Percentages") print("\t2 - Relative ranks") print("\t3 - Direct") PREFCLASSES = [PercentageSpecifictation, RelativeRanking, DirectSpecification] pref_sel = int( _prompt_wrapper( "Reference elicitation ", ...
def init_nautilus(method)
Initialize nautilus method Parameters ---------- method Interactive method used for the process Returns ------- PreferenceInformation subclass to be initialized
5.348863
5.208892
1.026872
solution = None while method.current_iter: preference_class = init_nautilus(method) pref = preference_class(method, None) default = ",".join(map(str, pref.default_input())) while method.current_iter: method.print_current_iteration() pref_input = _pro...
def iter_nautilus(method)
Iterate NAUTILUS method either interactively, or using given preferences if given Parameters ---------- method : instance of NAUTILUS subclass Fully initialized NAUTILUS method instance
6.453835
6.46004
0.999039
for i, v in enumerate(value): if v not in np.array(values)[:, i]: return False return True
def isin(value, values)
Check that value is in values
5.197502
4.760292
1.091845
from desdeo.preference.base import ReferencePoint objs1_arr = np.array(objs1) objs2_arr = np.array(objs2) segments = n + 1 diff = objs2_arr - objs1_arr solutions = [] for x in range(1, segments): btwn_obj = objs1_arr + float(x) / segments * d...
def between(self, objs1: List[float], objs2: List[float], n=1)
Generate `n` solutions which attempt to trade-off `objs1` and `objs2`. Parameters ---------- objs1 First boundary point for desired objective function values objs2 Second boundary point for desired objective function values n Number of solut...
7.060525
7.225166
0.977213
if not node.children: return node if node.focus: return find_focusable(node.children_dict[node.focus[0]])
def find_focusable(node)
Search for the first focusable window within the node tree
4.725528
4.451286
1.06161
if (node and node.orientation == orientation and len(node.children) > 1): return node if not node or node.type == "workspace": return None return find_parent_split(node.parent, orientation)
def find_parent_split(node, orientation)
Find the first parent split relative to the given node according to the desired orientation
4.05599
4.718299
0.85963
wanted = { "orientation": ("vertical" if direction in ("up", "down") else "horizontal"), "direction": (1 if direction in ("down", "right") else -1), } split = find_parent_split(tree.focused.parent, wanted["orientation"]) if split: ...
def cycle_windows(tree, direction)
Cycle through windows of the current workspace
3.870706
3.851007
1.005115
direction = 1 if direction == "next" else -1 outputs = [output for output in tree.root.children if output.name != "__i3"] focus_idx = outputs.index(tree.root.focused_child) next_idx = (focus_idx + direction) % len(outputs) next_output = outputs[next_idx] return find_focusable...
def cycle_outputs(tree, direction)
Cycle through directions
3.940932
3.979763
0.990243
parser = ArgumentParser() parser.add_argument("direction", choices=( "up", "down", "left", "right", "next", "prev" ), help="Direction to put the focus on") args = parser.parse...
def main()
Entry point
4.016697
3.996678
1.005009
rcls = [] for key, value in self._classification.items(): if value[0] == cls: rcls.append(key) return rcls
def with_class(self, cls)
Return functions with the class
4.374184
4.378155
0.999093
ref_val = [] for fn, f in self._classification.items(): if f[0] == "<": ref_val.append(self._method.problem.ideal[fn]) elif f[0] == "<>": ref_val.append(self._method.problem.nadir[fn]) else: ref_val.append(f[1])...
def _as_reference_point(self) -> np.ndarray
Return classification information as reference point
4.403984
3.738463
1.17802
# Duplicate output to log file class NAUTILUSOptionValidator(Validator): def validate(self, document): if document.text not in "ao": raise ValidationError( message="Please select a for apriori or o for optimization option", curso...
def main(logfile=False)
Solve River Pollution problem with NAUTILUS V1 and E-NAUTILUS Methods
6.211401
5.62298
1.104646
app.add_config_value( 'site_url', default=None, rebuild=False ) try: app.add_config_value( 'html_baseurl', default=None, rebuild=False ) except: pass app.connect('html-page-context', add_html_link) app.conn...
def setup(app)
Setup connects events to the sitemap builder
3.08068
2.979303
1.034027