code
stringlengths
1
18.2k
def main(args=None): """Main""" vs = [(v-100)*0.001 for v in range(200)] for f in ['IM.channel.nml','Kd.channel.nml']: nml_doc = pynml.read_neuroml2_file(f) for ct in nml_doc.ComponentType: ys = [] for v in vs: req_variables = {'v':'%sV'%v,'vShift':'10mV'} vals = pynml.evaluate_component(ct,req_variables=req_variables)...
plt.show()
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to generate a LEMS " "file to analyse the behaviour of channels in " "NeuroML 2")) parser.add_argument('channelFiles', type=str, nargs='+', metavar='<NeuroML 2 Channel file>', help="Name o...
type=int, metavar='<max v>', default=DEFAULTS['maxV'], help="Maximum voltage to test (integer, mV), default: %smV"%DEFAULTS['maxV']) parser.add_argument('-temperature', type=float, metavar='<temperature>', default=DEFAULTS['temperature'], help="Temperature (float, celsius), default: %sdegC"%DEFAULTS['temperature']) par...
voltage>', default=DEFAULTS['clampBaseVoltage'], help="Clamp base (starting/finishing) voltage in mV, default: %smV"%DEFAULTS['clampBaseVoltage']) parser.add_argument('-stepTargetVoltage', type=float, metavar='<step target voltage>', default=DEFAULTS['stepTargetVoltage'], help=("Voltage in mV through which to step volt...
(float, " "concentration in mM), default: %smM"%DEFAULTS['caConc'])) parser.add_argument('-datSuffix', type=str, metavar='<dat suffix>', default=DEFAULTS['datSuffix'], help="String to add to dat file names (before .dat)") parser.add_argument('-norun', action='store_true', default=DEFAULTS['norun'], help=("If used, just...
action='store_true', default=DEFAULTS['md'], help=("Generate a (GitHub flavoured) Markdown page featuring the plots for the " "channel")) parser.add_argument('-ivCurve', action='store_true', default=DEFAULTS['ivCurve'], help=("Save currents through voltage clamp at each " "level & plot current vs voltage for ion " "cha...
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs): """A single IV curve""" grid = plt_kwargs.pop('grid',True) same_fig = plt_kwargs.pop('same_fig',False) if not len(plt_args): plt_args = ('ko-',) if 'label' not in plt_kwargs: plt_kwargs['label'] = 'Current' if not same_fig: make_iv_curve_fig(a, grid=grid) if typ...
def root(context): """Multipart AJAX request example. See: http://test.getify.com/mpAjax/description.html """ response = context.response parts = [] for i in range(12): for j in range(12): parts.append(executor.submit(mul, i, j)) def stream(parts, timeout=None): try: for future in as_completed(parts, timeout): mime, re...
parts: future.cancel() response.content_length = None response.app_iter = stream(parts, 0.2) return response
def render_template_with_args_in_file(file, template_file_name, **kwargs): """ Get a file and render the content of the template_file_name with kwargs in a file :param file: A File Stream to write :param template_file_name: path to route with template name :param **kwargs: Args to be rendered in template """ template_f...
def create_or_open(file_name, initial_template_file_name, args): """ Creates a file or open the file with file_name name :param file_name: String with a filename :param initial_template_file_name: String with path to initial template :param args: from console to determine path to save the files """ file = None if not o...
file_name ), 'w+', encoding='UTF-8' ) print("Creating {}".format(file_name)) if initial_template_file_name: render_template_with_args_in_file(file, initial_template_file_name, **{}) else: # If file exists, just load the file file = codecs.open( os.path.join( args['django_application_folder'], file_name ), 'a+', encodin...
def generic_insert_module(module_name, args, **kwargs): """ In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template """ file = create_or_open( '{}.py'.format(module_name), os...
def sanity_check(args): """ Verify if the work folder is a django app. A valid django app always must have a models.py file :return: None """ if not os.path.isfile( os.path.join( args['django_application_folder'], 'models.py' ) ): print("django_application_folder is not a Django application folder") sys.exit(1)
def generic_insert_with_folder(folder_name, file_name, template_name, args): """ In general if we need to put a file on a folder, we use this method """ # First we make sure views are a package instead a file if not os.path.isdir( os.path.join( args['django_application_folder'], folder_name ) ): os.mkdir(os.path.join(a...
Load content from template render_template_with_args_in_file( view_file, os.path.join( BASE_TEMPLATES_DIR, template_name ), model_name=args['model_name'], model_prefix=args['model_prefix'], model_name_lower=args['model_name'].lower(), application_name=args['django_application_folder'].split("/")[-1] ) view_file.close()
def serve(application, host='127.0.0.1', port=8080, threads=4, **kw): """The recommended development HTTP server. Note that this server performs additional buffering and will not honour chunked encoding breaks. """ # Bind and start the server; this is a blocking process. serve_(application, host=host, port=int(port), t...
def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt.title("Simulation voltage vs time") plt.legend() plt.xlabel("Time [ms]") plt.ylabel("Voltage [mV]")...
def mul(self, a: int = None, b: int = None) -> 'json': """Multiply two values together and return the result via JSON. Python 3 function annotations are used to ensure that the arguments are integers. This requires the functionality of `web.ext.annotation:AnnotationExtension`. There are several ways to execute this met...
we can't descend past a callable method so the remaining path elements are used as positional arguments, whereas the others rely on keyword argument assignment from a form-encoded request body or query string arguments. (Security note: any data in the request body takes presidence over query string arguments!) You can ...
curl -d a=27 -d b=42 http://localhost:8080/mul # HTTP POST """ if not a or not b: return dict(message="Pass arguments a and b to multiply them together!") return dict(answer=a * b)
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1): '''Returns the colored string to print on the terminal. This function detects the terminal type and if it is supported and the output is not going to a pipe or a file, then it will return the colored string, otherwise it will return the string with...
strings must be encoded in advance. rgb = Rgb color for the text; for example 0xFF0000 is red. ansi = Ansi for the text bg = Rgb color for the background ansi_bg= Ansi color for the background fd = The file descriptor that will be used by print, by default is the stdout ''' #Reinitializes if fd used is different if col...
colorize.init = False colorize.fd = fd #Checks if it is on a terminal, and if the terminal is recognized if not colorize.init: colorize.init = True colorize.is_term = isatty(fd) if 'TERM' in environ: if environ['TERM'].startswith('xterm'): colorize.cmap = XTermColorMap() elif environ['TERM'] == 'vt100': colorize.cmap =...
def mutate(self, context, handler, args, kw): """Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be freely modified, though invalid arguments to the handler will fail. """ def cast(arg, val): if arg not in annotations: return cast = annotations[key] try: val = cast(val)...
'{}'".format(arg) e.args = tuple(parts) raise return val annotations = getattr(handler.__func__ if hasattr(handler, '__func__') else handler, '__annotations__', None) if not annotations: return argspec = getfullargspec(handler) arglist = list(argspec.args) if ismethod(handler): del arglist[0] for i, value in enumerate(...
def transform(self, context, handler, result): """Transform the value returned by the controller endpoint. This extension transforms returned values if the endpoint has a return type annotation. """ handler = handler.__func__ if hasattr(handler, '__func__') else handler annotation = getattr(handler, '__annotations__', ...
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!")) parser.add_argument('prefix', type=str, metavar='<prefix>', help="Prefix for optimisation run") parser...
values for parameters") parser.add_argument('minConstraints', type=str, metavar='<min_constraints>', help="Min values for parameters") parser.add_argument('targetData', type=str, metavar='<targetData>', help="List of name/value pairs for properties extracted from data to judge fitness against") parser.add_argument('wei...
metavar='<maxEvaluations>', default=DEFAULTS['maxEvaluations'], help="Maximum evaluations") parser.add_argument('-numSelected', type=int, metavar='<numSelected>', default=DEFAULTS['numSelected'], help="Number selected") parser.add_argument('-numOffspring', type=int, metavar='<numOffspring>', default=DEFAULTS['numOffspr...
known values of the target parameters") parser.add_argument('-nogui', action='store_true', default=DEFAULTS['nogui'], help="Should GUI elements be supressed?") parser.add_argument('-showPlotAlready', action='store_true', default=DEFAULTS['showPlotAlready'], help="Should generated plots be suppressed until show() called...
as optimisation progresses?") return parser.parse_args()
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with cell activity (e.g. as generated from a neuroConstruct simulation)") parser.add_argument('prefix', type=str, metavar='<network pre...
help='Max voltage for colour scale in mV') parser.add_argument('-minV', type=float, metavar='<minV>', default=-90.0, help='Min voltage for colour scale in mV') parser.add_argument('-startTime', type=float, metavar='<startTime>', default=0, help='Time in ms at which to start overlaying the simulation activity') parser.a...
type=int, metavar='<frames>', default=100, help='Number of frames') parser.add_argument('-name', type=str, metavar='<Movie name>', default='output', help='Movie name') return parser.parse_args()
def serve(application, host='127.0.0.1', port=8080, **options): """Tornado's HTTPServer. This is a high quality asynchronous server with many options. For details, please visit: http://www.tornadoweb.org/en/stable/httpserver.html#http-server """ # Wrap our our WSGI application (potentially stack) in a Tornado adapter. ...
def parse_arguments(): """Parse command line arguments""" import argparse parser = argparse.ArgumentParser( description=('pyNeuroML v%s: Python utilities for NeuroML2' % __version__ + "\n libNeuroML v%s"%(neuroml.__version__) + "\n jNeuroML v%s"%JNEUROML_VERSION), usage=('pynml [-h|--help] [<shared options>] ' '<one of...
shared_options.add_argument( '-java_max_memory', metavar='MAX', default=DEFAULTS['default_java_max_memory'], help=('Java memory for jNeuroML, e.g. 400M, 2G (used in\n' '-Xmx argument to java)') ) shared_options.add_argument( '-nogui', action='store_true', default=DEFAULTS['nogui'], help=('Suppress GUI,\n' 'i.e. show no...
help=('(Via jNeuroML) Load a LEMS file, and convert\n' 'simulation settings (duration, dt, what to save)\n' 'to SED-ML format') ) mut_exc_opts.add_argument( '-neuron', nargs=argparse.REMAINDER, help=('(Via jNeuroML) Load a LEMS file, and convert it to\n' 'NEURON format.\n' 'The full format of the \'-neuron\' option is:...
and quit\n' ' -run\n' ' compile NMODL files and run the main NEURON\n' ' hoc file (Linux only currently)\n' ' -outputdir <dir>\n' ' generate NEURON files in directory <dir>\n' ' <LEMS file>\n' ' the LEMS file to use') ) mut_exc_opts.add_argument( '-svg', action='store_true', help=('(Via jNeuroML) Convert NeuroML2 file ...
NeuroML2 file (network & cells)\n' 'to PNG format view of 3D structure') ) mut_exc_opts.add_argument( '-dlems', action='store_true', help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to dLEMS format, a distilled form of LEMS in JSON') ) mut_exc_opts.add_argument( '-vertex', action='store_true', help=('(Via jNe...
'to XPPAUT format') ) mut_exc_opts.add_argument( '-dnsim', action='store_true', help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to DNsim format') ) mut_exc_opts.add_argument( '-brian', action='store_true', help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to Brian format') ) mut_exc_opts.add_argumen...
'to MATLAB format') ) mut_exc_opts.add_argument( '-cvode', action='store_true', help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to C format using CVODE package') ) mut_exc_opts.add_argument( '-nineml', action='store_true', help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to NineML format') ) mut_ex...
Load a SBML file, and convert it\n' 'toLEMS format using values for duration & dt\n' 'in ms (ignoring SBML units)') ) mut_exc_opts.add_argument( '-sbml-import-units', metavar=('<SBML file>', 'duration', 'dt'), nargs=3, help=('(Via jNeuroML) Load a SBML file, and convert it\n' 'to LEMS format using values for duration &...
'<LEMS file>'), nargs=2, help=('(Via jNeuroML) Load a LEMS file, and convert it\n' 'to VHDL format') ) mut_exc_opts.add_argument( '-graph', metavar=('level'), nargs=1, help=('Load a NeuroML file, and convert it to a graph using\n' 'GraphViz. Detail is set by level (1, 2, etc.)') ) mut_exc_opts.add_argument( '-matrix', ...
etc.)') ) mut_exc_opts.add_argument( '-validate', action='store_true', help=('(Via jNeuroML) Validate NeuroML2 file(s) against the\n' 'latest Schema') ) mut_exc_opts.add_argument( '-validatev1', action='store_true', help=('(Via jNeuroML) Validate NeuroML file(s) against the\n' 'v1.8.1 Schema') ) return parser.parse_arg...
def quick_summary(nml2_doc): ''' Or better just use nml2_doc.summary(show_includes=False) ''' info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id membs = inspect.getmembers(nml2_doc) for memb in membs: if isinstance(memb[1], list) and len(memb[1])>0 \ and not memb[0].endswith('_'): info+=' %s:\n ['%memb[0] for en...
info+=" %s (%s),"%(entry, extra) info+=']\n' return info
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'], prefix="Output: ", env=None): """Execute a command in specific working directory""" if os.name == 'nt': directory = os.path.normpath(directory) print_comment("Executing: (%s) in directory: %s" % (command, directory), verbose) if env is not None: prin...
= return_string.decode("utf-8") # For Python 3 print_comment('Command completed. Output: \n %s%s' % \ (prefix,return_string.replace('\n','\n '+prefix)), verbose) return return_string except AttributeError: # For python 2.6... print_comment_v('Assuming Python 2.6...') return_string = subprocess.Popen(command, cwd=direct...
def evaluate_component(comp_type, req_variables={}, parameter_values={}): print_comment('Evaluating %s with req:%s; params:%s'%(comp_type.name,req_variables,parameter_values)) exec_str = '' return_vals = {} from math import exp for p in parameter_values: exec_str+='%s = %s\n'%(p, get_value_in_si(parameter_values[p])) f...
case in cdv.Case: if case.condition: cond = case.condition.replace('.neq.','!=').replace('.eq.','==').replace('.gt.','<').replace('.lt.','<') exec_str+='if ( %s ): %s = %s \n'%(cond, cdv.name, case.value) else: exec_str+='else: %s = %s \n'%(cdv.name, case.value) exec_str+='\n' exec_str+='return_vals["%s"] = %s\n'%(cdv....
def after(self, context, exc=None): """Executed after dispatch has returned and the response populated, prior to anything being sent to the client.""" duration = context._duration = round((time.time() - context._start_time) * 1000) # Convert to ms. delta = unicode(duration) # Default response augmentation. if self.head...
))
def _process_flat_kwargs(source, kwargs): """Apply a flat namespace transformation to recreate (in some respects) a rich structure. This applies several transformations, which may be nested: `foo` (singular): define a simple value named `foo` `foo` (repeated): define a simple value for placement in an array named `foo`...
simple value to place in the `foo` array at the identified index By nesting, you may define deeper, more complex structures: `foo.bar`: define a value for the named element `bar` of the `foo` dictionary `foo.<id>.bar`: define a `bar` dictionary element on the array element marked by that ID References to `<id>` represe...
not a dictionary. Exact indexes might not be able to be preserved if there are voids; Python lists are not sparse. No validation of values is performed. """ ordered_arrays = [] # Process arguments one at a time and apply them to the kwargs passed in. for name, value in source.items(): container = kwargs if '.' in name:...
for target, following in zip(parts[:-1], parts[1:]): if following.isnumeric(): # Prepare any use of numeric IDs. container.setdefault(target, [{}]) if container[target] not in ordered_arrays: ordered_arrays.append(container[target]) container = container[target][0] continue container = container.setdefault(target, {}) ...
if not isinstance(container[name], list): container[name] = [container[name]] container[name].append(value) continue container[name] = value for container in ordered_arrays: elements = container[0] del container[:] container.extend(value for name, value in sorted(elements.items()))
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A file for converting NeuroML v2 files into POVRay files for 3D rendering") parser.add_argument('neuroml_file', type=str, metavar='<NeuroML file>', help='NeuroML (version 2 beta 3+) file to be converted to PovRay for...
default=_WHITE, help='Colour of background, e.g. <0,0,0,0.55>') parser.add_argument('-movie', action='store_true', default=False, help="If this is specified, generate a ini file for generating a sequence of frames for a movie of the 3D structure") parser.add_argument('-inputs', action='store_true', default=False, help=...
the network with lines") parser.add_argument('-conn_points', action='store_true', default=False, help="If this is specified, show the end points of the connections present in the network") parser.add_argument('-v', action='store_true', default=False, help="Verbose output") parser.add_argument('-frames', type=int, metav...
(0 is centre, 1 is top)') parser.add_argument('-posz', type=float, metavar='<position offset z>', default=0, help='Offset position in z dir (0 is centre, 1 is top)') parser.add_argument('-viewx', type=float, metavar='<view offset x>', default=0, help='Offset viewing point in x dir (0 is centre, 1 is top)') parser.add_a...
default=0, help='Offset viewing point in z dir (0 is centre, 1 is top)') parser.add_argument('-scalex', type=float, metavar='<scale position x>', default=1, help='Scale position from network in x dir') parser.add_argument('-scaley', type=float, metavar='<scale position y>', default=1.5, help='Scale position from networ...
visualisations)') parser.add_argument('-plane', action='store_true', default=False, help="If this is specified, add a 2D plane below cell/network") parser.add_argument('-segids', action='store_true', default=False, help="Show segment ids") return parser.parse_args()
def _configure(self, config): """Prepare the incoming configuration and ensure certain expected values are present. For example, this ensures BaseExtension is included in the extension list, and populates the logging config. """ config = config or dict() # We really need this to be there. if 'extensions' not in config:...
the BaseExtension is present since request/response objects are handy. config['extensions'].insert(0, BaseExtension()) if not any(isinstance(ext, arguments.ArgumentExtension) for ext in config['extensions']): # Prepare a default set of argument mutators. config['extensions'].extend([ arguments.ValidateArgumentsExtensio...
need to test Python's own logging mechanism. level = config.get('logging', {}).get('level', None) if level: # pragma: no cover logging.basicConfig(level=getattr(logging, level.upper())) elif 'logging' in config: # pragma: no cover logging.config.dictConfig(config['logging']) return config
def serve(self, service='auto', **options): # pragma: no cover """Initiate a web server service to serve this application. You can always use the Application instance as a bare WSGI application, of course. This method is provided as a convienence. Pass in the name of the service you wish to use, and any additional conf...
`port` options, some also allow you to specify an on-disk `socket`. By default all web servers will listen to `127.0.0.1` (loopback only) on port 8080. """ service = load(service, 'web.server') # We don't bother with a full registry for these one-time lookups. try: service(self, **options) except KeyboardInterrupt: # W...
pass # Notify extensions that the service has returned and we are exiting. for ext in self.__context.extension.signal.stop: ext(self.__context)
def application(self, environ, start_response): """Process a single WSGI request/response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware, the `__call__` attribute of the Application instance will either become this, or become the outermost middleware calla...
various intermediary steps in the processing of a request and response. """ context = environ['wc.context'] = self.RequestContext(environ=environ) signals = context.extension.signal # Announce the start of a request cycle. This executes `prepare` and `before` callbacks in the correct order. for ext in signals.pre: ext(...
# Process the endpoint. except Exception as e: log.exception("Caught exception attempting to execute the endpoint.") result = HTTPInternalServerError(str(e) if __debug__ else "Please see the logs.") if 'debugger' in context.extension.feature: context.response = result for ext in signals.after: ext(context) # Allow sign...
if __debug__: log.debug("Result prepared, identifying view handler.", extra=dict( request = id(context), result = safe_name(type(result)) )) # Identify a view capable of handling this result. for view in context.view(result): if view(context, result): break else: # We've run off the bottom of the list of possible views...
= id(context), view = repr(view), )) for ext in signals.after: ext(context) def capture_done(response): for chunk in response: yield chunk for ext in signals.done: ext(context) # This is really long due to the fact we don't want to capture the response too early. # We need anything up to this point to be able to simply...
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit_length_ref, self.hit_length_qry...
def qry_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence''' return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end))
def ref_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence''' return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
def on_same_strand(self): '''Returns true iff the direction of the alignment is the same in the reference and the query''' return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end)
def is_self_hit(self): '''Returns true iff the alignment is of a sequence to itself: names and all coordinates are the same and 100 percent identity''' return self.ref_name == self.qry_name \ and self.ref_start == self.qry_start \ and self.ref_end == self.qry_end \ and self.percent_identity == 100
def reverse_query(self): '''Changes the coordinates as if the query sequence has been reverse complemented''' self.qry_start = self.qry_length - self.qry_start - 1 self.qry_end = self.qry_length - self.qry_end - 1
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
def to_msp_crunch(self): '''Returns the alignment as a line in MSPcrunch format. The columns are space-separated and are: 1. score 2. percent identity 3. match start in the query sequence 4. match end in the query sequence 5. query sequence name 6. subject sequence start 7. subject sequence end 8. subject sequence name...
for a match. aln_score = int(self.percent_identity * 0.005 * (self.hit_length_ref + self.hit_length_qry)) return ' '.join(str(x) for x in [ aln_score, '{0:.2f}'.format(self.percent_identity), self.qry_start + 1, self.qry_end + 1, self.qry_name, self.ref_start + 1, self.ref_end + 1, self.ref_name ])
def qry_coords_from_ref_coord(self, ref_coord, variant_list): '''Given a reference position and a list of variants ([variant.Variant]), works out the position in the query sequence, accounting for indels. Returns a tuple: (position, True|False), where second element is whether or not the ref_coord lies in an indel. If ...
get query coord in qry_coords_from_ref_coord because given ref_coord ' + str(ref_coord) + ' does not lie in nucmer alignment:\n' + str(self)) indel_variant_indexes = [] for i in range(len(variant_list)): if variant_list[i].var_type not in {variant.INS, variant.DEL}: continue if not self.intersects_variant(variant_list[...
variant_list[i].var_type == variant.INS: distance += len(variant_list[i].qry_base) else: assert variant_list[i].var_type == variant.DEL distance -= len(variant_list[i].ref_base) if self.on_same_strand(): return min(self.qry_start, self.qry_end) + distance, False else: return max(self.qry_start, self.qry_end) - distance...
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breaklen) if self.diagdiff is not None and not self.use_promer: command += ' -D ' + ...
+= ' -g ' + str(self.maxgap) if self.maxmatch: command += ' --maxmatch' if self.mincluster is not None: command += ' -c ' + str(self.mincluster) if not self.simplify and not self.use_promer: command += ' --nosimplify' return command + ' ' + ref + ' ' + qry
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) return command + ' ' + infile + ' > ' + outfile
def _show_coords_command(self, infile, outfile): '''Construct show-coords command''' command = 'show-coords -dTlro' if not self.coords_header: command += ' -H' return command + ' ' + infile + ' > ' + outfile
def _write_script(self, script_name, ref, qry, outfile): '''Write commands into a bash script''' f = pyfastaq.utils.open_file_write(script_name) print(self._nucmer_command(ref, qry, 'p'), file=f) print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f) print(self._show_coords_command('p.delta.filter', out...
def run(self): ''' Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory ''' qry = os.path.abspath(self.qry) ref = os.path.abspath(self.ref) outfile = os.path.abspath(self.outfile) tmpdir = tempfile.mkdtemp(prefix='tmp.run_nucmer.', dir=os.getcwd()...
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_variant = Variant...
\ or self.qry_name != new_variant.qry_name \ or self.ref_name != new_variant.ref_name \ or self.reverse != new_variant.reverse: return False if self.var_type == INS \ and self.ref_start == new_variant.ref_start \ and self.qry_end + 1 == new_variant.qry_start: self.qry_base += new_variant.qry_base self.qry_end += 1 retu...
True return False
def reader(fname): '''Helper function to open the results file (coords file) and create alignment objects with the values in it''' f = pyfastaq.utils.open_file_read(fname) for line in f: if line.startswith('[') or (not '\t' in line): continue yield alignment.Alignment(line) pyfastaq.utils.close(f)
def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None): '''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely). ACT ignores sequence names in the crunch file, and just looks at the numbers. To make a compatible file, the coords all must be shifted appropriately, which ca...