text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_firmware(self, device, id_override=None, type_override=None): """ Make a call to the update_firmware endpoint. As far as I know this is only valid for...
object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}/update_firmware".format(self.BASE_URL, object_type, object_id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_device(self, device, id_override=None, type_override=None): """ Remove a device. Args: device (WinkDevice): The device the change is being requested ...
object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, object_type, object_id) try: arequest = requests....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_lock_key(self, device, new_device_json, id_override=None, type_override=None): """ Create a new lock key code. Args: device (WinkDevice): The device ...
object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}/keys".format(self.BASE_URL, object_type, object_id) try: areque...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_concrete_model(model): """ Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or...
if not(inspect.isclass(model) and issubclass(model, models.Model)): model = get_model_by_name(model) return model
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_resource_name(meta): """ Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :...
if meta.name is None and not meta.is_model: msg = "Either name or model for resource.Meta shoud be provided" raise ValueError(msg) name = meta.name or get_model_name(get_concrete_model(meta.model)) return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_metas(*metas): """ Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with prop...
metadict = {} for meta in metas: metadict.update(meta.__dict__) metadict = {k: v for k, v in metadict.items() if not k.startswith('__')} return type('Meta', (object, ), metadict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate(self): """ Activate the scene. """
response = self.api_interface.set_device_state(self, None) self._update_state_from_response(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_model_by_name(model_name): """ Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_b...
if isinstance(model_name, six.string_types) and \ len(model_name.split('.')) == 2: app_name, model_name = model_name.split('.') if django.VERSION[:2] < (1, 8): model = models.get_model(app_name, model_name) else: from django.apps import apps ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_model_name(model): """ Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name ...
opts = model._meta if django.VERSION[:2] < (1, 7): model_name = opts.module_name else: model_name = opts.model_name return model_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_app_cache(app_name): """ Clear django cache for models. :param str ap_name: name of application to clear model cache """
loading_cache = django.db.models.loading.cache if django.VERSION[:2] < (1, 7): loading_cache.app_models[app_name].clear() else: loading_cache.all_models[app_name].clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_sbc_config(self, config): """ Translator from namedtuple config representation to the sbc_t type. :param namedtuple config: See :py:class:`.SBCCodecCon...
if (config.channel_mode == SBCChannelMode.CHANNEL_MODE_MONO): self.config.mode = self.codec.SBC_MODE_MONO elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_STEREO): self.config.mode = self.codec.SBC_MODE_STEREO elif (config.channel_mode == SBCChannelMode.CHANNEL_M...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, fd, mtu, max_len=2560): """ Read the media transport descriptor, depay the RTP payload and decode the SBC frames into a byte array. The maximum ...
output_buffer = ffi.new('char[]', max_len) sz = self.codec.rtp_sbc_decode_from_fd(self.config, output_buffer, max_len, mtu, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transport_ready_handler(self, fd, cb_condition): """ Wrapper for calling user callback routine to notify when transport data is ready to read """
if(self.user_cb): self.user_cb(self.user_arg) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_transport(self): """ Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed. :return data: Paylo...
if ('r' not in self.access_type): raise BTIncompatibleTransportAccessType return self.codec.decode(self.fd, self.read_mtu)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_transport(self, data): """ Write data to media transport. The data is encoded using the SBC codec and RTP encapsulated before being written to the tran...
if ('w' not in self.access_type): raise BTIncompatibleTransportAccessType return self.codec.encode(self.fd, self.write_mtu, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_transport(self): """ Forcibly close previously acquired media transport. .. note:: The user should first make sure any transport event handlers are unr...
if (self.path): self._release_media_transport(self.path, self.access_type) self.path = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _acquire_media_transport(self, path, access_type): """ Should be called by subclass when it is ready to acquire the media transport file descriptor """
transport = BTMediaTransport(path=path) (fd, read_mtu, write_mtu) = transport.acquire(access_type) self.fd = fd.take() # We must do the clean-up later self.write_mtu = write_mtu self.read_mtu = read_mtu self.access_type = access_type self.path = path se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _release_media_transport(self, path, access_type): """ Should be called by subclass when it is finished with the media transport file descriptor """
try: self._uninstall_transport_ready() os.close(self.fd) # Clean-up previously taken fd transport = BTMediaTransport(path=path) transport.release(access_type) except: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_config(config): """Helper to turn SBC codec configuration params into a a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular, # the a2dp_sbc_t type is converted into a 4-byte array: # uint8_t channel_mode:4 # uint8_t frequency:4 # uint8_t allocation_method:2 # uint8_t subbands:2 # uint8_t block_length:4 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_config(config): """Helper to turn a2dp_sbc_t structure into a more usable set of SBC codec configuration params"""
frequency = config[0] >> 4 channel_mode = config[0] & 0xF allocation_method = config[1] & 0x03 subbands = (config[1] >> 2) & 0x03 block_length = (config[1] >> 4) & 0x0F min_bitpool = config[2] max_bitpool = config[3] return SBCCodecConfig(channel_mode, fr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_new_key(self, code, name): """Add a new user key code."""
device_json = {"code": code, "name": name} return self.api_interface.create_lock_key(self, device_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_paired_device(self, dev_id, agent_path, capability, cb_notify_device, cb_notify_error): """ Creates a new object path for a remote device. This method...
return self._interface.CreatePairedDevice(dev_id, agent_path, capability, reply_handler=cb_notify_device, # noqa ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _visit_body(self, node): """ Traverse the body of the node manually. If the first node is an expression which contains a string or bytes it marks that as a d...
if (node.body and isinstance(node.body[0], ast.Expr) and self.is_base_string(node.body[0].value)): node.body[0].value.is_docstring = True self.visit(node.body[0].value) for sub_node in node.body: self.visit(sub_node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(self, domain, get_last_full_query=True): """ Lookup BuiltWith results for the given domain. If API version 2 is used and the get_last_full_query flag ...
last_full_builtwith_scan_date = None if self.api_version == 7 and isinstance(domain, list): domain = ','.join(domain) if self.api_version in [2, 7]: last_updates_resp = requests.get(ENDPOINTS_BY_API_VERSION[self.api_version], params={'UPDATE': 1}) last_upd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, resource=None, **kwargs): """ Register resource for currnet API. :param resource: Resource to be registered :type resource: jsonapi.resource.R...
if resource is None: def wrapper(resource): return self.register(resource, **kwargs) return wrapper for key, value in kwargs.items(): setattr(resource.Meta, key, value) if resource.Meta.name in self.resource_map: raise ValueError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urls(self): """ Get all of the api endpoints. NOTE: only for django as of now. NOTE: urlpatterns are deprecated since Django1.8 :return list: urls """
from django.conf.urls import url urls = [ url(r'^$', self.documentation), url(r'^map$', self.map_view), ] for resource_name in self.resource_map: urls.extend([ url(r'(?P<resource_name>{})$'.format( resource_name), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_urls(self, request, resource_name=None, ids=None): """ Update url configuration. :param request: :param resource_name: :type resource_name: str or Non...
http_host = request.META.get('HTTP_HOST', None) if http_host is None: http_host = request.META['SERVER_NAME'] if request.META['SERVER_PORT'] not in ('80', '443'): http_host = "{}:{}".format( http_host, request.META['SERVER_PORT']) se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_view(self, request): """ Show information about available resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse """
self.update_urls(request) resource_info = { "resources": [{ "id": index + 1, "href": "{}/{}".format(self.api_url, resource_name), } for index, (resource_name, resource) in enumerate( sorted(self.resource_map.items())) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def documentation(self, request): """ Resource documentation. .. versionadded:: 0.7.2 Content-Type check :return django.http.HttpResponse """
self.update_urls(request) context = { "resources": sorted(self.resource_map.items()) } return render(request, "jsonapi/index.html", context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handler_view(self, request, resource_name, ids=None): """ Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse ...
signal_request.send(sender=self, request=request) time_start = time.time() self.update_urls(request, resource_name=resource_name, ids=ids) resource = self.resource_map[resource_name] allowed_http_methods = resource.Meta.allowed_methods if request.method not in allowed_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cipher(self): """Applies the Caesar shift cipher. Based on the attributes of the object, applies the Caesar shift cipher to the message attribute. Accepts po...
# If no offset is selected, pick random one with sufficient distance # from original. if self.offset is False: self.offset = randrange(5, 25) logging.info("Random offset selected: {0}".format(self.offset)) logging.debug("Offset set: {0}".format(self.offset)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_entropy(self, entropy_string): """Calculates the entropy of a string based on known frequency of English letters. Args: entropy_string: A str repre...
total = 0 for char in entropy_string: if char.isalpha(): prob = self.frequency[char.lower()] total += - math.log(prob) / math.log(2) logging.debug("Entropy score: {0}".format(total)) return total
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cracked(self): """Attempts to crack ciphertext using frequency of letters in English. Returns: String of most likely message. """
logging.info("Cracking message: {0}".format(self.message)) entropy_values = {} attempt_cache = {} message = self.message for i in range(25): self.message = message self.offset = i * -1 logging.debug("Attempting crack with offset: " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decoded(self): """Decodes message using Caesar shift cipher Inverse operation of encoding, applies negative offset to Caesar shift cipher. Returns: String de...
logging.info("Decoding message: {0}".format(self.message)) self.offset = self.offset * -1 return self.cipher()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(cls, querydict): """ Parse querydict data. There are expected agruments: distinct, fields, filter, include, page, sort Parameters querydict : django.ht...
for key in querydict.keys(): if not any((key in JSONAPIQueryDict._fields, cls.RE_FIELDS.match(key))): msg = "Query parameter {} is not known".format(key) raise ValueError(msg) result = JSONAPIQueryDict( distinct=cls.prepa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_state_name(self): """ Search all of the capabilities of the device and return the supported binary state field. Default to returning powered. """
return_field = "powered" _capabilities = self.json_state.get('capabilities') if _capabilities is not None: _fields = _capabilities.get('fields') if _fields is not None: for field in _fields: if field.get('field') in SUPPORTED_BI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flux_production(F): r"""Returns the net flux production for all states Parameters F : (n, n) ndarray Matrix of flux values between pairs of states. Returns -...
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out prod = outfluxes - influxes # net flux into nodes return prod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_flux(F, A=None): r"""Compute the total flux, or turnover flux, that is produced by the flux sources and consumed by the flux sinks Parameters F : (n, n...
if A is None: prod = flux_production(F) zeros = np.zeros(len(prod)) outflux = np.sum(np.maximum(prod, zeros)) return outflux else: X = set(np.arange(F.shape[0])) # total state space A = set(A) notA = X.difference(A) outflux = (F[list(A), :])[:, l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_journal(self, permissive=True): """Add the initialization lines to the journal. By default adds JrnObj variable and timestamp to the journal contents. ...
nowstamp = datetime.now().strftime("%d-%b-%Y %H:%M:%S.%f")[:-3] self._add_entry(templates.INIT .format(time_stamp=nowstamp)) if permissive: self._add_entry(templates.INIT_DEBUG)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _new_from_rft(self, base_template, rft_file): """Append a new file from .rft entry to the journal. This instructs Revit to create a new model based on the pr...
self._add_entry(base_template) self._add_entry(templates.NEW_FROM_RFT .format(rft_file_path=rft_file, rft_file_name=op.basename(rft_file)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_model(self, template_name='<None>'): """Append a new model from .rft entry to the journal. This instructs Revit to create a new model based on the provid...
self._add_entry(templates.NEW_MODEL .format(template_name=template_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_template(self, template_name='<None>'): """Append a new template from .rft entry to the journal. This instructs Revit to create a new template model base...
self._add_entry(templates.NEW_MODEL_TEMPLATE .format(template_name=template_name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_workshared_model(self, model_path, central=False, detached=False, keep_worksets=True, audit=False, show_workset_config=1): """Append a open workshared m...
if detached: if audit: if keep_worksets: self._add_entry( templates.CENTRAL_OPEN_DETACH_AUDIT .format(model_path=model_path, workset_config=show_workset_config) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_model(self, model_path, audit=False): """Append a open non-workshared model entry to the journal. This instructs Revit to open a non-workshared model. A...
if audit: self._add_entry(templates.FILE_OPEN_AUDIT .format(model_path=model_path)) else: self._add_entry(templates.FILE_OPEN .format(model_path=model_path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_command(self, tab_name, panel_name, command_module, command_class, command_data=None): """Append an execute external command entry to the journal. Th...
# make sure command_data is not empty command_data = {} if command_data is None else command_data # make the canonical name for the command cmdclassname = '{}.{}'.format(command_module, command_class) self._add_entry(templates.EXTERNAL_COMMAND ....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_dynamo_definition(self, definition_path, show_ui=False, shutdown=True, automation=False, path_exec=True): """Execute a dynamo definition. Args: defin...
self._add_entry(templates.DYNAMO_COMMAND .format(dynamo_def_path=definition_path, dyn_show_ui=show_ui, dyn_automation=automation, dyn_path_exec=path_exec, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_family(self, rfa_file): """Append a import family entry to the journal. This instructs Revit to import a family into the opened model. Args: rfa_file ...
self._add_entry(templates.IMPORT_FAMILY .format(family_file=rfa_file))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_warnings(self, export_file): """Append an export warnings entry to the journal. This instructs Revit to export warnings from the opened model. Current...
warn_filepath = op.dirname(export_file) warn_filename = op.splitext(op.basename(export_file))[0] self._add_entry(templates.EXPORT_WARNINGS .format(warnings_export_path=warn_filepath, warnings_export_file=warn_filename))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge_unused(self, pass_count=3): """Append an purge model entry to the journal. This instructs Revit to purge the open model. Args: pass_count (int): numbe...
for purge_count in range(0, pass_count): self._add_entry(templates.PROJECT_PURGE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_model(self, comment='', compact_central=False, release_borrowed=True, release_workset=True, save_local=False): """Append a sync model entry to the journ...
self._add_entry(templates.FILE_SYNC_START) if compact_central: self._add_entry(templates.FILE_SYNC_COMPACT) if release_borrowed: self._add_entry(templates.FILE_SYNC_RELEASE_BORROWED) if release_workset: self._add_entry(templates.FILE_SYNC_RELEASE_USE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_journal(self, journal_file_path): """Write the constructed journal in to the provided file. Args: journal_file_path (str): full path to output journal...
# TODO: assert the extension is txt and not other with open(journal_file_path, "w") as jrn_file: jrn_file.write(self._journal_contents)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def endswith(self, search_str): """Check whether the provided string exists in Journal file. Only checks the last 5 lines of the journal file. This method is usu...
for entry in reversed(list(open(self._jrnl_file, 'r'))[-5:]): if search_str in entry: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prior_neighbor(C, alpha=0.001): r"""Neighbor prior of strength alpha for the given count matrix. Prior is defined by b_ij = alpha if Z_ij+Z_ji > 0 b_ij = 0 e...
C_sym = C + C.transpose() C_sym = C_sym.tocoo() data = C_sym.data row = C_sym.row col = C_sym.col data_B = alpha * np.ones_like(data) B = coo_matrix((data_B, (row, col))) return B
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prior_const(C, alpha=0.001): """Constant prior of strength alpha. Prior is defined via b_ij=alpha for all i,j Parameters C : (M, M) ndarray or scipy.sparse m...
B = alpha * np.ones(C.shape) return B
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_transition_matrix(T, tol=1e-10): """ Tests whether T is a transition matrix Parameters T : ndarray shape=(n, n) matrix to test tol : float tolerance to ch...
if T.ndim != 2: return False if T.shape[0] != T.shape[1]: return False dim = T.shape[0] X = np.abs(T) - T x = np.sum(T, axis=1) return np.abs(x - np.ones(dim)).max() < dim * tol and X.max() < 2.0 * tol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True, nstates=None): r"""Generate a count matrix from a given list discrete trajectories. The genera...
# Determine number of states if nstates is None: from msmtools.dtraj import number_of_states nstates = number_of_states(dtrajs) rows = [] cols = [] # collect transition index pairs for dtraj in dtrajs: if dtraj.size > lag: if (sliding): rows.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_transition_matrix(T, tol): """ True if T is a transition matrix Parameters T : scipy.sparse matrix Matrix to check tol : float tolerance to check with Ret...
T = T.tocsr() # compressed sparse row for fast row slicing values = T.data # non-zero entries of T """Check entry-wise positivity""" is_positive = np.allclose(values, np.abs(values), rtol=tol) """Check row normalization""" is_normed = np.allclose(T.sum(axis=1), 1.0, rtol=tol) return is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_connected(T, directed=True): r"""Check connectivity of the transition matrix. Return true, if the input matrix is completely connected, effectively checki...
nc = connected_components(T, directed=directed, connection='strong', \ return_labels=False) return nc == 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_ergodic(T, tol): """ checks if T is 'ergodic' Parameters T : scipy.sparse matrix Transition matrix tol : float tolerance Returns ------- Truth value : boo...
if isdense(T): T = T.tocsr() if not is_transition_matrix(T, tol): raise ValueError("given matrix is not a valid transition matrix.") num_components = connected_components(T, directed=True, \ connection='strong', \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(opts, conf): """ Acts like twistd """
if opts.config is not None: os.environ["CALLSIGN_CONFIG_FILE"] = opts.config sys.argv[1:] = [ "-noy", sibpath(__file__, "callsign.tac"), "--pidfile", conf['pidfile'], "--logfile", conf['logfile'], ] twistd.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_bottleneck(F, A, B): r"""Find dynamic bottleneck of flux network. Parameters F : scipy.sparse matrix The flux network A : array_like The set of starting...
if F.nnz == 0: raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries') F = F.tocoo() n = F.shape[0] """Get exdges and corresponding flux values""" val = F.data row = F.row col = F.col """Sort edges according to flux""" ind = np.argsor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_connection(graph, A, B): r"""Check if the given graph contains a path connecting A and B. Parameters graph : scipy.sparse matrix Adjacency matrix of the ...
for istart in A: nodes = csgraph.breadth_first_order(graph, istart, directed=True, return_predecessors=False) if has_path(nodes, A, B): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_path(nodes, A, B): r"""Test if nodes from a breadth_first_order search lead from A to B. Parameters nodes : array_like Nodes from breadth_first_oder_seat...
x1 = np.intersect1d(nodes, A).size > 0 x2 = np.intersect1d(nodes, B).size > 0 return x1 and x2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pathway(F, A, B): r"""Compute the dominant reaction-pathway. Parameters F : (M, M) scipy.sparse matrix The flux network (matrix of netflux values) A : array_...
if F.nnz == 0: raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries') b1, b2, F = find_bottleneck(F, A, B) if np.any(A == b1): wL = [b1, ] elif np.any(B == b1): raise PathwayError(("Roles of vertices b1 and b2 are switched." ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_path(F, path): r"""Remove capacity along a path from flux network. Parameters F : (M, M) scipy.sparse matrix The flux network (matrix of netflux value...
c = capacity(F, path) F = F.todok() L = len(path) for l in range(L - 1): i = path[l] j = path[l + 1] F[i, j] -= c return F
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_endstates(F, A, B): r"""Adds artifical end states replacing source and sink sets. Parameters F : (M, M) scipy.sparse matrix The flux network (matrix of n...
"""Outgoing currents from A""" F = F.tocsr() outA = (F[A, :].sum(axis=1)).getA()[:, 0] """Incoming currents into B""" F = F.tocsc() inB = (F[:, B].sum(axis=0)).getA()[0, :] F = F.tocoo() M = F.shape[0] data_old = F.data row_old = F.row col_old = F.col """Add current...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_utf_8(txt): """ Check a string is utf-8 encoded :param bytes txt: utf-8 string :return: Whether the string\ is utf-8 encoded or not :rtype: bool """
assert isinstance(txt, six.binary_type) try: _ = six.text_type(txt, 'utf-8') except (TypeError, UnicodeEncodeError): return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_libs(self, scripts_paths): """ Load script files into the context.\ This can be thought as the HTML script tag.\ The files content must be utf-8 encoded...
for path in scripts_paths: self.run_script(_read_file(path), identifier=path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME): """ Run a JS script within the context.\ All code is ran synchronously,\ there is no event loop. I...
assert isinstance(script, six.text_type) or _is_utf_8(script) assert isinstance(identifier, six.text_type) or _is_utf_8(identifier) if isinstance(script, six.text_type): script = script.encode('utf-8') if isinstance(identifier, six.text_type): identifier = iden...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalues(T, k=None, reversible=False, mu=None): r"""Compute eigenvalues of given transition matrix. Parameters T : (d, d) ndarray Transition matrix (stoch...
if reversible: try: evals = eigenvalues_rev(T, k=k, mu=mu) except: evals = eigvals(T).real # use fallback code but cast to real else: evals = eigvals(T) # nonreversible """Sort by decreasing absolute value""" ind = np.argsort(np.abs(evals))[::-1] e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalues_rev(T, k=None, mu=None): r"""Compute eigenvalues of reversible transition matrix. Parameters T : (d, d) ndarray Transition matrix (stochastic mat...
"""compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu """ symmetric eigenvalue problem ""...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rdl_decomposition_nrev(T, norm='standard'): r"""Decomposition into left and right eigenvectors. Parameters T : (M, M) ndarray Transition matrix norm: {'stand...
d = T.shape[0] w, R = eig(T) """Sort by decreasing magnitude of eigenvalue""" ind = np.argsort(np.abs(w))[::-1] w = w[ind] R = R[:, ind] """Diagonal matrix containing eigenvalues""" D = np.diag(w) # Standard norm: Euclidean norm is 1 for r and LR = I. if norm == 'standard': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rdl_decomposition_rev(T, norm='reversible', mu=None): r"""Decomposition into left and right eigenvectors for reversible transition matrices. Parameters T : (...
if mu is None: mu = stationary_distribution(T) """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu val, eigvec = eigh(S) """Sort eigenvalues and eigenvectors""" perm = np.argsort(np.abs(val))[::-1] val = val[perm] eigvec = eigvec[:, perm] """Diagonal matrix...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timescales_from_eigenvalues(evals, tau=1): r"""Compute implied time scales from given eigenvalues Parameters evals : eigenvalues tau : lag time Returns -----...
"""Check for dominant eigenvalues with large imaginary part""" if not np.allclose(evals.imag, 0.0): warnings.warn('Using eigenvalues with non-zero imaginary part', ImaginaryEigenValueWarning) """Check for multiple eigenvalues of magnitude one""" ind_abs_one = np.isclose(np.abs(evals), 1.0, r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_sparse_file(filename): """Determine if the given filename indicates a dense or a sparse matrix If pathname is xxx.coo.yyy return True otherwise False. """
dirname, basename = os.path.split(filename) name, ext = os.path.splitext(basename) matrix_name, matrix_ext = os.path.splitext(name) if matrix_ext == '.coo': return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stationary_distribution_from_backward_iteration(P, eps=1e-15): r"""Fast computation of the stationary vector using backward iteration. Parameters P : (M, M) ...
A = P.transpose() mu = 1.0 - eps x0 = np.ones(P.shape[0]) y = backward_iteration(A, mu, x0) pi = y / y.sum() return pi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalues(T, k=None, ncv=None, reversible=False, mu=None): r"""Compute the eigenvalues of a sparse transition matrix. Parameters T : (M, M) scipy.sparse ma...
if k is None: raise ValueError("Number of eigenvalues required for decomposition of sparse matrix") else: if reversible: try: v = eigenvalues_rev(T, k, ncv=ncv, mu=mu) except: # use fallback code, but cast to real v = scipy.sparse.linalg....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalues_rev(T, k, ncv=None, mu=None): r"""Compute the eigenvalues of a reversible, sparse transition matrix. Parameters T : (M, M) scipy.sparse matrix Tr...
"""compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) D = diags(smu, 0) Dinv = diags(1.0/smu, 0) S = (D.dot(T))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def number_of_states(dtrajs): r""" Determine the number of states from a set of discrete trajectories Parameters dtrajs : list of int-arrays discrete trajectorie...
# determine number of states n nmax = 0 for dtraj in dtrajs: nmax = max(nmax, np.max(dtraj)) # return number of states return nmax + 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_lengths(dtrajs): r""" Determines the lengths of all trajectories Parameters dtrajs : list of int-arrays discrete trajectories """
if (isinstance(dtrajs[0], (int))): return len(dtrajs) * np.ones((1)) lengths = np.zeros((len(dtrajs))) for i in range(len(dtrajs)): lengths[i] = len(dtrajs[i]) return lengths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap_counts_singletraj(dtraj, lagtime, n): """ Samples n counts at the given lagtime from the given trajectory """
# check if length is sufficient L = len(dtraj) if (lagtime > L): raise ValueError( 'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajectory with length ' + str(L)) # sample I = np.random.randint(0, L - lagtime - 1, size=n) J = I + lagtime # return state...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connected_sets(C, directed=True): r"""Compute connected components for a directed graph with weights represented by the given count matrix. Parameters C : sc...
M = C.shape[0] """ Compute connected components of C. nc is the number of components, indices contain the component labels of the states """ nc, indices = csgraph.connected_components(C, directed=directed, connection='strong') states = np.arange(M) # Discrete states """Order indices""" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def largest_connected_submatrix(C, directed=True, lcc=None): r"""Compute the count matrix of the largest connected set. The input count matrix is used as a weigh...
if lcc is None: lcc = largest_connected_set(C, directed=directed) """Row slicing""" if scipy.sparse.issparse(C): C_cc = C.tocsr() else: C_cc = C C_cc = C_cc[lcc, :] """Column slicing""" if scipy.sparse.issparse(C): C_cc = C_cc.tocsc() C_cc = C_cc[:, lcc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_connected(C, directed=True): r"""Return true, if the input count matrix is completely connected. Effectively checking if the number of connected component...
nc = csgraph.connected_components(C, directed=directed, connection='strong', \ return_labels=False) return nc == 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coarsegrain(F, sets): r"""Coarse-grains the flux to the given sets. Parameters F : (n, n) ndarray or scipy.sparse matrix Matrix of flux values between pairs ...
if issparse(F): return sparse.tpt.coarsegrain(F, sets) elif isdense(F): return dense.tpt.coarsegrain(F, sets) else: raise _type_not_supported
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_flux(F, A=None): r"""Compute the total flux, or turnover flux, that is produced by the flux sources and consumed by the flux sinks. Parameters F : (M, ...
if issparse(F): return sparse.tpt.total_flux(F, A=A) elif isdense(F): return dense.tpt.total_flux(F, A=A) else: raise _type_not_supported
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mfpt(totflux, pi, qminus): r"""Mean first passage time for reaction A to B. Parameters totflux : float The total flux between reactant and product pi : (M,) ...
return dense.tpt.mfpt(totflux, pi, qminus)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pcca_connected_isa(evec, n_clusters): """ PCCA+ spectral clustering method using the inner simplex algorithm. Clusters the first n_cluster eigenvectors of a...
(n, m) = evec.shape # do we have enough eigenvectors? if n_clusters > m: raise ValueError("Cannot cluster the (" + str(n) + " x " + str(m) + " eigenvector matrix to " + str(n_clusters) + " clusters.") # check if the first, and only the first eigenvector is constant ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _opt_soft(eigvectors, rot_matrix, n_clusters): """ Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative. Parameters eige...
# only consider first n_clusters eigenvectors eigvectors = eigvectors[:, :n_clusters] # crop first row and first column from rot_matrix # rot_crop_matrix = rot_matrix[1:,1:] rot_crop_matrix = rot_matrix[1:][:, 1:] (x, y) = rot_crop_matrix.shape # reshape rot_crop_matrix into linear vecto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """
(x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate((-row_sums, rot_crop_matrix), axis=1) tmp = -np.dot(eigvectors[:, 1:], rot_crop_matrix) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coarsegrain(P, n): """ Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preser...
M = pcca(P, n) # coarse-grained transition matrix W = np.linalg.inv(np.dot(M.T, M)) A = np.dot(np.dot(M.T, P), M) P_coarse = np.dot(W, A) # symmetrize and renormalize to eliminate numerical errors from msmtools.analysis import stationary_distribution pi_coarse = np.dot(M.T, stationary_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_transition_matrix(T, tol=1e-12): r"""Check if the given matrix is a transition matrix. Parameters T : (M, M) ndarray or scipy.sparse matrix Matrix to chec...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.assessment.is_transition_matrix(T, tol) else: return dense.assessment.is_transition_matrix(T, tol)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_rate_matrix(K, tol=1e-12): r"""Check if the given matrix is a rate matrix. Parameters K : (M, M) ndarray or scipy.sparse matrix Matrix to check tol : floa...
K = _types.ensure_ndarray_or_sparse(K, ndim=2, uniform=True, kind='numeric') if _issparse(K): return sparse.assessment.is_rate_matrix(K, tol) else: return dense.assessment.is_rate_matrix(K, tol)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_connected(T, directed=True): r"""Check connectivity of the given matrix. Parameters T : (M, M) ndarray or scipy.sparse matrix Matrix to check directed : b...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.assessment.is_connected(T, directed=directed) else: T = _csr_matrix(T) return sparse.assessment.is_connected(T, directed=directed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_reversible(T, mu=None, tol=1e-12): r"""Check reversibility of the given transition matrix. Parameters T : (M, M) ndarray or scipy.sparse matrix Transition...
# check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') mu = _types.ensure_float_vector_or_None(mu, require_order=True) # go if _issparse(T): return sparse.assessment.is_reversible(T, mu, tol) else: return dense.assessment.is_reversible(T, mu, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timescales(T, tau=1, k=None, ncv=None, reversible=False, mu=None): r"""Compute implied time scales of given transition matrix. Parameters T : (M, M) ndarray ...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.decomposition.timescales(T, tau=tau, k=k, ncv=ncv, reversible=reversible, mu=mu) else: return dense.decomposition.timescales(T, tau=tau,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def committor(T, A, B, forward=True, mu=None): r"""Compute the committor between sets of microstates. The committor assigns to each microstate a probability that...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') A = _types.ensure_int_vector(A) B = _types.ensure_int_vector(B) if _issparse(T): if forward: return sparse.committor.forward_committor(T, A, B) else: """ if P is time reversible backward...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expected_counts(T, p0, N): r"""Compute expected transition counts for Markov chain with n steps. Parameters T : (M, M) ndarray or sparse matrix Transition ma...
# check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') p0 = _types.ensure_float_vector(p0, require_order=True) # go if _issparse(T): return sparse.expectations.expected_counts(p0, T, N) else: return dense.expectations.expected_counts(p0, T, N)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprint_correlation(T, obs1, obs2=None, tau=1, k=None, ncv=None): r"""Dynamical fingerprint for equilibrium correlation experiment. Parameters T : (M, M)...
# check if square matrix and remember size T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') n = T.shape[0] # will not do fingerprint analysis for nonreversible matrices if not is_reversible(T): raise ValueError('Fingerprint calculation is not supported for nonrev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprint_relaxation(T, p0, obs, tau=1, k=None, ncv=None): r"""Dynamical fingerprint for relaxation experiment. The dynamical fingerprint is given by the i...
# check if square matrix and remember size T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') n = T.shape[0] # will not do fingerprint analysis for nonreversible matrices if not is_reversible(T): raise ValueError('Fingerprint calculation is not supported for nonrev...