code
stringlengths
1
18.2k
def _get_result_paths(self, data): """ Set the result paths """ result = {} # OTU map (mandatory output) result['OtuMap'] = ResultPath(Path=self.Parameters['-O'].Value, IsWritten=True) # SumaClust will not produce any output file if the # input file was empty, so we create an empty # output file if not isfile(result['O...
def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False): """ Generates clusters and fasta file of dereplicated subsequences Parameters ---------- fast...
the input fasta file, (search for the pattern "[>;]size=integer[;]" in sequence headers) sizeout : boolean, optional add abundance annotations to the output fasta file (add the pattern ";size=integer;" to sequence headers) log_name : string, optional specifies log filename HALT_EXEC : boolean, optional used for debuggi...
sizein: app.Parameters['--sizein'].on() if sizeout: app.Parameters['--sizeout'].on() if (strand == "both" or strand == "plus"): app.Parameters['--strand'].on(strand) else: raise ValueError("Option --strand accepts only 'both'" "or 'plus' values") app.Parameters['--derep_fulllength'].on(fasta_filepath) app.Parameters['-...
def vsearch_sort_by_abundance( fasta_filepath, output_filepath, working_dir=None, minsize=None, maxsize=None, log_name="abundance_sort.log", HALT_EXEC=False): """ Fasta entries are sorted by decreasing abundance (Fasta entries are assumed to be dereplicated with the pattern "[>;]size=integer[;]" present in the read lab...
filepath to log file """ # set working dir to same directory as the output # file (if not provided) if not working_dir: working_dir = dirname(output_filepath) app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC) log_filepath = join(working_dir, log_name) if minsize: app.Parameters['--minsize'].on(minsize) if maxs...
def vsearch_chimera_filter_de_novo( fasta_filepath, working_dir, output_chimeras=True, output_nonchimeras=True, output_alns=False, output_tabular=False, log_name="vsearch_uchime_de_novo_chimera_filtering.log", HALT_EXEC=False): """ Detect chimeras present in the fasta-formatted filename, without external references (i....
fields (see Vsearch user manual) HALT_EXEC : boolean, optional used for debugging app controller Return ------ output_chimera_filepath : string filepath to chimeric fasta sequences output_non_chimera_filepath : string filepath to nonchimeric fasta sequences output_alns_filepath : string filepath to chimeric sequences a...
app.Parameters['--uchimeout'].on(output_tabular_filepath) log_filepath = join(working_dir, log_name) app.Parameters['--uchime_denovo'].on(fasta_filepath) app.Parameters['--log'].on(log_filepath) app_result = app() return output_chimera_filepath, output_non_chimera_filepath,\ output_alns_filepath, output_tabular_filepat...
def _get_result_paths(self, data): """ Set the result paths """ result = {} result['Output'] = ResultPath( Path=self.Parameters['--output'].Value, IsWritten=self.Parameters['--output'].isOn()) result['ClusterFile'] = ResultPath( Path=self.Parameters['--uc'].Value, IsWritten=self.Parameters['--uc'].isOn()) # uchime 3-wa...
def extract(filename, doy, latitude, longitude, depth): """ For now only the nearest value For now only for one position, not an array of positions longitude 0-360 """ assert np.size(doy) == 1 assert np.size(latitude) == 1 assert np.size(longitude) == 1 assert np.size(depth) == 1 assert (longitude >= 0) & (longitude <=...
def cars_profile(filename, doy, latitude, longitude, depth): """ For now only the nearest value For now only for one position, not an array of positions longitude 0-360 """ assert np.size(doy) == 1 assert np.size(latitude) == 1 assert np.size(longitude) == 1 #assert np.size(depth) == 1 assert (longitude >= 0) & (longit...
+ \ nc['sa_sin'][:, I, J] * np.sin(2*t) value = value output = {'depth': np.asanyarray(depth)} from scipy.interpolate import griddata output['value'] = griddata(nc['depth'][Z], value[Z], depth) for v in ['std_dev']: output[v] = griddata(nc['depth'][Z], nc[v][Z, I, J], depth) return output
def crop(self, doy, depth, lat, lon, var): """ Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accepts 0 to 360 and -1...
zn = idx['zn'] tn = idx['tn'] subset = {} for v in var: if v == 'mn': mn = [] for d in doy: t = 2 * np.pi * d/366 # Naive solution # FIXME: This is not an efficient solution. value = self.ncs[0]['mean'][:, yn, xn] value[:64] += self.ncs[0]['an_cos'][:, yn, xn] * np.cos(t) + \ self.ncs[0]['an_sin'][:, yn, xn] * np.sin(t...
def interpolate(self, doy, depth, lat, lon, var): """ Interpolate each var on the coordinates requested """ subset, dims = self.crop(doy, depth, lat, lon, var) if np.all([d in dims['time'] for d in doy]) & \ np.all([z in dims['depth'] for z in depth]) & \ np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['l...
return output # The output coordinates shall be created only once. points_out = [] for doyn in doy: for depthn in depth: for latn in lat: for lonn in lon: points_out.append([doyn, depthn, latn, lonn]) points_out = np.array(points_out) output = {} for v in var: output[v] = ma.masked_all( (doy.size, depth.size, lat.size,...
ind])) ) # Remap the interpolated value back into a 4D array idx = np.isfinite(values_out) for [t, z, y, x], out in zip(points_out[idx], values_out[idx]): output[v][t==doy, z==depth, y==lat, x==lon] = out output[v] = ma.fix_invalid(output[v]) return output
def mark_as_read(self, room_name): """ message_ids return an array with unread message ids ['131313231', '323131'] """ api_meth = self.set_user_items_url(room_name) message_ids = self.unread_items(room_name).get('chat') if message_ids: return self.post(api_meth, data={'chat': message_ids}) else: raise GitterItemsError(...
def init(cls, site): """ put site settings in the header of the script """ bash_header = "" for k,v in site.items(): bash_header += "%s=%s" % (k.upper(), v) bash_header += '\n' site['bash_header'] = bash_header # TODO: execute before_deploy # P.S. running init_before seems like impossible, because the file hasn't been ...
def _create_configs(cls, site): """ This is going to generate the following configuration: * wsgi.py * <provider>.yml * settings_<provider>.py """ provider = cls.name cls._render_config('wsgi.py', 'wsgi.py', site) # create yaml file yaml_template_name = os.path.join(provider, cls.provider_yml_name) cls._render_config(c...
def _render_config(cls, dest, template_name, template_args): """ Renders and writes a template_name to a dest given some template_args. This is for platform-specific configurations """ template_args = template_args.copy() # Substitute values here pyversion = template_args['pyversion'] template_args['pyversion'] = cls.P...
def gen_subcommand_help(self): ''' Generates s ''' commands = sorted(self.subcommands.items(), key=lambda i: i[0]) return '\n'.join( '%s %s' % ( subcommand.ljust(15), textwrap.shorten(description, width=61), ) for subcommand, (description, action, opts) in commands )
def parse_args_to_action_args(self, argv=None): ''' Parses args and returns an action and the args that were parsed ''' args = self.parse_args(argv) action = self.subcommands[args.subcommand][1] return action, args
def register_subparser(self, action, name, description='', arguments={}): ''' Registers a new subcommand with a given function action. If the function action is synchronous ''' action = coerce_to_synchronous(action) opts = [] for flags, kwargs in arguments.items(): if isinstance(flags, str): flags = tuple([flags]) opts...
def subcommand(self, description='', arguments={}): ''' Decorator for quickly adding subcommands to the omnic CLI ''' def decorator(func): self.register_subparser( func, func.__name__.replace('_', '-'), description=description, arguments=arguments, ) return func return decorator
def print(self, *args, **kwargs): ''' Utility function that behaves identically to 'print' except it only prints if verbose ''' if self._last_args and self._last_args.verbose: print(*args, **kwargs)
def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines): """ Process results of uclust search and align """ alignments = get_next_two_fasta_records(fasta_pairs_lines) for hit in get_next_record_type(uc_lines, 'H'): matching_strand = hit[4] if matching_strand == '-': strand_id = '-' target_rev_match = True ...
uc files do not match." + " Got target %s but expected %s." % (fasta_target_id, uc_target_id + strand_id)) if target_rev_match: query_id = uc_query_id + ' RC' aligned_query = DNA.rc(aligned_query) target_id = uc_target_id aligned_target = DNA.rc(aligned_target) else: query_id = uc_query_id aligned_query = aligned_query...
def clusters_from_uc_file(uc_lines, error_on_multiple_hits=True): """ Given an open .uc file, return lists (clusters, failures, new_seeds) uc_lines: open .uc file, or similar object -- this is the output generated by uclust's -uc parameter error_on_multiple_hits: if True (default), when a single query hits to multiple ...
all_hits = set() # the types of hit lines we're interested in here # are hit (H), seed (S), library seed (L) and no hit (N) hit_types = {}.fromkeys(list('HSNL')) for record in get_next_record_type(uc_lines, hit_types): hit_type = record[0] # sequence identifiers from the fasta header lines only # (no comment data) are ...
a query to cluster to multiple seeds.") else: # add the hit to its existing cluster (either library # or new cluster) clusters[target_cluster].append(query_id) all_hits.add(query_id) elif hit_type == 'S': # a new seed was identified -- create a cluster with this # sequence as the first instance if query_id in clusters:...
hit # line will be specified separately. note we need to handle these # lines separately from the H lines to detect overlapping seq ids # between the reference and the input fasta files if query_id in clusters: raise UclustParseError("A seq id was provided as a seed, but that seq id already " "represents a cluster. Are...
the full clusters dict, I think, to support # useful identifiers in reference database clustering # return clusters.values(), failures, seeds return clusters, failures, seeds
def uclust_fasta_sort_from_filepath( fasta_filepath, output_filepath=None, tmp_dir=gettempdir(), HALT_EXEC=False): """Generates sorted fasta file via uclust --mergesort.""" if not output_filepath: _, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_fasta_sort', suffix='.fasta') app = Uclust(params={'--tmpdir': tmp...
def uclust_search_and_align_from_fasta_filepath( query_fasta_filepath, subject_fasta_filepath, percent_ID=0.75, enable_rev_strand_matching=True, max_accepts=8, max_rejects=32, tmp_dir=gettempdir(), HALT_EXEC=False): """ query seqs against subject fasta using uclust, return global pw alignment of best match """ # Explan...
= Uclust(params, TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC) # apply uclust _, alignment_filepath = mkstemp(dir=tmp_dir, prefix='uclust_alignments', suffix='.fasta') _, uc_filepath = mkstemp(dir=tmp_dir, prefix='uclust_results', suffix='.uc') input_data = {'--input': query_fasta_filepath, '--fastapairs': alignment_filepath, '...
def uclust_cluster_from_sorted_fasta_filepath( fasta_filepath, uc_save_filepath=None, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, enable_rev_strand_matching=False, subject_fasta_filepath=None, suppress_new_clusters=False, stable_sort=False,...
def get_clusters_from_fasta_filepath( fasta_filepath, original_fasta_path, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, output_dir=None, enable_rev_strand_matching=False, subject_fasta_filepath=None, suppress_new_clusters=False, return_clust...
function The percent_ID parameter specifies the percent identity for a clusters, i.e., if 99% were the parameter, all sequences that were 99% identical would be grouped as a cluster. """ # Create readable intermediate filenames if they are to be kept fasta_output_filepath = None uc_output_filepath = None cd_hit_filepat...
Generate uclust cluster file (.uc format) uclust_cluster = uclust_cluster_from_sorted_fasta_filepath( sorted_fasta_filepath, uc_save_filepath, percent_ID=percent_ID, max_accepts=max_accepts, max_rejects=max_rejects, stepwords=stepwords, word_length=word_length, optimal=optimal, exact=exact, suppress_sort=suppress_sort,...
def _input_as_parameters(self, data): """ Set the input path (a fasta filepath) """ # The list of values which can be passed on a per-run basis allowed_values = ['--input', '--uc', '--fastapairs', '--uc2clstr', '--output', '--mergesort'] unsupported_parameters = set(data.keys()) - set(allowed_values) if unsupported_par...
def _get_result_paths(self, data): """ Set the result paths """ result = {} result['Output'] = ResultPath( Path=self.Parameters['--output'].Value, IsWritten=self.Parameters['--output'].isOn()) result['ClusterFile'] = ResultPath( Path=self.Parameters['--uc'].Value, IsWritten=self.Parameters['--uc'].isOn()) result['Pairw...
def format_error(status=None, title=None, detail=None, code=None): '''Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Applic...
def return_an_error(*args): '''List of errors Put all errors into a list of errors ref: http://jsonapi.org/format/#errors Args: *args: A tuple contain errors Returns: A dictionary contains a list of errors ''' list_errors = [] list_errors.extend(list(args)) errors = { 'errors': list_errors } return errors
def forwards(self, orm): "Write your forwards methods here." for doc in orm['document_library.Document'].objects.all(): for title in doc.documenttitle_set.all(): title.is_published = doc.is_published title.save()
def _activity_import_doc(self, time_doc, activities): ''' Import activities for a single document into timeline. ''' batch_updates = [time_doc] # We want to consider only activities that happend before time_doc # do not move this, because time_doc._start changes # time_doc['_start'] is a timestamp, whereas act[0] is a ...
if last_doc['_end'] == when: new_doc = deepcopy(last_doc) last_doc = batch_updates.pop() else: new_doc = deepcopy(last_doc) new_doc['_start'] = when new_doc['_end'] = when last_doc['_start'] = when last_val = last_doc[field] new_val, inconsistent = self._activity_backwards(new_doc[field], removed, added) new_doc[field]...
to be epoch float... creation_ts = dt2ts(last_doc[creation_field]) if creation_ts < last_doc['_start']: last_doc['_start'] = creation_ts elif len(batch_updates) == 1: # we have only one version, that we did not change return [] else: pass # leave as-is except Exception as e: logger.error('Error updating creation time; ...
def get_changed_oids(self, last_update=None): ''' Returns a list of object ids of those objects that have changed since `mtime`. This method expects that the changed objects can be determined based on the `delta_mtime` property of the cube which specifies the field name that carries the time of the last change. This me...
not (mtime_columns and last_update): return [] mtime_columns = str2list(mtime_columns) where = [] for _column in mtime_columns: _sql = "%s >= %s" % (_column, last_update) where.append(_sql) return self.sql_get_oids(where)
def fieldmap(self): ''' Dictionary of field_id: field_name, as defined in self.fields property ''' if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap: fieldmap = self._sql_fieldmap else: fieldmap = defaultdict(str) fields = copy(self.fields) for field, opts in fields.iteritems(): field_id = opts.get('what') if fi...
def get_objects(self, force=None, last_update=None, flush=False): ''' Extract routine for SQL based cubes. :param force: for querying for all objects (True) or only those passed in as list :param last_update: manual override for 'changed since date' ''' return self._run_object_import(force=force, last_update=last_updat...
def get_new_oids(self): ''' Returns a list of unique oids that have not been extracted yet. Essentially, a diff of distinct oids in the source database compared to cube. ''' table = self.lconfig.get('table') _oid = self.lconfig.get('_oid') if is_array(_oid): _oid = _oid[0] # get the db column, not the field alias last_...
def get_full_history(self, force=None, last_update=None, flush=False): ''' Fields change depending on when you run activity_import, such as "last_updated" type fields which don't have activity being tracked, which means we'll always end up with different hash values, so we need to always remove all existing object stat...
def sql_get_oids(self, where=None): ''' Query source database for a distinct list of oids. ''' table = self.lconfig.get('table') db = self.lconfig.get('db_schema_name') or self.lconfig.get('db') _oid = self.lconfig.get('_oid') if is_array(_oid): _oid = _oid[0] # get the db column, not the field alias sql = 'SELECT DIST...
def get_objects(self, flush=False, autosnap=True, **kwargs): ''' Main API method for sub-classed cubes to override for the generation of the objects which are to (potentially) be added to the cube (assuming no duplicates) ''' logger.debug('Running get_objects(flush=%s, autosnap=%s, %s)' % ( flush, autosnap, kwargs)) if...
def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs): '''wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of the cube :param copy_config: apply config...
def insert_sequences_into_tree(aln, moltype, params={}, write_log=True): """Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object params: dict of parameters to pass in to the RAxML app controller. The result will be an ...
new_tree=build_tree_from_json_using_params(pplacer_result['json'].name, \ output_dir=params['--out-dir'], \ params=guppy_params) pplacer_result.cleanUp() return new_tree
def getTmpFilename(self, tmp_dir="/tmp",prefix='tmp',suffix='.fasta',\ include_class_id=False,result_constructor=FilePath): """ Define Tmp filename to contain .fasta suffix, since pplacer requires the suffix to be .fasta """ return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir, prefix=prefix, suffix=suffix, includ...
def _get_result_paths(self,data): """ Define the output filepaths """ output_dir = self.Parameters['--out-dir'].Value result = {} result['json'] = ResultPath(Path=join(output_dir, splitext(split(self._input_filename)[-1])[0] + \ '.jplace')) return result
def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10., ref_height=120.): """Adds unit vectors expressing the ion drift coordinate system organized by the geomagnetic field. Unit vectors are expressed in ECEF coordinates. Parameters ---------- inst : pysat.Instrument Instrument object that...
drifts in ecef coordinates zvx, zvy, zvz, bx, by, bz, mx, my, mz = calculate_mag_drift_unit_vectors_ecef(inst['latitude'], inst['longitude'], inst['altitude'], inst.data.index, steps=steps, max_steps=max_steps, step_size=step_size, ref_height=ref_height) inst['unit_zon_ecef_x'] = zvx inst['unit_zon_ecef_y'] = zvy inst[...
' 'the orthogonal system.'), 'axis': 'Zonal unit vector along ECEF-x', 'value_min': -1., 'value_max': 1., } inst.meta['unit_zon_ecef_y'] = {'long_name': 'Zonal unit vector along ECEF-y', 'desc': 'Zonal unit vector along ECEF-y', 'label': 'Zonal unit vector along ECEF-y', 'notes': ('Unit vector expressed using Earth Cen...
ECEF-z', 'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. ' 'Vector system is calcluated by field-line tracing along IGRF values ' 'down to reference altitudes of 120 km in both the Northern and Southern ' 'hemispheres. These two points, along with the satellite position, are ' 'used to d...
Northern and Southern ' 'hemispheres. These two points, along with the satellite position, are ' 'used to define the magnetic meridian. Vector math from here generates ' 'the orthogonal system.'), 'axis': 'Field-aligned unit vector along ECEF-x', 'value_min': -1., 'value_max': 1., } inst.meta['unit_fa_ecef_y'] = {'long...
along ECEF-y', 'value_min': -1., 'value_max': 1., } inst.meta['unit_fa_ecef_z'] = {'long_name': 'Field-aligned unit vector along ECEF-z', 'desc': 'Field-aligned unit vector along ECEF-z', 'label': 'Field-aligned unit vector along ECEF-z', 'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '...
Earth Fixed (ECEF) frame. ' 'Vector system is calcluated by field-line tracing along IGRF values ' 'down to reference altitudes of 120 km in both the Northern and Southern ' 'hemispheres. These two points, along with the satellite position, are ' 'used to define the magnetic meridian. Vector math from here generates ' ...
along with the satellite position, are ' 'used to define the magnetic meridian. Vector math from here generates ' 'the orthogonal system.'), 'axis': 'Meridional unit vector along ECEF-y', 'value_min': -1., 'value_max': 1., } inst.meta['unit_mer_ecef_z'] = {'long_name': 'Meridional unit vector along ECEF-z', 'desc': 'Me...
def add_mag_drift_unit_vectors(inst, max_steps=40000, step_size=10.): """Add unit vectors expressing the ion drift coordinate system organized by the geomagnetic field. Unit vectors are expressed in S/C coordinates. Interally, routine calls add_mag_drift_unit_vectors_ecef. See function for input parameter description. ...
in the S/C basis. """ # vectors are returned in geo/ecef coordinate system add_mag_drift_unit_vectors_ecef(inst, max_steps=max_steps, step_size=step_size) # convert them to S/C using transformation supplied by OA inst['unit_zon_x'], inst['unit_zon_y'], inst['unit_zon_z'] = project_ecef_vector_onto_basis(inst['unit_zon_...
RAM, ' 'z - towards nadir, y - completes the system, generally southward. ' 'Calculated using the corresponding unit vector in ECEF and the orientation ' 'of the IVM also expressed in ECEF (sc_*hat_*).'), 'scale': 'linear', 'units': '', 'value_min':-1., 'value_max':1} inst.meta['unit_zon_y'] = {'long_name':'Zonal direc...
'linear', 'units': '', 'value_min':-1., 'value_max':1} inst.meta['unit_zon_z'] = {'long_name':'Zonal direction along IVM-z', 'desc': 'Unit vector for the zonal geomagnetic direction.', 'label': 'Zonal Unit Vector: IVM-Z component', 'axis': 'Zonal Unit Vector: IVM-Z component', 'notes': ('Positive towards the east. Zona...
('Positive along the field, generally northward. Unit vector is along the geomagnetic field. ' 'The unit vector is expressed in the IVM coordinate system, x - along RAM, ' 'z - towards nadir, y - completes the system, generally southward. ' 'Calculated using the corresponding unit vector in ECEF and the orientation ' '...
towards nadir, y - completes the system, generally southward. ' 'Calculated using the corresponding unit vector in ECEF and the orientation ' 'of the IVM also expressed in ECEF (sc_*hat_*).'), 'scale': 'linear', 'units': '', 'value_min':-1., 'value_max':1} inst.meta['unit_fa_z'] = {'long_name':'Field-aligned direction ...
'linear', 'units': '', 'value_min':-1., 'value_max':1} inst.meta['unit_mer_x'] = {'long_name':'Meridional direction along IVM-x', 'desc': 'Unit vector for the geomagnetic meridional direction.', 'label': 'Meridional Unit Vector: IVM-X component', 'axis': 'Meridional Unit Vector: IVM-X component', 'notes': ('Positive is...
IVM-Y component', 'axis': 'Meridional Unit Vector: IVM-Y component', 'notes': ('Positive is aligned with vertical at ' 'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field ' 'and in the plane of the meridian.' 'The unit vector is expressed in the IVM coordinate system, x - along RAM, ' 'z - towar...
the geomagnetic field ' 'and in the plane of the meridian.' 'The unit vector is expressed in the IVM coordinate system, x - along RAM, ' 'z - towards nadir, y - completes the system, generally southward. ' 'Calculated using the corresponding unit vector in ECEF and the orientation ' 'of the IVM also expressed in ECEF (...
def add_mag_drifts(inst): """Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*', wher...
the corresponding unit vectors expressed in ' 'the instrument frame. '), 'label': 'Zonal Ion Velocity', 'axis': 'Zonal Ion Velocity', 'desc': 'Zonal ion velocity', 'scale': 'Linear', 'value_min':-500., 'value_max':500.} inst['iv_fa'] = {'data':inst['unit_fa_x'] * inst['iv_x'] + inst['unit_fa_y'] * inst['iv_y'] + inst['...
', 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed in ' 'the instrument frame. '), 'label':'Meridional Ion Velocity', 'axis':'Meridional Ion Velocity', 'desc':'Meridional Ion Velocity', 'scale':'Linear', 'value_min':-500.,...
def add_footpoint_and_equatorial_drifts(inst, equ_mer_scalar='equ_mer_drifts_scalar', equ_zonal_scalar='equ_zon_drifts_scalar', north_mer_scalar='north_footpoint_mer_drifts_scalar', north_zon_scalar='north_footpoint_zon_drifts_scalar', south_mer_scalar='south_footpoint_mer_drifts_scalar', south_zon_scalar='south_footpo...
to identify northern footpoint scalar for zonal ion drift south_mer_scalar : string Label used to identify northern footpoint scalar for meridional ion drift south_zon_scalar : string Label used to identify southern footpoint scalar for zonal ion drift mer_drift : string Label used to identify meridional ion drifts wit...
at magnetic equator. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed in ' 'the instrument frame. Field-line mapping and ' 'the assumption of equi-potential field lines ' 'is used to translate the locally measured ion ' '...
to ' 'magnetic equator. Positive is generally eastward. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed in ' 'the instrument frame. Field-line mapping and ' 'the assumption of equi-potential field lines ' 'is used to tra...
and within meridional plane, scaled to ' 'southern footpoint. Positive is up at magnetic equator. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed in ' 'the instrument frame. Field-line mapping and ' 'the assumption of eq...
direction, perpendicular ' 'to field and the meridional plane, scaled to ' 'southern footpoint. Positive is generally eastward. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed in ' 'the instrument frame. Field-line mappi...
'notes':('Velocity along meridional direction, perpendicular ' 'to field and within meridional plane, scaled to ' 'northern footpoint. Positive is up at magnetic equator. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'with the corresponding unit vectors expressed i...
'units':'m/s', 'long_name':'Northern zonal ion velocity', 'notes':('Velocity along zonal direction, perpendicular ' 'to field and the meridional plane, scaled to ' 'northern footpoint. Positive is generally eastward. ' 'Velocity obtained using ion velocities relative ' 'to co-rotation in the instrument frame along ' 'w...
def chi_squared(*choices): """Calculates the chi squared""" term = lambda expected, observed: float((expected - observed) ** 2) / max(expected, 1) mean_success_rate = float(sum([c.rewards for c in choices])) / max(sum([c.plays for c in choices]), 1) mean_failure_rate = 1 - mean_success_rate return sum([ term(mean_succe...
def sync_from_spec(redis, schema): """ Takes an input experiment spec and creates/modifies/archives the existing experiments to match the spec. If there's an experiment in the spec that currently doesn't exist, it will be created along with the associated choices. If there's an experiment in the spec that currently exi...
get_experiments_dict() archived_experiments = get_experiments_dict(active=False) # Get the newly defined experiment names and the names of the experiments # already setup new_experiment_names = set(schema.keys()) active_experiment_names = set(active_experiments.keys()) # Find all the experiments that are in the schema ...
if unarchivable_experiment_names: active_experiments = get_experiments_dict() active_experiment_names = set(active_experiments.keys()) # Create the new experiments for new_experiment_name in new_experiment_names - active_experiment_names: print("- Creating experiment %s" % new_experiment_name) experiment = add_experime...
for removable_choice_name in old_choice_names - new_choice_names: print("- Removing choice %s from existing experiment %s" % (removable_choice_name, experiment_name)) experiment.remove_choice(removable_choice_name)
def add_experiment(redis, name): """Adds a new experiment""" if not ALLOWED_NAMES.match(name): raise ExperimentException(name, "Illegal name") if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name): raise ExperimentException(name, "Already exists") json = dict(creation_date=util.unicode_type(datetime.datetime.now())) pi...
def get_experiments(redis, active=True): """Gets the full list of experiments""" key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)]
def refresh(self): """Re-pulls the data from redis""" pipe = self.redis.pipeline() pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "metadata") pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices") pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice") results = pipe.execute() if results[0...
def choices(self): """Gets the experiment choices""" if self._choices == None: self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names] return self._choices
def confidence(self): """ Returns a tuple (chi squared, confident) of the experiment. Confident is simply a boolean specifying whether we're > 95%% sure that the results are statistically significant. """ choices = self.choices # Get the chi-squared between the top two choices, if more than two choices exist if len(cho...