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 accessible_organisms(user, orgs): """Get the list of organisms accessible to a user, filtered by `orgs`"""
permission_map = { x['organism']: x['permissions'] for x in user.organismPermissions if 'WRITE' in x['permissions'] or 'READ' in x['permissions'] or 'ADMINISTRATE' in x['permissions'] or user.role == 'ADMIN' } if 'error' in orgs: raise Exception("Error received from Apollo server: \"%s\"" % orgs['error']) return [ (org['commonName'], org['id'], False) for org in sorted(orgs, key=lambda x: x['commonName']) if org['commonName'] in permission_map ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(cls, host, public_key, private_key, verbose=0, use_cache=True): """ Connect the client with the given host and the provided credentials. Parameters host : str The Cytomine host (without protocol). public_key : str The Cytomine public key. private_key : str The Cytomine private key. verbose : int The verbosity level of the client. use_cache : bool True to use HTTP cache, False otherwise. Returns ------- client : Cytomine A connected Cytomine client. """
return cls(host, public_key, private_key, verbose, use_cache)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_from_cli(cls, argv, use_cache=True): """ Connect with data taken from a command line interface. Parameters argv: list Command line parameters (executable name excluded) use_cache : bool True to use HTTP cache, False otherwise. Returns ------- client : Cytomine A connected Cytomine client. Notes ----- If some parameters are invalid, the function stops the execution and displays an help. """
argparse = cls._add_cytomine_cli_args(ArgumentParser()) params, _ = argparse.parse_known_args(args=argv) log_level = params.verbose if params.log_level is not None: log_level = logging.getLevelName(params.log_level) return cls.connect(params.host, params.public_key, params.private_key, log_level, use_cache=use_cache)
<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_url(host, provided_protocol=None): """ Process the provided host and protocol to return them in a standardized way that can be subsequently used by Cytomine methods. If the protocol is not specified, HTTP is the default. Only HTTP and HTTPS schemes are supported. Parameters host: str The host, with or without the protocol provided_protocol: str ("http", "http://", "https", "https://") The default protocol - used only if the host value does not specify one Return ------ (host, protocol): tuple The host and protocol in a standardized way (host without protocol, and protocol in ("http", "https")) Examples -------- ("localhost-core", "http") ("demo.cytomine.coop", "https") """
protocol = "http" # default protocol if host.startswith("http://"): protocol = "http" elif host.startswith("https://"): protocol = "https" elif provided_protocol is not None: provided_protocol = provided_protocol.replace("://", "") if provided_protocol in ("http", "https"): protocol = provided_protocol host = host.replace("http://", "").replace("https://", "") if host.endswith("/"): host = host[:-1] return host, protocol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_crop(self, ims_host, filename, id_annot, id_storage, id_project=None, sync=False, protocol=None): """ Upload the crop associated with an annotation as a new image. Parameters ims_host: str Cytomine IMS host, with or without the protocol filename: str Filename to give to the newly created image id_annot: int Identifier of the annotation to crop id_storage: int Identifier of the storage to use to upload the new image id_project: int, optional Identifier of a project in which the new image should be added sync: bool, optional True: the server will answer once the uploaded file is deployed (response will include the created image) False (default): the server will answer as soon as it receives the file protocol: str ("http", "http://", "https", "https://") The default protocol - used only if the host value does not specify one Return ------ uf: UploadedFile The uploaded file. Its images attribute is populated with the collection of created abstract images. """
if not protocol: protocol = self._protocol ims_host, protocol = self._parse_url(ims_host, protocol) ims_host = "{}://{}".format(protocol, ims_host) query_parameters = { "annotation" : id_annot, "storage": id_storage, "cytomine": "{}://{}".format(self._protocol, self._host), "name": filename, "sync": sync } if id_project: query_parameters["project"] = id_project response = self._session.post("{}/uploadCrop".format(ims_host), auth=CytomineAuth( self._public_key, self._private_key, ims_host, ""), headers=self._headers(), params=query_parameters) if response.status_code == requests.codes.ok: uf = self._process_upload_response(response.json()) self._logger.info("Image crop uploaded successfully to {}".format(ims_host)) return uf else: self._logger.error("Error during crop upload. Response: %s", response) 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 show_comment(self, value): """ Get a specific canned comment :type value: str :param value: Canned comment to show :rtype: dict :return: A dictionnary containing canned comment description """
comments = self.get_comments() comments = [x for x in comments if x['comment'] == value] if len(comments) == 0: raise Exception("Unknown comment") else: return comments[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arrow(ctx, apollo_instance, verbose, log_level): """Command line wrappers around Apollo functions. While this sounds unexciting, with arrow and jq you can easily build powerful command line scripts."""
set_logging_level(log_level) # We abuse this, knowing that calls to one will fail. try: ctx.gi = get_apollo_instance(apollo_instance) except TypeError: pass # ctx.log("Could not access Galaxy instance configuration") ctx.verbose = verbose
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_loads(data): """Load json data, allowing - to represent stdin."""
if data is None: return "" if data == "-": return json.load(sys.stdin) elif os.path.exists(data): with open(data, 'r') as handle: return json.load(handle) else: return json.loads(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 get_queryset(self, **options): """ Filters the list of log objects to display """
days = options.get('days') queryset = TimelineLog.objects.order_by('-timestamp') if days: try: start = timezone.now() - timedelta(days=days) except TypeError: raise CommandError("Incorrect 'days' parameter. 'days' must be a number of days.") else: return queryset.filter(timestamp__gte=start) return queryset
<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_recipients(self, **options): """ Figures out the recipients """
if options['recipients_from_setting']: return settings.TIMELINE_DIGEST_EMAIL_RECIPIENTS users = get_user_model()._default_manager.all() if options['staff']: users = users.filter(is_staff=True) elif not options['all']: users = users.filter(is_staff=True, is_superuser=True) return users.values_list(settings.TIMELINE_USER_EMAIL_FIELD, flat=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 expand_actions(self, actions): """Accepts an array of actions and returns an array of actions which match. This should be called before "matches?" and other checking methods since they rely on the actions to be expanded."""
results = list() for action in actions: if action in self.aliased_actions: results.append(action) for item in self.expand_actions(self.aliased_actions[action]): results.append(item) else: results.append(action) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _software_params_to_argparse(parameters): """ Converts a SoftwareParameterCollection into an ArgumentParser object. Parameters parameters: SoftwareParameterCollection The software parameters Returns ------- argparse: ArgumentParser An initialized argument parser """
# Check software parameters argparse = ArgumentParser() boolean_defaults = {} for parameter in parameters: arg_desc = {"dest": parameter.name, "required": parameter.required, "help": ""} # TODO add help if parameter.type == "Boolean": default = _to_bool(parameter.defaultParamValue) arg_desc["action"] = "store_true" if not default else "store_false" boolean_defaults[parameter.name] = default else: python_type = _convert_type(parameter.type) arg_desc["type"] = python_type arg_desc["default"] = None if parameter.defaultParamValue is None else python_type(parameter.defaultParamValue) argparse.add_argument(*_cytomine_parameter_name_synonyms(parameter.name), **arg_desc) argparse.set_defaults(**boolean_defaults) return argparse
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Connect to the Cytomine server and switch to job connection Incurs dataflows """
run_by_ui = False if not self.current_user.algo: # If user connects as a human (CLI execution) self._job = Job(self._project.id, self._software.id).save() user_job = User().fetch(self._job.userJob) self.set_credentials(user_job.publicKey, user_job.privateKey) else: # If the user executes the job through the Cytomine interface self._job = Job().fetch(self.current_user.job) run_by_ui = True # set job state to RUNNING self._job.status = Job.RUNNING self._job.update() # add software parameters if not run_by_ui and self._parameters is not None: parameters = vars(self._parameters) for software_param in self._software.parameters: name = software_param["name"] if name in parameters: value = parameters[name] else: value = software_param["defaultParamValue"] JobParameter(self._job.id, software_param["id"], value).save()
<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(self, value): """ Notify the Cytomine server of the job's end Incurs a dataflows """
if value is None: status = Job.TERMINATED status_comment = "Job successfully terminated" else: status = Job.FAILED status_comment = str(value)[:255] self._job.status = status self._job.statusComment = status_comment self._job.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_from_cli(args): """CLI entry point."""
parser = argparse.ArgumentParser(description="Generate Python classes from an Ecore model.") parser.add_argument( '--ecore-model', '-e', help="Path to Ecore XMI file.", required=True ) parser.add_argument( '--out-folder', '-o', help="Path to directory, where output files are generated.", required=True ) parser.add_argument( '--auto-register-package', help="Generate package auto-registration for the PyEcore 'global_registry'.", action='store_true' ) parser.add_argument( '--user-module', help="Dotted name of module with user-provided mixins to import from generated classes.", ) parser.add_argument( '--with-dependencies', help="Generates code for every metamodel the input metamodel depends on.", action='store_true' ) parser.add_argument( '--verbose', '-v', help="Increase logging verbosity.", action='count' ) parsed_args = parser.parse_args(args) configure_logging(parsed_args) model = load_model(parsed_args.ecore_model) EcoreGenerator( auto_register_package=parsed_args.auto_register_package, user_module=parsed_args.user_module, with_dependencies=parsed_args.with_dependencies ).generate(model, parsed_args.out_folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_uri_implementation(ecore_model_path): """Select the right URI implementation regarding the Ecore model path schema."""
if URL_PATTERN.match(ecore_model_path): return pyecore.resources.resource.HttpURI return pyecore.resources.URI
<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_model(ecore_model_path): """Load a single Ecore model and return the root package."""
rset = pyecore.resources.ResourceSet() uri_implementation = select_uri_implementation(ecore_model_path) resource = rset.get_resource(uri_implementation(ecore_model_path)) return resource.contents[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, client_method, data, post_params=None, is_json=True): """Make a POST request"""
url = self._wa.apollo_url + self.CLIENT_BASE + client_method if post_params is None: post_params = {} headers = { 'Content-Type': 'application/json' } data.update({ 'username': self._wa.username, 'password': self._wa.password, }) curl_command = ['curl', url] for (k, v) in headers.items(): curl_command += ['-H', quote('%s: %s' % (k, v))] curl_command += ['-d', quote(json.dumps(data))] log.info(' '.join(curl_command)) resp = requests.post(url, data=json.dumps(data), headers=headers, verify=self.__verify, params=post_params, allow_redirects=False, **self._request_args) if resp.status_code == 200 or resp.status_code == 302: if is_json: data = resp.json() return self._scrub_data(data) else: return resp.text # @see self.body for HTTP response body raise Exception("Unexpected response from apollo %s: %s" % (resp.status_code, resp.text))
<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(self, client_method, get_params, is_json=True): """Make a GET request"""
url = self._wa.apollo_url + self.CLIENT_BASE + client_method headers = {} response = requests.get(url, headers=headers, verify=self.__verify, params=get_params, **self._request_args) if response.status_code == 200: if is_json: data = response.json() return self._scrub_data(data) else: return response.text # @see self.body for HTTP response body raise Exception("Unexpected response from apollo %s: %s" % (response.status_code, response.text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can(user, action, subject): """Checks if a given user has the ability to perform the action on a subject :param user: A user object :param action: an action string, typically 'read', 'edit', 'manage'. Use bouncer.constants for readability :param subject: the resource in question. Either a Class or an instance of a class. Pass the class if you want to know if the user has general access to perform the action on that type of object. Or pass a specific object, if you want to know if the user has the ability to that specific instance :returns: Boolean """
ability = Ability(user, get_authorization_method()) return ability.can(action, subject)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cannot(user, action, subject): """inverse of ``can``"""
ability = Ability(user, get_authorization_method()) return ability.cannot(action, subject)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure(user, action, subject): """ Similar to ``can`` but will raise a AccessDenied Exception if does not have access"""
ability = Ability(user, get_authorization_method()) if ability.cannot(action, subject): raise AccessDenied()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self, dest_pattern="{id}.jpg", override=True, mask=False, alpha=False, bits=8, zoom=None, max_size=None, increase_area=None, contrast=None, gamma=None, colormap=None, inverse=None): """ Download the annotation crop, with optional image modifications. Parameters dest_pattern : str, optional Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute if it exists. override : bool, optional True if a file with same name can be overrided by the new file. mask : bool, optional True if a binary mask based on given annotations must be returned, False otherwise. alpha : bool, optional True if image background (outside annotations) must be transparent, False otherwise. zoom : int, optional Optional image zoom number bits : int (8,16,32) or str ("max"), optional Bit depth (bit per channel) of returned image. "max" returns the original image bit depth max_size : int, tuple, optional Maximum size (width or height) of returned image. None to get original size. increase_area : float, optional Increase the crop size. For example, an annotation whose bounding box size is (w,h) will have a crop dimension of (w*increase_area, h*increase_area). contrast : float, optional Optional contrast applied on returned image. gamma : float, optional Optional gamma applied on returned image. colormap : int, optional Cytomine identifier of a colormap to apply on returned image. inverse : bool, optional True to inverse color mapping, False otherwise. Returns ------- downloaded : bool True if everything happens correctly, False otherwise. As a side effect, object attribute "filename" is filled with downloaded file path. """
if self.id is None: raise ValueError("Cannot dump an annotation with no ID.") pattern = re.compile("{(.*?)}") dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern) destination = os.path.dirname(dest_pattern) filename, extension = os.path.splitext(os.path.basename(dest_pattern)) extension = extension[1:] if extension not in ("jpg", "png", "tif", "tiff"): extension = "jpg" if not os.path.exists(destination): os.makedirs(destination) parameters = { "zoom": zoom, "maxSize": max_size, "increaseArea": increase_area, "contrast": contrast, "gamma": gamma, "colormap": colormap, "inverse": inverse, "bits": bits } if mask and alpha: image = "alphamask" if extension == "jpg": extension = "png" elif mask: image = "mask" else: image = "crop" file_path = os.path.join(destination, "{}.{}".format(filename, extension)) url = self.cropURL.replace("crop.jpg", "{}.{}".format(image, extension)) result = Cytomine.get_instance().download_file(url, file_path, override, parameters) if result: self.filename = file_path return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, organism, sequence): """Set the sequence for subsequent requests. Mostly used in client scripts to avoid passing the sequence and organism on every function call. Output: None """
return ctx.gi.annotations.set_sequence(organism, sequence)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path(self): """The path attribute returns a stringified, concise representation of the MultiFieldSelector. It can be reversed by the ``from_path`` constructor. """
if len(self.heads) == 1: return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0]) else: return "(" + "|".join( _fmt_mfs_path(k, v) for (k, v) in self.heads.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 get(self, obj): """Creates a copy of the passed object which only contains the parts which are pointed to by one of the FieldSelectors that were used to construct the MultiFieldSelector. Can be used to produce 'filtered' versions of objects. """
ctor = type(obj) if isinstance(obj, (list, ListCollection)): if self.has_string: raise TypeError( "MultiFieldSelector has string in list collection context" ) if self.has_none: tail = self.heads[None] vals = list(self._get(x, tail) for x in obj) else: vals = list( self._get(obj[head], tail) for head, tail in self.heads.iteritems() ) if isinstance(obj, ListCollection): return ctor(values=vals) else: return vals elif isinstance(obj, (dict, DictCollection)): if self.has_none: tail = self.heads[None] return ctor( (k, self._get(v, tail)) for k, v in obj.iteritems() ) else: return ctor( (head, self._get(obj[head], tail)) for head, tail in self.heads.iteritems() if head in obj ) else: if self.has_int or (self.has_none and self.heads[None] is not all): raise TypeError( "MultiFieldSelector has %s in %s context" % ( "int" if self.has_int else "none", ctor.__name__ ) ) if self.has_none: return self._get(obj, all) else: kwargs = dict() for head, tail in self.heads.iteritems(): val = getattr(obj, head, None) if val is not None: kwargs[head] = self._get(val, tail) return ctor(**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, obj, force=False): """Deletes all of the fields at the specified locations. args: ``obj=``\ *OBJECT* the object to remove the fields from ``force=``\ *BOOL* if True, missing attributes do not raise errors. Otherwise, the first failure raises an exception without making any changes to ``obj``. """
# TODO: this could be a whole lot more efficient! if not force: for fs in self: try: fs.get(obj) except FieldSelectorException: raise for fs in self: try: fs.delete(obj) except FieldSelectorException: 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 reset_socat(use_sudo=False): """ Finds and closes all processes of `socat`. :param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `sudo`, this is by default set to ``False``. Setting it to ``True`` could unintentionally remove instances from other users. :type use_sudo: bool """
output = stdout_result('ps -o pid -C socat', quiet=True) pids = output.split('\n')[1:] puts("Removing process(es) with id(s) {0}.".format(', '.join(pids))) which = sudo if use_sudo else run which('kill {0}'.format(' '.join(pids)), quiet=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 version(): """ Shows version information of the remote Docker service, similar to ``docker version``. """
output = docker_fabric().version() col_len = max(map(len, output.keys())) + 1 puts('') for k, v in six.iteritems(output): fastprint('{0:{1}} {2}'.format(''.join((k, ':')), col_len, v), end='\n', flush=False) fastprint('', flush=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 list_images(list_all=False, full_ids=False): """ Lists images on the Docker remote host, similar to ``docker images``. :param list_all: Lists all images (e.g. dependencies). Default is ``False``, only shows named images. :type list_all: bool :param full_ids: Shows the full ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool """
images = docker_fabric().images(all=list_all) _format_output_table(images, IMAGE_COLUMNS, full_ids)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False): """ Lists containers on the Docker remote host, similar to ``docker ps``. :param list_all: Shows all containers. Default is ``False``, which omits exited containers. :type list_all: bool :param short_image: Hides the repository prefix for preserving space. Default is ``True``. :type short_image: bool :param full_ids: Shows the full image ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool :param full_cmd: Shows the full container command. When ``False`` (default) only shows the first 25 characters. :type full_cmd: bool """
containers = docker_fabric().containers(all=list_all) _format_output_table(containers, CONTAINER_COLUMNS, full_ids, full_cmd, short_image)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_networks(full_ids=False): """ Lists networks on the Docker remote host, similar to ``docker network ls``. :param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters. :type full_ids: bool """
networks = docker_fabric().networks() _format_output_table(networks, NETWORK_COLUMNS, full_ids)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_containers(**kwargs): """ Removes all containers that have finished running. Similar to the ``prune`` functionality in newer Docker versions. """
containers = docker_fabric().cleanup_containers(**kwargs) if kwargs.get('list_only'): puts('Existing containers:') for c_id, c_name in containers: fastprint('{0} {1}'.format(c_id, c_name), end='\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 cleanup_images(remove_old=False, **kwargs): """ Removes all images that have no name, and that are not references as dependency by any other named image. Similar to the ``prune`` functionality in newer Docker versions, but supports more filters. :param remove_old: Also remove images that do have a name, but no `latest` tag. :type remove_old: bool """
keep_tags = env.get('docker_keep_tags') if keep_tags is not None: kwargs.setdefault('keep_tags', keep_tags) removed_images = docker_fabric().cleanup_images(remove_old=remove_old, **kwargs) if kwargs.get('list_only'): puts('Unused images:') for image_name in removed_images: fastprint(image_name, end='\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 save_image(image, filename=None): """ Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client on the host, generates a gzip-tarball and downloads that. :param image: Image name or id. :type image: unicode :param filename: File name to store the local file. If not provided, will use ``<image>.tar.gz`` in the current working directory. :type filename: unicode """
local_name = filename or '{0}.tar.gz'.format(image) cli.save_image(image, local_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 load_image(filename, timeout=120): """ Uploads an image from a local file to a Docker remote. Note that this temporarily has to extend the service timeout period. :param filename: Local file name. :type filename: unicode :param timeout: Timeout in seconds to set temporarily for the upload. :type timeout: int """
c = docker_fabric() with open(expand_path(filename), 'r') as f: _timeout = c._timeout c._timeout = timeout try: c.load_image(f) finally: c._timeout = _timeout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_iter(self, other, **kwargs): """Generator method which returns the differences from the invocant to the argument. args: ``other=``\ *Record*\ \|\ *Anything* The thing to compare against; the types must match, unless ``duck_type=True`` is passed. *diff_option*\ =\ *value* Unknown keyword arguments are eventually passed to a :ref:`DiffOptions` constructor. """
from normalize.diff import diff_iter return diff_iter(self, other, **kwargs)
<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_weights(weight_args, default_weight=0.6): """Parse list of weight assignments."""
weights_dict = {} r_group_weight = default_weight for weight_arg in weight_args: for weight_assignment in weight_arg.split(','): if '=' not in weight_assignment: raise ValueError( 'Invalid weight assignment: {}'.format(weight_assignment)) key, value = weight_assignment.split('=', 1) value = float(value) if key == 'R': r_group_weight = value elif key == '*': default_weight = value elif hasattr(Atom, key): weights_dict[Atom(key)] = value else: raise ValueError('Invalid element: {}'.format(key)) return weights_dict, r_group_weight, default_weight
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _combine_transfers(self, result): """Combine multiple pair transfers into one."""
transfers = {} for reaction_id, c1, c2, form in result: key = reaction_id, c1, c2 combined_form = transfers.setdefault(key, Formula()) transfers[key] = combined_form | form for (reaction_id, c1, c2), form in iteritems(transfers): yield reaction_id, c1, c2, form
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_resource(container, resource, local_filename, contents_only=True): """ Copies a resource from a container to a compressed tarball and downloads it. :param container: Container name or id. :type container: unicode :param resource: Name of resource to copy. :type resource: unicode :param local_filename: Path to store the tarball locally. :type local_filename: unicode :param contents_only: In case ``resource`` is a directory, put all contents at the root of the tar file. If this is set to ``False``, the directory itself will be at the root instead. :type contents_only: bool """
with temp_dir() as remote_tmp: base_name = os.path.basename(resource) copy_path = posixpath.join(remote_tmp, 'copy_tmp') run(mkdir(copy_path, check_if_exists=True)) remote_name = posixpath.join(copy_path, base_name) archive_name = 'container_{0}.tar.gz'.format(container) archive_path = posixpath.join(remote_tmp, archive_name) run('docker cp {0}:{1} {2}'.format(container, resource, copy_path), shell=False) if contents_only and is_directory(remote_name): src_dir = remote_name src_files = '*' else: src_dir = copy_path src_files = base_name with cd(src_dir): run(targz(archive_path, src_files)) get(archive_path, local_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 save_image(image, local_filename): """ Saves a Docker image as a compressed tarball. This command line client method is a suitable alternative, if the Remove API method is too slow. :param image: Image id or tag. :type image: unicode :param local_filename: Local file name to store the image into. If this is a directory, the image will be stored there as a file named ``image_<Image name>.tar.gz``. """
r_name, __, i_name = image.rpartition('/') i_name, __, __ = i_name.partition(':') with temp_dir() as remote_tmp: archive = posixpath.join(remote_tmp, 'image_{0}.tar.gz'.format(i_name)) run('docker save {0} | gzip --stdout > {1}'.format(image, archive), shell=False) get(archive, local_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 decode_name(s): """Decode names in ModelSEED files"""
# Some names contain XML-like entity codes return re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), s)
<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_compound_file(f, context=None): """Iterate over the compound entries in the given file"""
f.readline() # Skip header for lineno, row in enumerate(csv.reader(f, delimiter='\t')): compound_id, names, formula = row[:3] names = (decode_name(name) for name in names.split(',<br>')) # ModelSEED sometimes uses an asterisk and number at # the end of formulas. This seems to have a similar # meaning as '(...)n'. m = re.match(r'^(.*)\*(\d*)$', formula) if m is not None: if m.group(2) != '': formula = '({}){}'.format(m.group(1), m.group(2)) else: formula = '({})n'.format(m.group(1)) formula = formula.strip() if formula == '' or formula == 'noformula': formula = None mark = FileMark(context, lineno, 0) yield CompoundEntry(compound_id, names, formula, filemark=mark)
<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_parser(cls, parser): """Initialize argument parser"""
subparsers = parser.add_subparsers(title='Search domain') # Compound subcommand parser_compound = subparsers.add_parser( 'compound', help='Search in compounds') parser_compound.set_defaults(which='compound') parser_compound.add_argument( '--id', '-i', dest='id', metavar='id', action=FilePrefixAppendAction, type=text_type, default=[], help='Compound ID') parser_compound.add_argument( '--name', '-n', dest='name', metavar='name', action=FilePrefixAppendAction, type=text_type, default=[], help='Name of compound') # Reaction subcommand parser_reaction = subparsers.add_parser( 'reaction', help='Search in reactions') parser_reaction.set_defaults(which='reaction') parser_reaction.add_argument( '--id', '-i', dest='id', metavar='id', action=FilePrefixAppendAction, type=str, default=[], help='Reaction ID') parser_reaction.add_argument( '--compound', '-c', dest='compound', metavar='compound', action=FilePrefixAppendAction, type=str, default=[], help='Comma-separated list of compound IDs')
<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(self): """Run search command."""
which_command = self._args.which if which_command == 'compound': self._search_compound() elif which_command == 'reaction': self._search_reaction()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self, propval, extraneous=False, to_json_func=None): """This function calls the ``json_out`` function, if it was specified, otherwise continues with JSON conversion of the value in the slot by calling ``to_json_func`` on it. """
if self.json_out: return self.json_out(propval) else: if not to_json_func: from normalize.record.json import to_json to_json_func = to_json return to_json_func(propval, extraneous)
<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_compound(s, global_compartment=None): """Parse a compound specification. If no compartment is specified in the string, the global compartment will be used. """
m = re.match(r'^\|(.*)\|$', s) if m: s = m.group(1) m = re.match(r'^(.+)\[(\S+)\]$', s) if m: compound_id = m.group(1) compartment = m.group(2) else: compound_id = s compartment = global_compartment return Compound(compound_id, compartment=compartment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_sparse(strategy, prob, obj_reaction, flux_threshold): """Find a random minimal network of model reactions. Given a reaction to optimize and a threshold, delete entities randomly until the flux of the reaction to optimize falls under the threshold. Keep deleting until no more entities can be deleted. It works with two strategies: deleting reactions or deleting genes (reactions related to certain genes). Args: strategy: :class:`.ReactionDeletionStrategy` or :class:`.GeneDeletionStrategy`. prob: :class:`psamm.fluxanalysis.FluxBalanceProblem`. obj_reaction: objective reactions to optimize. flux_threshold: threshold of max reaction flux. """
essential = set() deleted = set() for entity, deleted_reactions in strategy.iter_tests(): if obj_reaction in deleted_reactions: logger.info( 'Marking entity {} as essential because the objective' ' reaction depends on this entity...'.format(entity)) essential.add(entity) continue if len(deleted_reactions) == 0: logger.info( 'No reactions were removed when entity {}' ' was deleted'.format(entity)) deleted.add(entity) strategy.delete(entity, deleted_reactions) continue logger.info('Deleted reactions: {}'.format( ', '.join(deleted_reactions))) constr = [] for r in deleted_reactions: flux_var = prob.get_flux_var(r) c, = prob.prob.add_linear_constraints(flux_var == 0) constr.append(c) logger.info('Trying FBA without reactions {}...'.format( ', '.join(deleted_reactions))) try: prob.maximize(obj_reaction) except fluxanalysis.FluxBalanceError: logger.info( 'FBA is infeasible, marking {} as essential'.format( entity)) for c in constr: c.delete() essential.add(entity) continue logger.debug('Reaction {} has flux {}'.format( obj_reaction, prob.get_flux(obj_reaction))) if prob.get_flux(obj_reaction) < flux_threshold: for c in constr: c.delete() essential.add(entity) logger.info('Entity {} was essential'.format( entity)) else: deleted.add(entity) strategy.delete(entity, deleted_reactions) logger.info('Entity {} was deleted'.format(entity)) return essential, deleted
<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_sink_check(self, model, solver, threshold, implicit_sinks=True): """Run sink production check method."""
prob = solver.create_problem() # Create flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[reaction_id] v.define([reaction_id], lower=lower, upper=upper) # Build mass balance constraints massbalance_lhs = {compound: 0 for compound in model.compounds} for spec, value in iteritems(model.matrix): compound, reaction_id = spec massbalance_lhs[compound] += v(reaction_id) * value mass_balance_constrs = {} for compound, lhs in iteritems(massbalance_lhs): if implicit_sinks: # The constraint is merely >0 meaning that we have implicit # sinks for all compounds. prob.add_linear_constraints(lhs >= 0) else: # Save these constraints so we can temporarily remove them # to create a sink. c, = prob.add_linear_constraints(lhs == 0) mass_balance_constrs[compound] = c for compound, lhs in sorted(iteritems(massbalance_lhs)): if not implicit_sinks: mass_balance_constrs[compound].delete() prob.set_objective(lhs) try: result = prob.solve(lp.ObjectiveSense.Maximize) except lp.SolverError as e: logger.warning('Failed to solve for compound: {} ({})'.format( compound, e)) if result.get_value(lhs) < threshold: yield compound if not implicit_sinks: # Restore mass balance constraint. c, = prob.add_linear_constraints(lhs == 0) mass_balance_constrs[compound] = c
<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_reaction_production_check(self, model, solver, threshold, implicit_sinks=True): """Run reaction production check method."""
prob = solver.create_problem() # Create flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[reaction_id] v.define([reaction_id], lower=lower, upper=upper) # Build mass balance constraints massbalance_lhs = {compound: 0 for compound in model.compounds} for spec, value in iteritems(model.matrix): compound, reaction_id = spec massbalance_lhs[compound] += v(reaction_id) * value # Create production variables and apply constraints for compound, lhs in iteritems(massbalance_lhs): if implicit_sinks: # The constraint is merely >0 meaning that we have implicit # sinks for all compounds. prob.add_linear_constraints(lhs >= 0) else: prob.add_linear_constraints(lhs == 0) confirmed_production = set() for reaction in model.reactions: if all(c in confirmed_production for c, _ in model.get_reaction_values(reaction)): continue prob.set_objective(v(reaction)) for sense in (lp.ObjectiveSense.Maximize, lp.ObjectiveSense.Minimize): try: result = prob.solve(sense) except lp.SolverError as e: self.fail( 'Failed to solve for compound, reaction: {}, {}:' ' {}'.format(compound, reaction, e)) flux = result.get_value(v(reaction)) for compound, value in model.get_reaction_values(reaction): if compound in confirmed_production: continue production = 0 if sense == lp.ObjectiveSense.Maximize and flux > 0: production = float(value) * flux elif sense == lp.ObjectiveSense.Minimize and flux < 0: production = float(value) * flux if production >= threshold: confirmed_production.add(compound) for compound in sorted(model.compounds): if compound not in confirmed_production: yield compound
<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_linear_constraints(self, *relations): """Add constraints to the problem Each constraint is represented by a Relation, and the expression in that relation can be a set expression. """
constraints = [] for relation in relations: if self._check_relation(relation): constraints.append(Constraint(self, None)) else: for name in self._add_constraints(relation): constraints.append(Constraint(self, name)) return constraints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_objective(self, expression): """Set objective expression of the problem."""
if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression(offset=expression) linear = [] quad = [] # Reset previous objective. for var in self._non_zero_objective: if var not in expression: if not isinstance(var, Product): linear.append((self._variables[var], 0)) else: t = self._variables[var[0]], self._variables[var[1]], 0 quad.append(t) self._non_zero_objective.clear() # Set actual objective values for var, value in expression.values(): if not isinstance(var, Product): self._non_zero_objective.add(var) linear.append((self._variables[var], float(value))) else: if len(var) > 2: raise ValueError('Invalid objective: {}'.format(var)) self._non_zero_objective.add(var) var1 = self._variables[var[0]] var2 = self._variables[var[1]] if var1 == var2: value *= 2 quad.append((var1, var2, float(value))) # We have to build the set of variables to # update so that we can avoid calling set_linear if the set is empty. # This is due to set_linear failing if the input is an empty # iterable. if len(linear) > 0: self._cp.objective.set_linear(linear) if len(quad) > 0: self._cp.objective.set_quadratic_coefficients(quad) if hasattr(self._cp.objective, 'set_offset'): self._cp.objective.set_offset(float(expression.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 _reset_problem_type(self): """Reset problem type to whatever is appropriate."""
# Only need to reset the type after the first solve. This also works # around a bug in Cplex where get_num_binary() is some rare cases # causes a segfault. if self._solve_count > 0: integer_count = 0 for func in (self._cp.variables.get_num_binary, self._cp.variables.get_num_integer, self._cp.variables.get_num_semicontinuous, self._cp.variables.get_num_semiinteger): integer_count += func() integer = integer_count > 0 quad_constr = self._cp.quadratic_constraints.get_num() > 0 quad_obj = self._cp.objective.get_num_quadratic_variables() > 0 if not integer: if quad_constr: new_type = self._cp.problem_type.QCP elif quad_obj: new_type = self._cp.problem_type.QP else: new_type = self._cp.problem_type.LP else: if quad_constr: new_type = self._cp.problem_type.MIQCP elif quad_obj: new_type = self._cp.problem_type.MIQP else: new_type = self._cp.problem_type.MILP logger.debug('Setting problem type to {}...'.format( self._cp.problem_type[new_type])) self._cp.set_problem_type(new_type) else: logger.debug('Problem type is {}'.format( self._cp.problem_type[self._cp.get_problem_type()])) # Force QP/MIQP solver to look for global optimum. We set it here only # for QP/MIQP problems to avoid the warnings generated for other # problem types when this parameter is set. quad_obj = self._cp.objective.get_num_quadratic_variables() > 0 if hasattr(self._cp.parameters, 'optimalitytarget'): target_param = self._cp.parameters.optimalitytarget else: target_param = self._cp.parameters.solutiontarget if quad_obj: target_param.set(target_param.values.optimal_global) else: target_param.set(target_param.values.auto)
<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_value(self, expression): """Return value of expression."""
self._check_valid() return super(Result, self).get_value(expression)
<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_formula(s): """Parse formula string."""
scanner = re.compile(r''' (\s+) | # whitespace (\(|\)) | # group ([A-Z][a-z]*) | # element (\d+) | # number ([a-z]) | # variable (\Z) | # end (.) # error ''', re.DOTALL | re.VERBOSE) def transform_subformula(form): """Extract radical if subformula is a singleton with a radical.""" if isinstance(form, dict) and len(form) == 1: # A radical in a singleton subformula is interpreted as a # numbered radical. element, value = next(iteritems(form)) if isinstance(element, Radical): return Radical('{}{}'.format(element.symbol, value)) return form stack = [] formula = {} expect_count = False def close(formula, count=1): if len(stack) == 0: raise ParseError('Unbalanced parenthesis group in formula') subformula = transform_subformula(formula) if isinstance(subformula, dict): subformula = Formula(subformula) formula = stack.pop() if subformula not in formula: formula[subformula] = 0 formula[subformula] += count return formula for match in re.finditer(scanner, s): (whitespace, group, element, number, variable, end, error) = match.groups() if error is not None: raise ParseError( 'Invalid token in formula string: {!r}'.format(match.group(0)), span=(match.start(), match.end())) elif whitespace is not None: continue elif group is not None and group == '(': if expect_count: formula = close(formula) stack.append(formula) formula = {} expect_count = False elif group is not None and group == ')': if expect_count: formula = close(formula) expect_count = True elif element is not None: if expect_count: formula = close(formula) stack.append(formula) if element in 'RX': formula = Radical(element) else: formula = Atom(element) expect_count = True elif number is not None and expect_count: formula = close(formula, int(number)) expect_count = False elif variable is not None and expect_count: formula = close(formula, Expression(variable)) expect_count = False elif end is not None: if expect_count: formula = close(formula) else: raise ParseError( 'Invalid token in formula string: {!r}'.format(match.group(0)), span=(match.start(), match.end())) if len(stack) > 0: raise ParseError('Unbalanced parenthesis group in formula') return Formula(formula)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Be sure to implement this method when sub-classing, otherwise you will lose any specialization context."""
doppel = type(self)( self.unpack, self.apply, self.collect, self.reduce, apply_empty_slots=self.apply_empty_slots, extraneous=self.extraneous, ignore_empty_string=self.ignore_empty_string, ignore_none=self.ignore_none, visit_filter=self.visit_filter, ) for x in self.cue: doppel.push(x) doppel.seen = self.seen return doppel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack(cls, value, value_type, visitor): """Unpack a value during a 'visit' args: ``value=``\ *object* The instance being visited ``value_type=``\ *RecordType* The expected type of the instance ``visitor=``\ *Visitor* The context/options returns a tuple with two items: ``get_prop=``\ *function* This function should take a :py:class:`normalize.property.Property` instance, and return the slot from the value, or raise ``AttributeError`` or ``KeyError`` if the slot is empty. Returning nothing means that the item has no properties to unpack; ie, it's an opaque type. ``get_item=``\ *generator* This generator should return the tuple protocol used by :py:class:`normalize.coll.Collection`: (K, V) where K can be an ascending integer (for sequences), V (for sets), or something hashable like a string (for dictionaries/maps) """
if issubclass(value_type, Collection): try: generator = value.itertuples() except AttributeError: if isinstance(value, value_type.colltype): generator = value_type.coll_to_tuples(value) else: raise exc.VisitorUnpackError( passed=value, colltype=value_type.colltype.__name__, context=visitor, ) else: generator = None if issubclass(value_type, Record): def propget(prop): return prop.__get__(value) else: propget = None return propget, generator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(cls, value, prop, visitor): """'apply' is a general place to put a function which is called on every extant record slot. This is usually the most important function to implement when sub-classing. The default implementation passes through the slot value as-is, but expected exceptions are converted to ``None``. args: ``value=``\ *value*\ \|\ *AttributeError*\ \|\ *KeyError* This is the value currently in the slot, or the Record itself with the ``apply_records`` visitor option. *AttributeError* will only be received if you passed ``apply_empty_slots``, and *KeyError* will be passed if ``parent_obj`` is a ``dict`` (see :py:meth:`Visitor.map_prop` for details about when this might happen) ``prop=``\ *Property*\ \|\ ``None`` This is the :py:class:`normalize.Property` instance which represents the field being traversed. This can be ``None`` when being applied over Collection instances, where the type of the contents is not a Record. ``visitor=``\ *Visitor* This object can be used to inspect parameters of the current run, such as options which control which kinds of values are visited, which fields are being visited and where the function is in relation to the starting point. """
return ( None if isinstance(value, (AttributeError, KeyError)) else value )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate(self, mapped_coll_generator, coll_type, visitor): """Hook called for each normalize.coll.Collection, after mapping over each of the items in the collection. The default implementation calls :py:meth:`normalize.coll.Collection.tuples_to_coll` with ``coerce=False``, which just re-assembles the collection into a native python collection type of the same type of the input collection. args: ``result_coll_generator=`` *generator func* Generator which returns (key, value) pairs (like :py:meth:`normalize.coll.Collection.itertuples`) ``coll_type=``\ *CollectionType* This is the :py:class:`normalize.coll.Collection`-derived *class* which is currently being reduced. ``visitor=``\ *Visitor* Context/options object """
return coll_type.tuples_to_coll(mapped_coll_generator, coerce=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 reduce(self, mapped_props, aggregated, value_type, visitor): """This reduction is called to combine the mapped slot and collection item values into a single value for return. The default implementation tries to behave naturally; you'll almost always get a dict back when mapping over a record, and list or some other collection when mapping over collections. If the collection has additional properties which are not ignored (eg, not extraneous, not filtered), then the result will be a dictionary with the results of mapping the properties, and a 'values' key will be added with the result of mapping the items in the collection. args: ``mapped_props=``\ *generator* Iterating over this generator will yield K, V pairs, where K is **the Property object** and V is the mapped value. ``aggregated=``\ *object* This contains whatever ``aggregate`` returned, normally a list. ``value_type=``\ *RecordType* This is the type which is currently being reduced. A :py:class:`normalize.record.Record` subclass ``visitor=``\ *Visitor* Contenxt/options object. """
reduced = None if mapped_props: reduced = dict((k.name, v) for k, v in mapped_props) if issubclass(value_type, Collection) and aggregated is not None: if all(visitor.is_filtered(prop) for prop in value_type.properties.values()): reduced = aggregated else: if reduced.get("values", False): raise exc.VisitorTooSimple( fs=visitor.field_selector, value_type_name=value_type.__name__, visitor=type(self).__name__, ) else: reduced['values'] = aggregated return reduced
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reflect(cls, X, **kwargs): """Reflect is for visitors where you are exposing some information about the types reachable from a starting type to an external system. For example, a front-end, a REST URL router and documentation framework, an avro schema definition, etc. X can be a type or an instance. This API should be considered **experimental** """
if isinstance(X, type): value = None value_type = X else: value = X value_type = type(X) if not issubclass(value_type, Record): raise TypeError("Cannot reflect on %s" % value_type.__name__) visitor = cls.Visitor( cls.scantypes, cls.propinfo, cls.itemtypes, cls.typeinfo, **kwargs) return cls.map(visitor, value, value_type)
<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(cls, visitor, value, value_type): """The common visitor API used by all three visitor implementations. args: ``visitor=``\ *Visitor* Visitor options instance: contains the callbacks to use to implement the visiting, as well as traversal & filtering options. ``value=``\ *Object* Object being visited ``value_type=``\ *RecordType* The type object controlling the visiting. """
unpacked = visitor.unpack(value, value_type, visitor) if unpacked == cls.StopVisiting or isinstance( unpacked, cls.StopVisiting ): return unpacked.return_value if isinstance(unpacked, tuple): props, coll = unpacked else: props, coll = unpacked, None # recurse into values for collections if coll: coll_map_generator = cls.map_collection( visitor, coll, value_type, ) mapped_coll = visitor.collect( coll_map_generator, value_type, visitor, ) else: mapped_coll = None # recurse into regular properties mapped_props = None if props: mapped_props = cls.map_record(visitor, props, value_type) elif mapped_coll is None: return visitor.apply(value, None, visitor) return visitor.reduce( mapped_props, mapped_coll, value_type, visitor, )
<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_fba_problem(model, tfba, solver): """Convenience function for returning the right FBA problem instance"""
p = FluxBalanceProblem(model, solver) if tfba: p.add_thermodynamic() return p
<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_balance(model, reaction, tfba, solver): """Run flux balance analysis on the given model. Yields the reaction id and flux value for each reaction in the model. This is a convenience function for sertting up and running the FluxBalanceProblem. If the FBA is solved for more than one parameter it is recommended to setup and reuse the FluxBalanceProblem manually for a speed up. This is an implementation of flux balance analysis (FBA) as described in [Orth10]_ and [Fell86]_. Args: model: MetabolicModel to solve. reaction: Reaction to maximize. If a dict is given, this instead represents the objective function weights on each reaction. tfba: If True enable thermodynamic constraints. solver: LP solver instance to use. Returns: Iterator over reaction ID and reaction flux pairs. """
fba = _get_fba_problem(model, tfba, solver) fba.maximize(reaction) for reaction in model.reactions: yield reaction, fba.get_flux(reaction)
<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_variability(model, reactions, fixed, tfba, solver): """Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a tuple of minimum and maximum value for each of the given reactions. The fixed reactions are given in a dictionary as a reaction id to value mapping. This is an implementation of flux variability analysis (FVA) as described in [Mahadevan03]_. Args: model: MetabolicModel to solve. reactions: Reactions on which to report variablity. fixed: dict of additional lower bounds on reaction fluxes. tfba: If True enable thermodynamic constraints. solver: LP solver instance to use. Returns: Iterator over pairs of reaction ID and bounds. Bounds are returned as pairs of lower and upper values. """
fba = _get_fba_problem(model, tfba, solver) for reaction_id, value in iteritems(fixed): flux = fba.get_flux_var(reaction_id) fba.prob.add_linear_constraints(flux >= value) def min_max_solve(reaction_id): for direction in (-1, 1): yield fba.flux_bound(reaction_id, direction) # Solve for each reaction for reaction_id in reactions: yield reaction_id, tuple(min_max_solve(reaction_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 flux_minimization(model, fixed, solver, weights={}): """Minimize flux of all reactions while keeping certain fluxes fixed. The fixed reactions are given in a dictionary as reaction id to value mapping. The weighted L1-norm of the fluxes is minimized. Args: model: MetabolicModel to solve. fixed: dict of additional lower bounds on reaction fluxes. solver: LP solver instance to use. weights: dict of weights on the L1-norm terms. Returns: An iterator of reaction ID and reaction flux pairs. """
fba = FluxBalanceProblem(model, solver) for reaction_id, value in iteritems(fixed): flux = fba.get_flux_var(reaction_id) fba.prob.add_linear_constraints(flux >= value) fba.minimize_l1() return ((reaction_id, fba.get_flux(reaction_id)) for reaction_id in model.reactions)
<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_randomization(model, threshold, tfba, solver): """Find a random flux solution on the boundary of the solution space. The reactions in the threshold dictionary are constrained with the associated lower bound. Args: model: MetabolicModel to solve. threshold: dict of additional lower bounds on reaction fluxes. tfba: If True enable thermodynamic constraints. solver: LP solver instance to use. Returns: An iterator of reaction ID and reaction flux pairs. """
optimize = {} for reaction_id in model.reactions: if model.is_reversible(reaction_id): optimize[reaction_id] = 2*random.random() - 1.0 else: optimize[reaction_id] = random.random() fba = _get_fba_problem(model, tfba, solver) for reaction_id, value in iteritems(threshold): fba.prob.add_linear_constraints(fba.get_flux_var(reaction_id) >= value) fba.maximize(optimize) for reaction_id in model.reactions: yield reaction_id, fba.get_flux(reaction_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 consistency_check(model, subset, epsilon, tfba, solver): """Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and also allows the reaction in question to have non-zero flux. This can be determined by running FBA on each reaction in turn and checking whether the flux in the solution is non-zero. Since FBA only tries to maximize the flux (and the flux can be negative for reversible reactions), we have to try to both maximize and minimize the flux. An optimization to this method is implemented such that if checking one reaction results in flux in another unchecked reaction, that reaction will immediately be marked flux consistent. Args: model: MetabolicModel to check for consistency. subset: Subset of model reactions to check. epsilon: The threshold at which the flux is considered non-zero. tfba: If True enable thermodynamic constraints. solver: LP solver instance to use. Returns: An iterator of flux inconsistent reactions in the subset. """
fba = _get_fba_problem(model, tfba, solver) subset = set(subset) while len(subset) > 0: reaction = next(iter(subset)) logger.info('{} left, checking {}...'.format(len(subset), reaction)) fba.maximize(reaction) subset = set(reaction_id for reaction_id in subset if abs(fba.get_flux(reaction_id)) <= epsilon) if reaction not in subset: continue elif model.is_reversible(reaction): fba.maximize({reaction: -1}) subset = set(reaction_id for reaction_id in subset if abs(fba.get_flux(reaction_id)) <= epsilon) if reaction not in subset: continue logger.info('{} not consistent!'.format(reaction)) yield reaction subset.remove(reaction)
<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_thermodynamic(self, em=1000): """Apply thermodynamic constraints to the model. Adding these constraints restricts the solution space to only contain solutions that have no internal loops [Schilling00]_. This is solved as a MILP problem as described in [Muller13]_. The time to solve a problem with thermodynamic constraints is usually much longer than a normal FBA problem. The ``em`` parameter is the upper bound on the delta mu reaction variables. This parameter has to be balanced based on the model size since setting the value too low can result in the correct solutions being infeasible and setting the value too high can result in numerical instability which again makes the correct solutions infeasible. The default value should work in all cases as long as the model is not unusually large. """
internal = set(r for r in self._model.reactions if not self._model.is_exchange(r)) # Reaction fluxes v = self._v # Indicator variable alpha = self._prob.namespace(internal, types=lp.VariableType.Binary) # Delta mu is the stoichiometrically weighted sum of the compound mus. dmu = self._prob.namespace(internal) for reaction_id in self._model.reactions: if not self._model.is_exchange(reaction_id): flux = v(reaction_id) alpha_r = alpha(reaction_id) dmu_r = dmu(reaction_id) lower, upper = self._model.limits[reaction_id] # Constrain the reaction to a direction determined by alpha # and contrain the delta mu to a value in [-em; -1] if # alpha is one, otherwise in [1; em]. self._prob.add_linear_constraints( flux >= lower * (1 - alpha_r), flux <= upper * alpha_r, dmu_r >= -em * alpha_r + (1 - alpha_r), dmu_r <= em * (1 - alpha_r) - alpha_r) # Define mu variables mu = self._prob.namespace(self._model.compounds) tdbalance_lhs = {reaction_id: 0 for reaction_id in self._model.reactions} for spec, value in iteritems(self._model.matrix): compound, reaction_id = spec if not self._model.is_exchange(reaction_id): tdbalance_lhs[reaction_id] += mu(compound) * value for reaction_id, lhs in iteritems(tdbalance_lhs): if not self._model.is_exchange(reaction_id): self._prob.add_linear_constraints(lhs == dmu(reaction_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 maximize(self, reaction): """Solve the model by maximizing the given reaction. If reaction is a dictionary object, each entry is interpreted as a weight on the objective for that reaction (non-existent reaction will have zero weight). """
self._prob.set_objective(self.flux_expr(reaction)) self._solve()
<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_bound(self, reaction, direction): """Return the flux bound of the reaction. Direction must be a positive number to obtain the upper bound or a negative number to obtain the lower bound. A value of inf or -inf is returned if the problem is unbounded. """
try: self.maximize({reaction: direction}) except FluxBalanceError as e: if not e.result.unbounded: raise return direction * _INF else: return self.get_flux(reaction)
<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_minimization_vars(self): """Add variables and constraints for L1 norm minimization."""
self._z = self._prob.namespace(self._model.reactions, lower=0) # Define constraints v = self._v.set(self._model.reactions) z = self._z.set(self._model.reactions) self._prob.add_linear_constraints(z >= v, v >= -z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimize_l1(self, weights={}): """Solve the model by minimizing the L1 norm of the fluxes. If the weights dictionary is given, the weighted L1 norm if minimized instead. The dictionary contains the weights of each reaction (default 1). """
if self._z is None: self._add_minimization_vars() objective = self._z.expr( (reaction_id, -weights.get(reaction_id, 1)) for reaction_id in self._model.reactions) self._prob.set_objective(objective) self._solve()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_min_l1(self, reaction, weights={}): """Maximize flux of reaction then minimize the L1 norm. During minimization the given reaction will be fixed at the maximum obtained from the first solution. If reaction is a dictionary object, each entry is interpreted as a weight on the objective for that reaction (non-existent reaction will have zero weight). """
self.maximize(reaction) if isinstance(reaction, dict): reactions = list(reaction) else: reactions = [reaction] # Save flux values before modifying the LP problem fluxes = {r: self.get_flux(r) for r in reactions} # Add constraints on the maximized reactions for r in reactions: flux_var = self.get_flux_var(r) c, = self._prob.add_linear_constraints(flux_var == fluxes[r]) self._temp_constr.append(c) self.minimize_l1(weights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _solve(self): """Solve the problem with the current objective."""
# Remove temporary constraints while len(self._remove_constr) > 0: self._remove_constr.pop().delete() try: self._prob.solve(lp.ObjectiveSense.Maximize) except lp.SolverError as e: raise_from(FluxBalanceError('Failed to solve: {}'.format( e), result=self._prob.result), e) finally: # Set temporary constraints to be removed on next solve call self._remove_constr = self._temp_constr self._temp_constr = []
<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_expr(self, reaction): """Get LP expression representing the reaction flux."""
if isinstance(reaction, dict): return self._v.expr(iteritems(reaction)) return self._v(reaction)
<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_flux(self, reaction): """Get resulting flux value for reaction."""
return self._prob.result.get_value(self._v(reaction))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_objective(self, expression): """Set linear objective of problem"""
if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression() self._p.set_linear_objective( (lp_name, expression.value(var)) for var, lp_name in iteritems(self._variables))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unbounded(self): """Whether the solution is unbounded"""
self._check_valid() return (self._problem._p.get_status() == qsoptex.SolutionStatus.UNBOUNDED)
<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(job, f, o=None): """ Executes a librsync "job" by reading bytes from `f` and writing results to `o` if provided. If `o` is omitted, the output is ignored. """
# Re-use the same buffer for output, we will read from it after each # iteration. out = ctypes.create_string_buffer(RS_JOB_BLOCKSIZE) while True: block = f.read(RS_JOB_BLOCKSIZE) buff = Buffer() # provide the data block via input buffer. buff.next_in = ctypes.c_char_p(block) buff.avail_in = ctypes.c_size_t(len(block)) buff.eof_in = ctypes.c_int(not block) # Set up our buffer for output. buff.next_out = ctypes.cast(out, ctypes.c_char_p) buff.avail_out = ctypes.c_size_t(RS_JOB_BLOCKSIZE) r = _librsync.rs_job_iter(job, ctypes.byref(buff)) if o: o.write(out.raw[:RS_JOB_BLOCKSIZE - buff.avail_out]) if r == RS_DONE: break elif r != RS_BLOCKED: raise LibrsyncError(r) if buff.avail_in > 0: # There is data left in the input buffer, librsync did not consume # all of it. Rewind the file a bit so we include that data in our # next read. It would be better to simply tack data to the end of # this buffer, but that is very difficult in Python. f.seek(f.tell() - buff.avail_in) if o and callable(getattr(o, 'seek', None)): # As a matter of convenience, rewind the output file. o.seek(0) return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signature(f, s=None, block_size=RS_DEFAULT_BLOCK_LEN): """ Generate a signature for the file `f`. The signature will be written to `s`. If `s` is omitted, a temporary file will be used. This function returns the signature file `s`. You can specify the size of the blocks using the optional `block_size` parameter. """
if s is None: s = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') job = _librsync.rs_sig_begin(block_size, RS_DEFAULT_STRONG_LEN) try: _execute(job, f, s) finally: _librsync.rs_job_free(job) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delta(f, s, d=None): """ Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary file will be used. This function returns the delta file `d`. All parameters must be file-like objects. """
if d is None: d = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') sig = ctypes.c_void_p() try: job = _librsync.rs_loadsig_begin(ctypes.byref(sig)) try: _execute(job, s) finally: _librsync.rs_job_free(job) r = _librsync.rs_build_hash_table(sig) if r != RS_DONE: raise LibrsyncError(r) job = _librsync.rs_delta_begin(sig) try: _execute(job, f, d) finally: _librsync.rs_job_free(job) finally: _librsync.rs_free_sumset(sig) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(f, d, o=None): """ Patch the file `f` using the delta `d`. The patched file will be written to `o`. If `o` is omitted, a temporary file will be used. This function returns the be patched file `o`. All parameters should be file-like objects. `f` is required to be seekable. """
if o is None: o = tempfile.SpooledTemporaryFile(max_size=MAX_SPOOL, mode='wb+') @patch_callback def read_cb(opaque, pos, length, buff): f.seek(pos) size_p = ctypes.cast(length, ctypes.POINTER(ctypes.c_size_t)).contents size = size_p.value block = f.read(size) size_p.value = len(block) buff_p = ctypes.cast(buff, ctypes.POINTER(ctypes.c_char_p)).contents buff_p.value = block return RS_DONE job = _librsync.rs_patch_begin(read_cb, None) try: _execute(job, d, o) finally: _librsync.rs_job_free(job) return o
<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_integer_tolerance(epsilon, v_max, min_tol): """Find appropriate integer tolerance for gap-filling problems."""
int_tol = min(epsilon / (10 * v_max), 0.1) min_tol = max(1e-10, min_tol) if int_tol < min_tol: eps_lower = min_tol * 10 * v_max logger.warning( 'When the maximum flux is {}, it is recommended that' ' epsilon > {} to avoid numerical issues with this' ' solver. Results may be incorrect with' ' the current settings!'.format(v_max, eps_lower)) return min_tol return int_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 gapfind(model, solver, epsilon=0.001, v_max=1000, implicit_sinks=True): """Identify compounds in the model that cannot be produced. Yields all compounds that cannot be produced. This method assumes implicit sinks for all compounds in the model so the only factor that influences whether a compound can be produced is the presence of the compounds needed to produce it. Epsilon indicates the threshold amount of reaction flux for the products to be considered non-blocked. V_max indicates the maximum flux. This method is implemented as a MILP-program. Therefore it may not be efficient for larger models. Args: model: :class:`MetabolicModel` containing core reactions and reactions that can be added for gap-filling. solver: MILP solver instance. epsilon: Threshold amount of a compound produced for it to not be considered blocked. v_max: Maximum flux. implicit_sinks: Whether implicit sinks for all compounds are included when gap-filling (traditional GapFill uses implicit sinks). """
prob = solver.create_problem() # Set integrality tolerance such that w constraints are correct min_tol = prob.integrality_tolerance.min int_tol = _find_integer_tolerance(epsilon, v_max, min_tol) if int_tol < prob.integrality_tolerance.value: prob.integrality_tolerance.value = int_tol # Define flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[reaction_id] v.define([reaction_id], lower=lower, upper=upper) # Define constraints on production of metabolites in reaction w = prob.namespace(types=lp.VariableType.Binary) binary_cons_lhs = {compound: 0 for compound in model.compounds} for spec, value in iteritems(model.matrix): compound, reaction_id = spec if value != 0: w.define([spec]) w_var = w(spec) lower, upper = (float(x) for x in model.limits[reaction_id]) if value > 0: dv = v(reaction_id) else: dv = -v(reaction_id) lower, upper = -upper, -lower prob.add_linear_constraints( dv <= upper * w_var, dv >= epsilon + (lower - epsilon) * (1 - w_var)) binary_cons_lhs[compound] += w_var xp = prob.namespace(model.compounds, types=lp.VariableType.Binary) objective = xp.sum(model.compounds) prob.set_objective(objective) for compound, lhs in iteritems(binary_cons_lhs): prob.add_linear_constraints(lhs >= xp(compound)) # Define mass balance constraints massbalance_lhs = {compound: 0 for compound in model.compounds} for spec, value in iteritems(model.matrix): compound, reaction_id = spec massbalance_lhs[compound] += v(reaction_id) * value for compound, lhs in iteritems(massbalance_lhs): if implicit_sinks: # The constraint is merely >0 meaning that we have implicit sinks # for all compounds. prob.add_linear_constraints(lhs >= 0) else: prob.add_linear_constraints(lhs == 0) # Solve try: result = prob.solve(lp.ObjectiveSense.Maximize) except lp.SolverError as e: raise_from(GapFillError('Failed to solve gapfill: {}'.format(e), e)) for compound in model.compounds: if result.get_value(xp(compound)) < 0.5: yield compound
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def float_constructor(loader, node): """Construct Decimal from YAML float encoding."""
s = loader.construct_scalar(node) if s == '.inf': return Decimal('Infinity') elif s == '-.inf': return -Decimal('Infinity') elif s == '.nan': return Decimal('NaN') return Decimal(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml_load(stream): """Load YAML file using safe loader."""
# Surprisingly, the CSafeLoader does not seem to be used by default. # Check whether the CSafeLoader is available and provide a log message # if it is not available. global _HAS_YAML_LIBRARY if _HAS_YAML_LIBRARY is None: _HAS_YAML_LIBRARY = hasattr(yaml, 'CSafeLoader') if not _HAS_YAML_LIBRARY: logger.warning('libyaml was not found! Please install libyaml to' ' speed up loading the model files.') if _HAS_YAML_LIBRARY: loader = yaml.CSafeLoader(stream) else: loader = yaml.SafeLoader(stream) loader.add_constructor('tag:yaml.org,2002:float', float_constructor) return loader.get_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 _check_id(entity, entity_type): """Check whether the ID is valid. First check if the ID is missing, and then check if it is a qualified string type, finally check if the string is empty. For all checks, it would raise a ParseError with the corresponding message. Args: entity: a string type object to be checked. entity_type: a string that shows the type of entities to check, usually `Compound` or 'Reaction'. """
if entity is None: raise ParseError('{} ID missing'.format(entity_type)) elif not isinstance(entity, string_types): msg = '{} ID must be a string, id was {}.'.format(entity_type, entity) if isinstance(entity, bool): msg += (' You may have accidentally used an ID value that YAML' ' interprets as a boolean, such as "yes", "no", "on",' ' "off", "true" or "false". To use this ID, you have to' ' quote it with single or double quotes') raise ParseError(msg) elif len(entity) == 0: raise ParseError('{} ID must not be empty'.format(entity_type))
<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_compound(compound_def, context=None): """Parse a structured compound definition as obtained from a YAML file Returns a CompoundEntry."""
compound_id = compound_def.get('id') _check_id(compound_id, 'Compound') mark = FileMark(context, None, None) return CompoundEntry(compound_def, mark)
<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_compound_list(path, compounds): """Parse a structured list of compounds as obtained from a YAML file Yields CompoundEntries. Path can be given as a string or a context. """
context = FilePathContext(path) for compound_def in compounds: if 'include' in compound_def: file_format = compound_def.get('format') include_context = context.resolve(compound_def['include']) for compound in parse_compound_file(include_context, file_format): yield compound else: yield parse_compound(compound_def, 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 parse_compound_table_file(path, f): """Parse a tab-separated file containing compound IDs and properties The compound properties are parsed according to the header which specifies which property is contained in each column. """
context = FilePathContext(path) for i, row in enumerate(csv.DictReader(f, delimiter=str('\t'))): if 'id' not in row or row['id'].strip() == '': raise ParseError('Expected `id` column in table') props = {key: value for key, value in iteritems(row) if value != ''} if 'charge' in props: props['charge'] = int(props['charge']) mark = FileMark(context, i + 2, None) yield CompoundEntry(props, mark)
<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_compound_file(path, format): """Open and parse reaction file based on file extension or given format Path can be given as a string or a context. """
context = FilePathContext(path) # YAML files do not need to explicitly specify format format = resolve_format(format, context.filepath) if format == 'yaml': logger.debug('Parsing compound file {} as YAML'.format( context.filepath)) with context.open('r') as f: for compound in parse_compound_yaml_file(context, f): yield compound elif format == 'modelseed': logger.debug('Parsing compound file {} as ModelSEED TSV'.format( context.filepath)) with context.open('r') as f: for compound in modelseed.parse_compound_file(f, context): yield compound elif format == 'tsv': logger.debug('Parsing compound file {} as TSV'.format( context.filepath)) with context.open('r') as f: for compound in parse_compound_table_file(context, f): yield compound else: raise ParseError('Unable to detect format of compound file {}'.format( context.filepath))
<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_reaction_equation_string(equation, default_compartment): """Parse a string representation of a reaction equation. Converts undefined compartments to the default compartment. """
def _translate_compartments(reaction, compartment): """Translate compound with missing compartments. These compounds will have the specified compartment in the output. """ left = (((c.in_compartment(compartment), v) if c.compartment is None else (c, v)) for c, v in reaction.left) right = (((c.in_compartment(compartment), v) if c.compartment is None else (c, v)) for c, v in reaction.right) return Reaction(reaction.direction, left, right) eq = _REACTION_PARSER.parse(equation).normalized() return _translate_compartments(eq, default_compartment)
<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_reaction_equation(equation_def, default_compartment): """Parse a structured reaction equation as obtained from a YAML file Returns a Reaction. """
def parse_compound_list(l, compartment): """Parse a list of reactants or metabolites""" for compound_def in l: compound_id = compound_def.get('id') _check_id(compound_id, 'Compound') value = compound_def.get('value') if value is None: raise ParseError('Missing value for compound {}'.format( compound_id)) compound_compartment = compound_def.get('compartment') if compound_compartment is None: compound_compartment = compartment compound = Compound(compound_id, compartment=compound_compartment) yield compound, value if isinstance(equation_def, string_types): return parse_reaction_equation_string( equation_def, default_compartment) else: compartment = equation_def.get('compartment', default_compartment) reversible = bool(equation_def.get('reversible', True)) left = equation_def.get('left', []) right = equation_def.get('right', []) if len(left) == 0 and len(right) == 0: raise ParseError('Reaction values are missing') return Reaction(Direction.Both if reversible else Direction.Forward, parse_compound_list(left, compartment), parse_compound_list(right, compartment))
<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_reaction(reaction_def, default_compartment, context=None): """Parse a structured reaction definition as obtained from a YAML file Returns a ReactionEntry. """
reaction_id = reaction_def.get('id') _check_id(reaction_id, 'Reaction') reaction_props = dict(reaction_def) # Parse reaction equation if 'equation' in reaction_def: reaction_props['equation'] = parse_reaction_equation( reaction_def['equation'], default_compartment) mark = FileMark(context, None, None) return ReactionEntry(reaction_props, mark)
<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_reaction_list(path, reactions, default_compartment=None): """Parse a structured list of reactions as obtained from a YAML file Yields tuples of reaction ID and reaction object. Path can be given as a string or a context. """
context = FilePathContext(path) for reaction_def in reactions: if 'include' in reaction_def: include_context = context.resolve(reaction_def['include']) for reaction in parse_reaction_file( include_context, default_compartment): yield reaction else: yield parse_reaction(reaction_def, default_compartment, 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 parse_reaction_table_file(path, f, default_compartment): """Parse a tab-separated file containing reaction IDs and properties The reaction properties are parsed according to the header which specifies which property is contained in each column. """
context = FilePathContext(path) for lineno, row in enumerate(csv.DictReader(f, delimiter=str('\t'))): if 'id' not in row or row['id'].strip() == '': raise ParseError('Expected `id` column in table') props = {key: value for key, value in iteritems(row) if value != ''} if 'equation' in props: props['equation'] = parse_reaction_equation_string( props['equation'], default_compartment) mark = FileMark(context, lineno + 2, 0) yield ReactionEntry(props, mark)
<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_reaction_file(path, default_compartment=None): """Open and parse reaction file based on file extension Path can be given as a string or a context. """
context = FilePathContext(path) format = resolve_format(None, context.filepath) if format == 'tsv': logger.debug('Parsing reaction file {} as TSV'.format( context.filepath)) with context.open('r') as f: for reaction in parse_reaction_table_file( context, f, default_compartment): yield reaction elif format == 'yaml': logger.debug('Parsing reaction file {} as YAML'.format( context.filepath)) with context.open('r') as f: for reaction in parse_reaction_yaml_file( context, f, default_compartment): yield reaction else: raise ParseError('Unable to detect format of reaction file {}'.format( context.filepath))
<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_exchange(exchange_def, default_compartment): """Parse a structured exchange definition as obtained from a YAML file. Returns in iterator of compound, reaction, lower and upper bounds. """
default_compartment = exchange_def.get('compartment', default_compartment) for compound_def in exchange_def.get('compounds', []): compartment = compound_def.get('compartment', default_compartment) compound = Compound(compound_def['id'], compartment=compartment) reaction = compound_def.get('reaction') lower, upper = get_limits(compound_def) yield compound, reaction, lower, upper
<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_exchange_list(path, exchange, default_compartment): """Parse a structured exchange list as obtained from a YAML file. Yields tuples of compound, reaction ID, lower and upper flux bounds. Path can be given as a string or a context. """
context = FilePathContext(path) for exchange_def in exchange: if 'include' in exchange_def: include_context = context.resolve(exchange_def['include']) for exchange_compound in parse_exchange_file( include_context, default_compartment): yield exchange_compound else: for exchange_compound in parse_exchange( exchange_def, default_compartment): yield exchange_compound