code
stringlengths
1
18.2k
(degrees) Longitude of location, degrees, WGS84 altitude : array-like of floats (km) Altitude of location, height above surface, WGS84 datetimes : array-like of datetimes Time to calculate vectors max_steps : int Maximum number of steps allowed for field line tracing step_size : float Maximum step size (km) allowed whe...
geo_lat, geo_long, geo_alt = ecef_to_geocentric(ecef_x, ecef_y, ecef_z, ref_height=0.) # filter longitudes (could use pysat's function here) idx, = np.where(geo_long < 0) geo_long[idx] = geo_long[idx] + 360. # prepare output lists north_x = []; north_y = []; north_z = [] south_x = []; south_y = []; south_z = [] bn = []...
= trace_north[-1, :] trace_south = trace_south[-1, :] # magnetic field at spacecraft location, using geocentric inputs # to get magnetic field in geocentric output # recast from datetime to float, as required by IGRF12 code doy = (time - datetime.datetime(time.year,1,1)).days # number of days in year, works for leap ye...
np.array(bd) # calculate vector from satellite to northern/southern footpoints north_x = north_x - ecef_x north_y = north_y - ecef_y north_z = north_z - ecef_z north_x, north_y, north_z = normalize_vector(north_x, north_y, north_z) south_x = south_x - ecef_x south_y = south_y - ecef_y south_z = south_z - ecef_z south_x...
point zvx_south, zvy_south, zvz_south = cross_product(south_x, south_y, south_z, bx, by, bz) # normalize the vectors norm_foot = np.sqrt(zvx_foot ** 2 + zvy_foot ** 2 + zvz_foot ** 2) # calculate zonal vector zvx = zvx_foot / norm_foot zvy = zvy_foot / norm_foot zvz = zvz_foot / norm_foot # remove any field aligned com...
zvz, bx, by, bz, mx, my, mz
def step_until_intersect(pos, field_line, sign, time, direction=None, step_size_goal=5., field_step_size=None): """Starting at pos, method steps along magnetic unit vector direction towards the supplied field line trace. Determines the distance of closest approach to field line. Routine is used when calculting the mapp...
ECEF locations of field line trace, produced by the field_line_trace method. sign : int if 1, move along positive unit vector. Negwtive direction for -1. time : datetime or float Date to perform tracing on (year + day/365 + hours/24. + etc.) Accounts for leap year if datetime provided. direction : string ('meridional',...
trace. """ # work on a copy, probably not needed field_copy = field_line # set a high last minimum distance to ensure first loop does better than this last_min_dist = 2500000. # scalar is the distance along unit vector line that we are taking scalar = 0. # repeat boolean repeat=True # first run boolean first=True # fac...
user provided step_size_goal unit_steps = np.abs(scalar//step_size_goal) if unit_steps == 0: unit_steps = 1 # print (unit_steps, scalar/unit_steps) pos_step = step_along_mag_unit_vector(pos[0], pos[1], pos[2], time, direction=direction, num_steps=unit_steps, step_size=np.abs(scalar)/unit_steps, scalar=sign) # find clos...
number of elements we really need to check # field_copy = field_copy[min_idx-100:min_idx+100] # # difference with position # diff = field_copy - pos_step # diff_mag = np.sqrt((diff ** 2).sum(axis=1)) # # find closest one # min_idx = np.argmin(diff_mag) first = False # pull out distance of closest point min_dist = diff_...
pos[2], time, direction=direction, num_steps=unit_steps, step_size=np.abs(scalar)/unit_steps, scalar=sign) else: # undo increment to last total distance scalar = scalar - last_min_dist/(2*factor) # increase the divisor used to reduce the distance # actually stepped per increment factor = factor + 1. # try a new increme...
def step_along_mag_unit_vector(x, y, z, date, direction=None, num_steps=5., step_size=5., scalar=1): """ Move along 'lines' formed by following the magnetic unit vector directions. Moving along the field is effectively the same as a field line trace though extended movement along a field should use the specific field_l...
step_size = float Distance taken for each step (km) scalar : int Scalar modifier for step size distance. Input a -1 to move along negative unit vector direction. Returns ------- np.array [x, y, z] of ECEF location after taking num_steps along direction, each step_size long. """ # set parameters for the field line traci...
direction == 'zonal': ux, uy, uz = zvx, zvy, zvz elif direction == 'aligned': ux, uy, uz = bx, by, bz # take steps along direction x = x + step_size*ux[0]*scalar y = y + step_size*uy[0]*scalar z = z + step_size*uz[0]*scalar return np.array([x, y, z])
def apex_location_info(glats, glons, alts, dates): """Determine apex location for the field line passing through input point. Employs a two stage method. A broad step (100 km) field line trace spanning Northern/Southern footpoints is used to find the location with the largest geodetic (WGS84) height. A higher resolutio...
(km), Geodetic Latitude (degrees), Geodetic Longitude (degrees), Geodetic Altitude (km) """ # use input location and convert to ECEF ecef_xs, ecef_ys, ecef_zs = geodetic_to_ecef(glats, glons, alts) # prepare parameters for field line trace step_size = 100. max_steps = 1000 steps = np.arange(max_steps) # high resolution...
# determine location that is highest with respect to the geodetic Earth max_idx = np.argmax(talt) # repeat using a high resolution trace one big step size each # direction around identified max # recurse False ensures only max_steps are taken trace = full_field_line(trace[max_idx,:], date, 0., steps=fine_steps, step_si...
def closed_loop_edge_lengths_via_footpoint(glats, glons, alts, dates, direction, vector_direction, step_size=None, max_steps=None, edge_length=25., edge_steps=5): """ Forms closed loop integration along mag field, satrting at input points and goes through footpoint. At footpoint, steps along vector direction in both po...
dates : list-like of datetimes Date and time for determination of scalars direction : string 'north' or 'south' for tracing through northern or southern footpoint locations vector_direction : string 'meridional' or 'zonal' unit vector directions step_size : float (km) Step size (km) used for field line integration max_...
through input location is provided. The distances of closest approach for the positive step along vector direction, and the negative step are returned. """ if step_size is None: step_size = 100. if max_steps is None: max_steps = 1000 steps = np.arange(max_steps) if direction == 'south': direct = -1 elif direction == 'n...
meridional and zonal # directions and trace back from location of interest, step along # field line directions until we intersect or hit the distance of # closest approach to the return field line with the known # distances of footpoint steps, and the closet approach distance # we can determine the scalar mapping of on...
step_size=edge_length/edge_steps) # trace this back to other footpoint other_plus = field_line_trace(plus_step, double_date, -direct, 0., steps=steps, step_size=step_size, max_steps=max_steps) # take half step from first footpoint along - vector direction minus_step = step_along_mag_unit_vector(ftpnt[0], ftpnt[1], ftpn...
np.array(full_local_step), np.array(min_distance_plus), np.array(min_distance_minus)
def closed_loop_edge_lengths_via_equator(glats, glons, alts, dates, vector_direction, edge_length=25., edge_steps=5): """ Calculates the distance between apex locations mapping to the input location. Using the input location, the apex location is calculated. Also from the input location, a step along both the positive ...
is planned. Note ---- vector direction refers to the magnetic unit vector direction Parameters ---------- glats : list-like of floats (degrees) Geodetic (WGS84) latitude glons : list-like of floats (degrees) Geodetic (WGS84) longitude alts : list-like of floats (km) Geodetic (WGS84) altitude, height above surface dates...
(positive/negative) along unit vector Returns ------- np.array, ### np.array, np.array The change in field line apex locations. ## Pending ## The return edge length through input location is provided. ## Pending ## The distances of closest approach for the positive step along vector direction, and the negative step are...
apex_location_info( [glat], [glon], [alt], [date]) # apex in ecef (maps to input location) apex_root = np.array([apex_x[0], apex_y[0], apex_z[0]]) # take step from s/c along + vector direction # then get the apex location plus = step_along_mag_unit_vector(ecef_x, ecef_y, ecef_z, date, direction=vector_direction, num_st...
(plus_apex_z[0]-minus_apex_z[0])**2)) # # take an alternative path to calculation # # do field line trace around pos and neg apexes # # then do intersection with field line projection thing # # # do a short centered field line trace around plus apex location # other_trace = full_field_line(plus_apex_root, double_date, ...
determine where the intersection of apex field line # # in relation to the vector direction from the s/c field apex location. # minus_edge_length, _, mind_minus = step_until_intersect(apex_root, # other_trace, # -1, date, # direction=vector_direction, # field_step_size=1., # step_size_goal=edge_length/edge_steps) # ful...
def scalars_for_mapping_ion_drifts(glats, glons, alts, dates, step_size=None, max_steps=None, e_field_scaling_only=False): """ Calculates scalars for translating ion motions at position glat, glon, and alt, for date, to the footpoints of the field line as well as at the magnetic equator. All inputs are assumed to be 1D...
changes in magnitude of B. Note ion velocity related to E/B. Returns ------- dict array-like of scalars for translating ion drifts. Keys are, 'north_zonal_drifts_scalar', 'north_mer_drifts_scalar', and similarly for southern locations. 'equator_mer_drifts_scalar' and 'equator_zonal_drifts_scalar' cover the mappings to ...
north_mer_drifts_scalar, mind_plus, mind_minus = closed_loop_edge_lengths_via_footpoint(glats, glons, alts, dates, 'north', 'zonal', step_size=step_size, max_steps=max_steps, edge_length=25., edge_steps=5) # print ('Starting Southern') south_zon_drifts_scalar, mind_plus, mind_minus = closed_loop_edge_lengths_via_footpo...
figure out scaling for drifts based upon change in magnetic field # strength for ecef_x, ecef_y, ecef_z, glat, glon, alt, date in zip(ecef_xs, ecef_ys, ecef_zs, glats, glons, alts, dates): yr, doy = pysat.utils.getyrdoy(date) double_date = float(yr) + float(doy) / 366. # get location of apex for s/c field line apex_x, ...
need to include the magnetic field, drift = E/B tbn, tbe, tbd, b_sc = igrf.igrf12syn(0, double_date, 1, alt, np.deg2rad(90.-glat), np.deg2rad(glon)) # get mag field and scalar for northern footpoint tbn, tbe, tbd, b_nft = igrf.igrf12syn(0, double_date, 1, nft_alt, np.deg2rad(90.-nft_glat), np.deg2rad(nft_glon)) north_m...
north_zon_drifts_scalar out['south_zonal_drifts_scalar'] = south_zon_drifts_scalar out['north_mer_drifts_scalar'] = north_mer_drifts_scalar out['south_mer_drifts_scalar'] = south_mer_drifts_scalar out['equator_zonal_drifts_scalar'] = eq_zon_drifts_scalar out['equator_mer_drifts_scalar'] = eq_mer_drifts_scalar return ou...
def add_fabfile(): """ Copy the base fabfile.py to the current working directory. """ fabfile_src = os.path.join(PACKAGE_ROOT, 'fabfile.py') fabfile_dest = os.path.join(os.getcwd(), 'fabfile_deployer.py') if os.path.exists(fabfile_dest): print "`fabfile.py` exists in the current directory. " \ "Please remove or rename ...
def delete(self): """Remove the item from the infoblox server. :rtype: bool :raises: AssertionError :raises: ValueError :raises: infoblox.exceptions.ProtocolError """ if not self._ref: raise ValueError('Object has no reference id for deletion') if 'save' not in self._supports: raise AssertionError('Can not save this ob...
def fetch(self): """Attempt to fetch the object from the Infoblox device. If successful the object will be updated and the method will return True. :rtype: bool :raises: infoblox.exceptions.ProtocolError """ LOGGER.debug('Fetching %s, %s', self._path, self._search_values) response = self._session.get(self._path, self._...
def save(self): """Update the infoblox with new values for the specified object, or add the values if it's a new object all together. :raises: AssertionError :raises: infoblox.exceptions.ProtocolError """ if 'save' not in self._supports: raise AssertionError('Can not save this object type') values = {} for key in [key ...
%r', response.status_code, response.content) if 200 <= response.status_code <= 201: self.fetch() return True else: try: error = response.json() raise exceptions.ProtocolError(error['text']) except ValueError: raise exceptions.ProtocolError(response.content)
def _assign(self, values): """Assign the values passed as either a dict or list to the object if the key for each value matches an available attribute on the object. :param dict values: The values to assign """ LOGGER.debug('Assigning values: %r', values) if not values: return keys = self.keys() if not self._ref: keys....
def _build_search_values(self, kwargs): """Build the search criteria dictionary. It will first try and build the values from already set attributes on the object, falling back to the passed in kwargs. :param dict kwargs: Values to build the dict from :rtype: dict """ criteria = {} for key in self._search_by: if getattr...
def add_ipv4addr(self, ipv4addr): """Add an IPv4 address to the host. :param str ipv4addr: The IP address to add. :raises: ValueError """ for addr in self.ipv4addrs: if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or (isinstance(addr, HostIPv4) and addr.ipv4addr == ipv4addr)): raise ValueError('Already ex...
def remove_ipv4addr(self, ipv4addr): """Remove an IPv4 address from the host. :param str ipv4addr: The IP address to remove """ for addr in self.ipv4addrs: if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or (isinstance(addr, HostIPv4) and addr.ipv4addr == ipv4addr)): self.ipv4addrs.remove(addr) break
def add_ipv6addr(self, ipv6addr): """Add an IPv6 address to the host. :param str ipv6addr: The IP address to add. :raises: ValueError """ for addr in self.ipv6addrs: if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or (isinstance(addr, HostIPv4) and addr.ipv6addr == ipv6addr)): raise ValueError('Already ex...
def remove_ipv6addr(self, ipv6addr): """Remove an IPv6 address from the host. :param str ipv6addr: The IP address to remove """ for addr in self.ipv6addrs: if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or (isinstance(addr, HostIPv4) and addr.ipv6addr == ipv6addr)): self.ipv6addrs.remove(addr) break
def _sqla_postgresql(self, uri, version=None, isolation_level="READ COMMITTED"): ''' expected uri form: postgresql+psycopg2://%s:%s@%s:%s/%s' % ( username, password, host, port, db) ''' isolation_level = isolation_level or "READ COMMITTED" kwargs = dict(isolation_level=isolation_level) # FIXME: version of postgresql < ...
def autoschema(self, objects, **kwargs): ''' wrapper around utils.autoschema function ''' return autoschema(objects=objects, exclude_keys=self.RESTRICTED_KEYS, **kwargs)
def count(self, query=None, date=None, table=None): ''' Run a query on the given cube and return only the count of resulting matches. :param query: The query in pql :param date: date (metrique date range) that should be queried If date==None then the most recent versions of the objects will be queried. :param collectio...
def deptree(self, field, oids, date=None, level=None, table=None): ''' Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build depedency tree for :param date: date (me...
checked} checked |= fringe loop_k += 1 return sorted(checked)
def get_last_field(self, field, table=None): '''Shortcut for querying to get the last field value for a given owner, cube. :param field: field name to query ''' field = field if is_array(field) else [field] table = self.get_table(table, except_=False) if table is None: last = None else: is_defined(field, 'field must be...
def index(self, fields, name=None, table=None, **kwargs): ''' Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param collection: cube name :param owner: username of cube owner ''' tab...
def index_list(self): ''' List all cube indexes :param collection: cube name :param owner: username of cube owner ''' logger.info('Listing indexes') _ix = {} _i = self.inspector for tbl in _i.get_table_names(): _ix.setdefault(tbl, []) for ix in _i.get_indexes(tbl): _ix[tbl].append(ix) return _ix
def ls(self, startswith=None): ''' List all cubes available to the calling client. :param startswith: string to use in a simple "startswith" query filter :returns list: sorted list of cube names ''' logger.info('Listing cubes starting with "%s")' % startswith) startswith = unicode(startswith or '') tables = sorted(name...
def share(self, with_user, roles=None, table=None): ''' Give cube access rights to another user Not, this method is NOT supported by SQLite3! ''' table = self.get_table(table) is_true(table is not None, 'invalid table: %s' % table) with_user = validate_username(with_user) roles = roles or ['SELECT'] roles = validate_ro...
def muscle_seqs(seqs, add_seq_names=False, out_filename=None, input_handler=None, params={}, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None): """Muscle align list of sequences. seqs: a list of sequences as strings or objects, you must set add_seq_names=True or sequences in a multiline string...
lines, unless add_seq_names is true (in which case treat as list of seqs). If it's a string, test whether it has newlines. If it doesn't have newlines, assume it's a filename. If it does have newlines, it can't be a filename, so assume it's a multiline string containing sequences. If you want to skip the detection and ...
muscle_app(seqs)
def cluster_seqs(seqs, neighbor_join=False, params={}, add_seq_names=True, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None, max_chars=1000000, max_hours=1.0, constructor=PhyloNode, clean_up=True ): """Muscle cluster list of sequences. seqs: either file name or list of sequence objects or list...
muscle_res.cleanUp() return tree
def aln_tree_seqs(seqs, input_handler=None, tree_type='neighborjoining', params={}, add_seq_names=True, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None, max_hours=5.0, constructor=PhyloNode, clean_up=True ): """Muscle align sequences and report tree from iteration2. Unlike cluster_seqs, retur...
clean_up: muscle_res.cleanUp() return tree, aln
def align_unaligned_seqs(seqs, moltype=DNA, params=None): """Returns an Alignment object from seqs. seqs: SequenceCollection object, or data that can be used to build one. moltype: a MolType object. DNA, RNA, or PROTEIN. params: dict of parameters to pass in to the Muscle app controller. Result will be an Alignment obj...
new_alignment[int_keys[k]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) #Clean up res.cleanUp() del(seq_collection,int_map,int_keys,app,res,alignment,params) return new_alignment
def align_and_build_tree(seqs, moltype, best_tree=False, params=None): """Returns an alignment and a tree from Sequences object seqs. seqs: a cogent.core.alignment.SequenceCollection object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: if True (default:False), uses a slo...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None): """Returns a tree from Alignment object aln. aln: a cogent.core.alignment.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: unsupported params: dict of parameters to pass in to th...
def add_seqs_to_alignment(seqs, aln, params=None): """Returns an Alignment object from seqs and existing Alignment. seqs: a cogent.core.alignment.SequenceCollection object, or data that can be used to build one. aln: a cogent.core.alignment.Alignment object, or data that can be used to build one params: dict of paramet...
= open(seqs_filename,'w') seqs_out.write(seqs_int_map.toFasta()) seqs_out.close() #save aln to tmp file aln_filename = get_tmp_filename() aln_out = open(aln_filename, 'w') aln_out.write(aln_int_map.toFasta()) aln_out.close() #Create Muscle app and get results app = Muscle(InputHandler='_input_as_multifile', params=para...
def align_two_alignments(aln1, aln2, params=None): """Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. params: dict of parameters to pass in to the Muscle app controller. """ if not params: params = {} #create Sequence...
open(aln2_filename, 'w') aln2_out.write(aln2_int_map.toFasta()) aln2_out.close() #Create Muscle app and get results app = Muscle(InputHandler='_input_as_multifile', params=params, WorkingDir=tempfile.gettempdir()) res = app((aln1_filename, aln2_filename)) #Get alignment as dict out of results alignment = dict(parse_fas...
def _input_as_multifile(self, data): """For use with the -profile option This input handler expects data to be a tuple containing two filenames. Index 0 will be set to -in1 and index 1 to -in2 """ if data: try: filename1, filename2 = data except: raise ValueError, "Expected two filenames" self.Parameters['-in'].off() s...
def get_example(): """Make an example for training and testing. Outputs a tuple (label, features) where label is +1 if capital letters are the majority, and -1 otherwise; and features is a list of letters. """ features = random.sample(string.ascii_letters, NUM_SAMPLES) num_capitalized = len([ letter for letter in featu...
def static_url(redis, path): """Gets the static path for a file""" file_hash = get_cache_buster(redis, path) return "%s/%s?v=%s" % (oz.settings["static_host"], path, file_hash)
def get_cache_buster(redis, path): """Gets the cache buster value for a given file path""" return escape.to_unicode(redis.hget("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path))
def set_cache_buster(redis, path, hash): """Sets the cache buster value for a given file path""" redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash)
def get_bucket(s3_bucket=None, validate=False): """Gets a bucket from specified settings""" global S3Connection if S3Connection != None: settings = oz.settings s3_bucket = s3_bucket or settings["s3_bucket"] opts = {} if settings["s3_host"]: opts["host"] = settings["s3_host"] if settings["aws_access_key"] and settings["...
def get_file(path, s3_bucket=None): """Gets a file""" bucket_name = s3_bucket or oz.settings["s3_bucket"] if bucket_name: bucket = get_bucket(bucket_name) key = bucket.get_key(path) if not key: key = bucket.new_key(path) return S3File(key) else: return LocalFile(oz.settings["static_path"], path)
def copy(self, new_path, replace=False): """ Uses shutil to copy a file over """ new_full_path = os.path.join(self.static_path, new_path) if replace or not os.path.exists(new_full_path): shutil.copy2(self.full_path, new_full_path) return True return False
def copy(self, new_path, replace=False): """Uses boto to copy the file to the new path instead of uploading another file to the new key""" if replace or not get_file(new_path).exists(): self.key.copy(self.key.bucket, new_path) return True return False
def create_connection(): """Sets up a redis configuration""" global _cached_connection settings = oz.settings if settings["redis_cache_connections"] and _cached_connection != None: return _cached_connection else: conn = redis.StrictRedis( host=settings["redis_host"], port=settings["redis_port"], db=settings["redis_db"]...
def clusters_from_blast_uc_file(uc_lines, otu_id_field=1): """ Parses out hit/miss sequences from usearch blast uc file All lines should be 'H'it or 'N'o hit. Returns a dict of OTU ids: sequence labels of the hits, and a list of all sequence labels that miss. uc_lines = open file object of uc file otu_id_field: uc fiel...
label to dictionary, or create key try: otus[curr_otu_id].append(curr_seq_label) except KeyError: otus[curr_otu_id] = [curr_seq_label] return otus, unassigned_seqs
def usearch_fasta_sort_from_filepath( fasta_filepath, output_filepath=None, log_name="sortlen.log", HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None): """Generates sorted fasta file via usearch --mergesort. fasta_filepath: filepath to input fasta file output_filepath: filepath...
def usearch_sort_by_abundance( fasta_filepath, output_filepath=None, sizein=True, sizeout=True, minsize=0, log_name="abundance_sort.log", usersort=False, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None): """ Sorts fasta file by abundance fasta_filepath = input fasta file, gen...
sizeout: app.Parameters['--sizeout'].on() data = {'--sortsize': fasta_filepath, '--output': output_filepath } if not remove_usearch_logs: data['--log'] = log_filepath # Can have no data following this filter step, which will raise an # application error, try to catch it here to raise meaningful message. try: app_result...
def usearch_cluster_error_correction( fasta_filepath, output_filepath=None, output_uc_filepath=None, percent_id_err=0.97, sizein=True, sizeout=True, w=64, slots=16769023, maxrejects=64, log_name="usearch_cluster_err_corrected.log", usersort=False, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=Fals...
controller save_intermediate_files: Preserve all intermediate files created. """ if not output_filepath: _, output_filepath = mkstemp(prefix='usearch_cluster_err_corrected', suffix='.fasta') log_filepath = join(working_dir, log_name) params = {'--sizein': sizein, '--sizeout': sizeout, '--id': percent_id_err, '--w': w, ...
def usearch_chimera_filter_de_novo( fasta_filepath, output_chimera_filepath=None, output_non_chimera_filepath=None, abundance_skew=2.0, log_name="uchime_de_novo_chimera_filtering.log", usersort=False, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, working_dir=None): """ Chimera filter de nov...
log_filepath app_result = app(data) if not save_intermediate_files: remove_files([output_chimera_filepath]) return app_result, output_non_chimera_filepath
def usearch_cluster_seqs_ref( fasta_filepath, output_filepath=None, percent_id=0.97, sizein=True, sizeout=True, w=64, slots=16769023, maxrejects=64, log_name="usearch_cluster_seqs.log", usersort=True, HALT_EXEC=False, save_intermediate_files=False, remove_usearch_logs=False, suppress_new_clusters=False, refseqs_fp=None...
--w 16 or --w 32. maxrejects = Max rejected targets, 0=ignore, default 32. log_name = string specifying output log name usersort = Enable if input fasta not sorted by length purposefully, lest usearch will raise an error. In post chimera checked sequences, the seqs are sorted by abundance, so this should be set to True...
app = Usearch(params, WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) if usersort: app.Parameters['--usersort'].on() if rev: app.Parameters['--rev'].on() data = {'--query': fasta_filepath, '--uc': uc_filepath, '--db': refseqs_fp } if not remove_usearch_logs: data['--log'] = log_filepath app_result = app(data) files_to_rem...
'clustered_seqs_reference_failures.fasta'), percent_id=percent_id, sizein=sizein, sizeout=sizeout, w=w, slots=slots, maxrejects=maxrejects, save_intermediate_files=save_intermediate_files, remove_usearch_logs=remove_usearch_logs, working_dir=working_dir) output_filepath = concatenate_fastas(output_fna_clustered, output...
def concatenate_fastas(output_fna_clustered, output_fna_failures, output_concat_filepath): """ Concatenates two input fastas, writes to output_concat_filepath output_fna_clustered: fasta of successful ref clusters output_fna_failures: de novo fasta of cluster failures output_concat_filepath: path to write combined fast...
def enumerate_otus(fasta_filepath, output_filepath=None, label_prefix="", label_suffix="", retain_label_as_comment=False, count_start=0): """ Writes unique, sequential count to OTUs fasta_filepath = input fasta filepath output_filepath = output fasta filepath label_prefix = string to place before enumeration label_suff...
def get_fasta_from_uc_file(fasta_filepath, uc_filepath, hit_type="H", output_fna_filepath=None, label_prefix="", output_dir=None): """ writes fasta of sequences from uc file of type hit_type fasta_filepath: Filepath of original query fasta file uc_filepath: Filepath of .uc file created by usearch post error filtering h...
"w") for label, seq in parse_fasta(open(fasta_filepath, "U")): if label in labels_to_keep: if hit_type == "H": out_fna.write(">" + labels_hits[label] + "\n%s\n" % seq) if hit_type == "N": out_fna.write(">" + label + "\n%s\n" % seq) return output_fna_filepath, labels_hits
def get_retained_chimeras(output_fp_de_novo_nonchimeras, output_fp_ref_nonchimeras, output_combined_fp, chimeras_retention='union'): """ Gets union or intersection of two supplied fasta files output_fp_de_novo_nonchimeras: filepath of nonchimeras from de novo usearch detection. output_fp_ref_nonchimeras: filepath of no...