INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Show all indexes in the database
def index(context, collection_name): """Show all indexes in the database""" LOG.info("Running scout view index") adapter = context.obj['adapter'] i = 0 click.echo("collection\tindex") for collection_name in adapter.collections(): for index in adapter.indexes(collection_name): ...
Update the phenotype for a institute. If -- add the groups will be added to the default groups. Else the groups will be replaced.
def groups(context, institute_id, phenotype_group, group_abbreviation, group_file, add): """ Update the phenotype for a institute. If --add the groups will be added to the default groups. Else the groups will be replaced. """ adapter = context.obj['adapter'] LOG.info("Running scout update instit...
Get a list with compounds objects for this variant.
def parse_compounds(compound_info, case_id, variant_type): """Get a list with compounds objects for this variant. Arguments: compound_info(str): A Variant dictionary case_id (str): unique family id variant_type(str): 'research' or 'clinical' Returns: ...
Export all genes from a build
def genes(context, build, json): """Export all genes from a build""" LOG.info("Running scout export genes") adapter = context.obj['adapter'] result = adapter.all_genes(build=build) if json: click.echo(dumps(result)) return gene_string = ("{0}\t{1}\t{2}\t{3}\t{4}") c...
Build a Individual object
def build_individual(ind): """Build a Individual object Args: ind (dict): A dictionary with individual information Returns: ind_obj (dict): A Individual object dict( individual_id = str, # required display_name = str, sex = str, ...
Upload variants to a case
def variants(context, case_id, institute, force, cancer, cancer_research, sv, sv_research, snv, snv_research, str_clinical, chrom, start, end, hgnc_id, hgnc_symbol, rank_treshold): """Upload variants to a case Note that the files has to be linked with the case, if they ...
Return a variant.
def case(institute_id, case_name): """Return a variant.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) if case_obj is None: return abort(404) return Response(json_util.dumps(case_obj), mimetype='application/json')
Display a specific SNV variant.
def variant(institute_id, case_name, variant_id): """Display a specific SNV variant.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) variant_obj = store.variant(variant_id) return Response(json_util.dumps(variant_obj), mimetype='application/json')
Show all collections in the database
def collections(context): """Show all collections in the database""" LOG.info("Running scout view collections") adapter = context.obj['adapter'] for collection_name in adapter.collections(): click.echo(collection_name)
Create a new institute and add it to the database
def institute(ctx, internal_id, display_name, sanger_recipients): """ Create a new institute and add it to the database """ adapter = ctx.obj['adapter'] if not internal_id: logger.warning("A institute has to have an internal id") ctx.abort() if not display_name: displa...
Update an institute
def institute(context, institute_id, sanger_recipient, coverage_cutoff, frequency_cutoff, display_name, remove_sanger): """ Update an institute """ adapter = context.obj['adapter'] LOG.info("Running scout update institute") try: adapter.update_institute( i...
Return a opened file
def get_file_handle(file_path): """Return a opened file""" if file_path.endswith('.gz'): file_handle = getreader('utf-8')(gzip.open(file_path, 'r'), errors='replace') else: file_handle = open(file_path, 'r', encoding='utf-8') return file_handle
Increments the day by converting to a datetime. date ().
def _inc_day(year, month, day, net): """Increments the day by converting to a datetime.date().""" d = date(year, month, day) new_d = d + timezone.timedelta(days=net) return new_d.year, new_d.month, new_d.day
Get the net of any next and prev querystrings.
def get_net(req): """Get the net of any 'next' and 'prev' querystrings.""" try: nxt, prev = map( int, (req.GET.get('cal_next', 0), req.GET.get('cal_prev', 0)) ) net = nxt - prev except Exception: net = 0 return net
Group events that occur on the same day then sort them alphabetically by title then sort by day. Returns a list of tuples that looks like [ ( day: [ events ] ) ] where day is the day of the event ( s ) and [ events ] is an alphabetically sorted list of the events for the day.
def order_events(events, d=False): """ Group events that occur on the same day, then sort them alphabetically by title, then sort by day. Returns a list of tuples that looks like [(day: [events])], where day is the day of the event(s), and [events] is an alphabetically sorted list of the events for ...
Returns what the next and prev querystrings should be.
def get_next_and_prev(net): """Returns what the next and prev querystrings should be.""" if net == 0: nxt = prev = 1 elif net > 0: nxt = net + 1 prev = -(net - 1) else: nxt = net + 1 prev = abs(net) + 1 return nxt, prev
Checks that the year is within 50 years from now.
def _check_year(year, month, error, error_msg): """Checks that the year is within 50 years from now.""" if year not in xrange((now.year - 50), (now.year + 51)): year = now.year month = now.month error = error_msg return year, month, error
If month_orig which is the month given in the url BEFORE any next/ prev query strings have been applied is out of range sets month to the current month and returns an error message. Also Returns an error message if the year given is +/ - 50 years from now. If month which is the month given in the url AFTER any next/ pr...
def clean_year_month(year, month, month_orig): """ If 'month_orig', which is the month given in the url BEFORE any next/prev query strings have been applied, is out of range, sets month to the current month and returns an error message. Also Returns an error message if the year given is +/- 50 years...
Make sure any event day we send back for weekday repeating events is not a weekend.
def check_weekday(year, month, day, reverse=False): """ Make sure any event day we send back for weekday repeating events is not a weekend. """ d = date(year, month, day) while d.weekday() in (5, 6): if reverse: d -= timedelta(days=1) else: d += timedelta(...
Parse all data necessary for loading a case into scout
def parse_case_data(config=None, ped=None, owner=None, vcf_snv=None, vcf_sv=None, vcf_cancer=None, vcf_str=None, peddy_ped=None, peddy_sex=None, peddy_check=None, delivery_report=None, multiqc=None): """Parse all data necessary for loading a case into scout This can be d...
Add information from peddy outfiles to the individuals
def add_peddy_information(config_data): """Add information from peddy outfiles to the individuals""" ped_info = {} ped_check = {} sex_check = {} relations = [] if config_data.get('peddy_ped'): file_handle = open(config_data['peddy_ped'], 'r') for ind_info in parse_peddy_ped(file...
Parse individual information
def parse_individual(sample): """Parse individual information Args: sample (dict) Returns: { 'individual_id': str, 'father': str, 'mother': str, 'display_name': str, 'sex': str, ...
Parse the individual information
def parse_individuals(samples): """Parse the individual information Reformat sample information to proper individuals Args: samples(list(dict)) Returns: individuals(list(dict)) """ individuals = [] if len(samples) == 0: raise PedigreeError("No s...
Parse case information from config or PED files.
def parse_case(config): """Parse case information from config or PED files. Args: config (dict): case config with detailed information Returns: dict: parsed case data """ if 'owner' not in config: raise ConfigError("A case has to have a owner") if 'family' not in confi...
Parse out minimal family information from a PED file.
def parse_ped(ped_stream, family_type='ped'): """Parse out minimal family information from a PED file. Args: ped_stream(iterable(str)) family_type(str): Format of the pedigree information Returns: family_id(str), samples(list[dict]) """ pedigree = FamilyParser(ped_stream, f...
Build a evaluation object ready to be inserted to database
def build_evaluation(variant_specific, variant_id, user_id, user_name, institute_id, case_id, classification, criteria): """Build a evaluation object ready to be inserted to database Args: variant_specific(str): md5 string for the specific variant variant_id(str): md5 strin...
Export all mitochondrial variants for each sample of a case and write them to an excel file
def mt_report(context, case_id, test, outpath=None): """Export all mitochondrial variants for each sample of a case and write them to an excel file Args: adapter(MongoAdapter) case_id(str) test(bool): True if the function is called for testing purposes ...
Build a genotype call Args: gt_call ( dict ) Returns: gt_obj ( dict ) gt_call = dict ( sample_id = str display_name = str genotype_call = str allele_depths = list # int read_depth = int genotype_quality = int )
def build_genotype(gt_call): """Build a genotype call Args: gt_call(dict) Returns: gt_obj(dict) gt_call = dict( sample_id = str, display_name = str, genotype_call = str, allele_depths = list, # int read_depth = int, genotype_...
Check if the criterias for Pathogenic is fullfilled
def is_pathogenic(pvs, ps_terms, pm_terms, pp_terms): """Check if the criterias for Pathogenic is fullfilled The following are descriptions of Pathogenic clasification from ACMG paper: Pathogenic (i) 1 Very strong (PVS1) AND (a) ≥1 Strong (PS1–PS4) OR (b) ≥2 Moderate (PM1–PM6) OR ...
Check if the criterias for Likely Pathogenic is fullfilled
def is_likely_pathogenic(pvs, ps_terms, pm_terms, pp_terms): """Check if the criterias for Likely Pathogenic is fullfilled The following are descriptions of Likely Pathogenic clasification from ACMG paper: Likely pathogenic (i) 1 Very strong (PVS1) AND 1 moderate (PM1– PM6) OR (ii) 1 Strong (P...
Check if criterias for Likely Benign are fullfilled
def is_likely_benign(bs_terms, bp_terms): """Check if criterias for Likely Benign are fullfilled The following are descriptions of Likely Benign clasification from ACMG paper: Likely Benign (i) 1 Strong (BS1–BS4) and 1 supporting (BP1– BP7) OR (ii) ≥2 Supporting (BP1–BP7) Args: bs...
Use the algorithm described in ACMG paper to get a ACMG calssification
def get_acmg(acmg_terms): """Use the algorithm described in ACMG paper to get a ACMG calssification Args: acmg_terms(set(str)): A collection of prediction terms Returns: prediction(int): 0 - Uncertain Significanse 1 - Benign 2 - Likely Benign...
Add extra information about genes from gene panels
def add_gene_info(self, variant_obj, gene_panels=None): """Add extra information about genes from gene panels Args: variant_obj(dict): A variant from the database gene_panels(list(dict)): List of panels from database """ gene_panels = gene_panels or [] #...
Returns variants specified in question for a specific case.
def variants(self, case_id, query=None, variant_ids=None, category='snv', nr_of_variants=10, skip=0, sort_key='variant_rank'): """Returns variants specified in question for a specific case. If skip not equal to 0 skip the first n variants. Arguments: case_id(str): ...
Return all variants with sanger information
def sanger_variants(self, institute_id=None, case_id=None): """Return all variants with sanger information Args: institute_id(str) case_id(str) Returns: res(pymongo.Cursor): A Cursor with all variants with sanger activity """ query = {'valida...
Returns the specified variant.
def variant(self, document_id, gene_panels=None, case_id=None): """Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant...
Return all variants seen in a given gene.
def gene_variants(self, query=None, category='snv', variant_type=['clinical'], nr_of_variants=50, skip=0): """Return all variants seen in a given gene. If skip not equal to 0 skip the first n variants. Arguments: query(dict): A dictionary with ...
Return all verified variants for a given institute
def verified(self, institute_id): """Return all verified variants for a given institute Args: institute_id(str): institute id Returns: res(list): a list with validated variants """ query = { 'verb' : 'validate', 'institute' : inst...
Return all causative variants for an institute
def get_causatives(self, institute_id, case_id=None): """Return all causative variants for an institute Args: institute_id(str) case_id(str) Yields: str: variant document id """ causatives = [] if case_id: ...
Check if there are any variants that are previously marked causative
def check_causatives(self, case_obj=None, institute_obj=None): """Check if there are any variants that are previously marked causative Loop through all variants that are marked 'causative' for an institute and check if any of the variants are present in the current case. ...
Find the same variant in other cases marked causative.
def other_causatives(self, case_obj, variant_obj): """Find the same variant in other cases marked causative. Args: case_obj(dict) variant_obj(dict) Yields: other_variant(dict) """ # variant id without "*_[variant_type]" variant_id = v...
Delete variants of one type for a case
def delete_variants(self, case_id, variant_type, category=None): """Delete variants of one type for a case This is used when a case is reanalyzed Args: case_id(str): The case id variant_type(str): 'research' or 'clinical' category(str): '...
Return overlapping variants.
def overlapping(self, variant_obj): """Return overlapping variants. Look at the genes that a variant overlaps to. Then return all variants that overlap these genes. If variant_obj is sv it will return the overlapping snvs and oposite There is a problem when SVs are huge since t...
Returns variants that has been evaluated
def evaluated_variants(self, case_id): """Returns variants that has been evaluated Return all variants, snvs/indels and svs from case case_id which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant' or if they are commented. Args: case_id(str) ...
Produce a reduced vcf with variants from the specified coordinates This is used for the alignment viewer.
def get_region_vcf(self, case_obj, chrom=None, start=None, end=None, gene_obj=None, variant_type='clinical', category='snv', rank_threshold=None): """Produce a reduced vcf with variants from the specified coordinates This is used for the alignment viewer....
Given a list of variants get variant objects found in a specific patient
def sample_variants(self, variants, sample_name, category = 'snv'): """Given a list of variants get variant objects found in a specific patient Args: variants(list): a list of variant ids sample_name(str): a sample display name category(str): 'snv', 'sv' .. ...
Get a client to the mongo database
def get_connection(host='localhost', port=27017, username=None, password=None, uri=None, mongodb=None, authdb=None, timeout=20, *args, **kwargs): """Get a client to the mongo database host(str): Host of database port(int): Port of database username(str) password(s...
Creates a list of submission objects ( variant and case - data ) from the clinvar submission form in blueprints/ variants/ clinvar. html.
def set_submission_objects(form_fields): """Creates a list of submission objects (variant and case-data) from the clinvar submission form in blueprints/variants/clinvar.html. Args: form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_H...
Extract the objects to be saved in the clinvar database collection. object_type param specifies if these objects are variant or casedata objects
def get_objects_from_form(variant_ids, form_fields, object_type): """Extract the objects to be saved in the clinvar database collection. object_type param specifies if these objects are variant or casedata objects Args: variant_ids(list): list of database variant ids form_fields(dict)...
Extracts a list of variant ids from the clinvar submission form in blueprints/ variants/ clinvar. html ( creation of a new clinvar submission ).
def get_submission_variants(form_fields): """Extracts a list of variant ids from the clinvar submission form in blueprints/variants/clinvar.html (creation of a new clinvar submission). Args: form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and ...
Determine which fields to include in csv header by checking a list of submission objects
def clinvar_submission_header(submission_objs, csv_type): """Determine which fields to include in csv header by checking a list of submission objects Args: submission_objs(list): a list of objects (variants or casedata) to include in a csv file csv_type(str) : 'variant_data' or 'cas...
Create the lines to include in a Clinvar submission csv file from a list of submission objects and a custom document header
def clinvar_submission_lines(submission_objs, submission_header): """Create the lines to include in a Clinvar submission csv file from a list of submission objects and a custom document header Args: submission_objs(list): a list of objects (variants or casedata) to include in a csv file ...
Load all the transcripts
def load_transcripts(adapter, transcripts_lines=None, build='37', ensembl_genes=None): """Load all the transcripts Transcript information is from ensembl. Args: adapter(MongoAdapter) transcripts_lines(iterable): iterable with ensembl transcript lines build(str) ensembl_gene...
Add a gene panel to the database.
def panel(context, path, date, display_name, version, panel_type, panel_id, institute, omim, api_key, panel_app): """Add a gene panel to the database.""" adapter = context.obj['adapter'] institute = institute or 'cust000' if omim: api_key = api_key or context.obj.get('omim_api_key') if...
Build a Exon object object
def build_exon(exon_info, build='37'): """Build a Exon object object Args: exon_info(dict): Exon information Returns: exon_obj(Exon) "exon_id": str, # str(chrom-start-end) "chrom": str, "start": int, "end": int, "trans...
Delete a version of a gene panel or all versions of a gene panel
def panel(context, panel_id, version): """Delete a version of a gene panel or all versions of a gene panel""" LOG.info("Running scout delete panel") adapter = context.obj['adapter'] panel_objs = adapter.gene_panels(panel_id=panel_id, version=version) if panel_objs.count() == 0: LOG.info("No...
Delete all indexes in the database
def index(context): """Delete all indexes in the database""" LOG.info("Running scout delete index") adapter = context.obj['adapter'] for collection in adapter.db.collection_names(): adapter.db[collection].drop_indexes() LOG.info("All indexes deleted")
Delete a user from the database
def user(context, mail): """Delete a user from the database""" LOG.info("Running scout delete user") adapter = context.obj['adapter'] user_obj = adapter.user(mail) if not user_obj: LOG.warning("User {0} could not be found in database".format(mail)) else: adapter.delete_user(mail)
Delete all genes in the database
def genes(context, build): """Delete all genes in the database""" LOG.info("Running scout delete genes") adapter = context.obj['adapter'] if build: LOG.info("Dropping genes collection for build: %s", build) else: LOG.info("Dropping genes collection") adapter.drop_genes()
Delete all exons in the database
def exons(context, build): """Delete all exons in the database""" LOG.info("Running scout delete exons") adapter = context.obj['adapter'] adapter.drop_exons(build)
Delete a case and it s variants from the database
def case(context, institute, case_id, display_name): """Delete a case and it's variants from the database""" adapter = context.obj['adapter'] if not (case_id or display_name): click.echo("Please specify what case to delete") context.abort() if display_name: if not institute: ...
Show all individuals from all cases in the database
def individuals(context, institute, causatives, case_id): """Show all individuals from all cases in the database""" LOG.info("Running scout view individuals") adapter = context.obj['adapter'] individuals = [] if case_id: case = adapter.case(case_id=case_id) if case: case...
Extract all phenotype - associated terms for a case. Drawback of this method is that it returns the same phenotype terms for each affected individual of the case. Args: case_obj ( dict ): a scout case object Returns: features ( list ): a list of phenotype objects that looks like this: [ { id: HP: 0001644 label: Dilated...
def hpo_terms(case_obj): """Extract all phenotype-associated terms for a case. Drawback of this method is that it returns the same phenotype terms for each affected individual of the case. Args: case_obj(dict): a scout case object Returns: features(list): a li...
Extract all OMIM phenotypes available for the case Args: case_obj ( dict ): a scout case object Returns: disorders ( list ): a list of OMIM disorder objects
def omim_terms(case_obj): """Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects """ LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name'))) disorders...
Extract and parse matchmaker - like genomic features from pinned variants of a patient Args: store ( MongoAdapter ): connection to the database case_obj ( dict ): a scout case object sample_name ( str ): sample display name genes_only ( bool ): if True only gene names will be included in genomic features
def genomic_features(store, case_obj, sample_name, genes_only): """Extract and parse matchmaker-like genomic features from pinned variants of a patient Args: store(MongoAdapter) : connection to the database case_obj(dict): a scout case object sample_name(str): sample display name...
Parse a list of matchmaker matches objects and returns a readable list of matches to display in matchmaker matches view.
def parse_matches(patient_id, match_objs): """Parse a list of matchmaker matches objects and returns a readable list of matches to display in matchmaker matches view. Args: patient_id(str): id of a mme patient match_objs(list): list of match objs returned by MME server for the patient ...
Display cases from the database
def cases(context, institute, display_name, case_id, nr_variants, variants_treshold): """Display cases from the database""" LOG.info("Running scout view institutes") adapter = context.obj['adapter'] models = [] if case_id: case_obj = adapter.case(case_id=case_id) if case_obj: ...
Returns the currently active user as an object.
def load_user(user_email): """Returns the currently active user as an object.""" user_obj = store.user(user_email) user_inst = LoginUser(user_obj) if user_obj else None return user_inst
Login a user if they have access.
def login(): """Login a user if they have access.""" # store potential next param URL in the session if 'next' in request.args: session['next_url'] = request.args['next'] if current_app.config.get('GOOGLE'): callback_url = url_for('.authorized', _external=True) return google.aut...
Updates a case after a submission to MatchMaker Exchange Args: case_obj ( dict ): a scout case object user_obj ( dict ): a scout user object mme_subm_obj ( dict ): contains MME submission params and server response Returns: updated_case ( dict ): the updated scout case
def case_mme_update(self, case_obj, user_obj, mme_subm_obj): """Updates a case after a submission to MatchMaker Exchange Args: case_obj(dict): a scout case object user_obj(dict): a scout user object mme_subm_obj(dict): contains MME submission params an...
Delete a MatchMaker submission from a case record and creates the related event. Args: case_obj ( dict ): a scout case object user_obj ( dict ): a scout user object Returns: updated_case ( dict ): the updated scout case
def case_mme_delete(self, case_obj, user_obj): """Delete a MatchMaker submission from a case record and creates the related event. Args: case_obj(dict): a scout case object user_obj(dict): a scout user object Returns: updated_case(dict): the updated...
Build a institute object
def build_institute(internal_id, display_name, sanger_recipients=None, coverage_cutoff=None, frequency_cutoff=None): """Build a institute object Args: internal_id(str) display_name(str) sanger_recipients(list(str)): List with email addresses Returns: ins...
Delete a event
def delete_event(self, event_id): """Delete a event Arguments: event_id (str): The database key for the event """ LOG.info("Deleting event{0}".format(event_id)) if not isinstance(event_id, ObjectId): event_id = ObjectId(event_id) self.even...
Create a Event with the parameters given.
def create_event(self, institute, case, user, link, category, verb, subject, level='specific', variant=None, content=None, panel=None): """Create a Event with the parameters given. Arguments: institute (dict): A institute case (dict): A ...
Fetch events from the database.
def events(self, institute, case=None, variant_id=None, level=None, comments=False, panel=None): """Fetch events from the database. Args: institute (dict): A institute case (dict): A case variant_id (str, optional): global variant id leve...
Fetch all events by a specific user.
def user_events(self, user_obj=None): """Fetch all events by a specific user.""" query = dict(user_id=user_obj['_id']) if user_obj else dict() return self.event_collection.find(query)
Add a new phenotype term to a case
def add_phenotype(self, institute, case, user, link, hpo_term=None, omim_term=None, is_group=False): """Add a new phenotype term to a case Create a phenotype term and event with the given information Args: institute (Institute): A Institute object ...
Remove an existing phenotype from a case
def remove_phenotype(self, institute, case, user, link, phenotype_id, is_group=False): """Remove an existing phenotype from a case Args: institute (dict): A Institute object case (dict): Case object user (dict): A User object link...
Add a comment to a variant or a case.
def comment(self, institute, case, user, link, variant=None, content="", comment_level="specific"): """Add a comment to a variant or a case. This function will create an Event to log that a user have commented on a variant. If a variant id is given it will be a variant comment. ...
Parse the genotype calls for a variant
def parse_genotypes(variant, individuals, individual_positions): """Parse the genotype calls for a variant Args: variant(cyvcf2.Variant) individuals: List[dict] individual_positions(dict) Returns: genotypes(list(dict)): A list of genotypes """ ...
Get the genotype information in the proper format
def parse_genotype(variant, ind, pos): """Get the genotype information in the proper format Sv specific format fields: ##FORMAT=<ID=DV,Number=1,Type=Integer, Description="Number of paired-ends that support the event"> ##FORMAT=<ID=PE,Number=1,Type=Integer, Description="Number of paired-ends t...
Check if a variant is in the Pseudo Autosomal Region or not Args: chromosome ( str ) position ( int ) build ( str ): The genome build Returns: bool
def is_par(chromosome, position, build='37'): """Check if a variant is in the Pseudo Autosomal Region or not Args: chromosome(str) position(int) build(str): The genome build Returns: bool """ chrom_match = CHR_PATTERN.match(chromosome) chrom = chrom_matc...
Check if the variant is in the interval given by the coordinates
def check_coordinates(chromosome, pos, coordinates): """Check if the variant is in the interval given by the coordinates Args: chromosome(str): Variant chromosome pos(int): Variant position coordinates(dict): Dictionary with the region of interest """ chrom_match...
Export all genes in gene panels Exports the union of genes in one or several gene panels to a bed like format with coordinates. Args: adapter ( scout. adapter. MongoAdapter ) panels ( iterable ( str )): Iterable with panel ids bed ( bool ): If lines should be bed formated
def export_panels(adapter, panels, versions=None, build='37'): """Export all genes in gene panels Exports the union of genes in one or several gene panels to a bed like format with coordinates. Args: adapter(scout.adapter.MongoAdapter) panels(iterable(str)): Iterable with panel ids...
Export the genes of a gene panel Takes a list of gene panel names and return the lines of the gene panels. Unlike export_panels this function only export the genes and extra information not the coordinates. Args: adapter ( MongoAdapter ) panels ( list ( str )) version ( float ): Version number only works when one panel...
def export_gene_panels(adapter, panels, version=None): """Export the genes of a gene panel Takes a list of gene panel names and return the lines of the gene panels. Unlike export_panels this function only export the genes and extra information, not the coordinates. Args: adapter(M...
Render search box and view for HPO phenotype terms
def hpo_terms(): """Render search box and view for HPO phenotype terms""" if request.method == 'GET': data = controllers.hpo_terms(store= store, limit=100) return data else: # POST. user is searching for a specific term or phenotype search_term = request.form.get('hpo_term') ...
Export all transcripts to. bed like format
def transcripts(context, build): """Export all transcripts to .bed like format""" LOG.info("Running scout export transcripts") adapter = context.obj['adapter'] header = ["#Chrom\tStart\tEnd\tTranscript\tRefSeq\tHgncID"] for line in header: click.echo(line) transcript_string = ("{0...
Load exons into the scout database
def exons(context, build): """Load exons into the scout database""" adapter = context.obj['adapter'] start = datetime.now() # Test if there are any exons loaded nr_exons = adapter.exons(build=build).count() if nr_exons: LOG.warning("Dropping all exons ") adapter.dr...
Show all indexes in the database
def intervals(context, build): """Show all indexes in the database""" LOG.info("Running scout view index") adapter = context.obj['adapter'] intervals = adapter.get_coding_intervals(build) nr_intervals = 0 longest = 0 for chrom in CHROMOSOMES: for iv in intervals[chrom]: ...
Load all variants in a region to a existing case
def region(context, hgnc_id, case_id, chromosome, start, end): """Load all variants in a region to a existing case""" adapter = context.obj['adapter'] load_region( adapter=adapter, case_id=case_id, hgnc_id=hgnc_id, chrom=chromosome, start=start, end=end )
Helper function for getting category/ tag kwargs.
def _get_kwargs(self, category, tag): """Helper function for getting category/tag kwargs.""" vals = { 'categories__title__iexact': category, 'tags__name__iexact': tag } kwargs = {} for k, v in vals.items(): if v: kwargs[k] = v ...
Returns two datetimes: first day and last day of given year&month
def get_first_and_last(year, month): """Returns two datetimes: first day and last day of given year&month""" ym_first = make_aware( datetime.datetime(year, month, 1), get_default_timezone() ) ym_last = make_aware( datetime.datetime(year, month, monthra...
Returns all events that have an occurrence within the given month & year.
def all_month_events(self, year, month, category=None, tag=None, loc=False, cncl=False): """ Returns all events that have an occurrence within the given month & year. """ kwargs = self._get_kwargs(category, tag) ym_first, ym_last = self.get_first_...
Returns a queryset of events that will occur again after now. Used to help generate a list of upcoming events.
def live(self, now): """ Returns a queryset of events that will occur again after 'now'. Used to help generate a list of upcoming events. """ return self.model.objects.filter( Q(end_repeat=None) | Q(end_repeat__gte=now) | Q(start_date__gte=now) | Q(end_dat...
Build a user object Args: user_info ( dict ): A dictionary with user information Returns: user_obj ( scout. models. User )
def build_user(user_info): """Build a user object Args: user_info(dict): A dictionary with user information Returns: user_obj(scout.models.User) """ try: email = user_info['email'] except KeyError as err: raise KeyError("A user has to have a email") ...
Recursively parse requirements from nested pip files.
def parse_reqs(req_path='./requirements.txt'): """Recursively parse requirements from nested pip files.""" install_requires = [] with io.open(os.path.join(here, 'requirements.txt'), encoding='utf-8') as handle: # remove comments and empty lines lines = (line.strip() for line in handle ...
Check if gene is already added to a panel.
def existing_gene(store, panel_obj, hgnc_id): """Check if gene is already added to a panel.""" existing_genes = {gene['hgnc_id']: gene for gene in panel_obj['genes']} return existing_genes.get(hgnc_id)
Update an existing gene panel with genes.
def update_panel(store, panel_name, csv_lines, option): """Update an existing gene panel with genes. Args: store(scout.adapter.MongoAdapter) panel_name(str) csv_lines(iterable(str)): Stream with genes option(str): 'add' or 'replace' Returns: panel_obj(dict) """ ...
Create a new gene panel.
def new_panel(store, institute_id, panel_name, display_name, csv_lines): """Create a new gene panel. Args: store(scout.adapter.MongoAdapter) institute_id(str) panel_name(str) display_name(str) csv_lines(iterable(str)): Stream with genes Returns: panel_id: th...
Preprocess a panel of genes.
def panel_export(store, panel_obj): """Preprocess a panel of genes.""" panel_obj['institute'] = store.institute(panel_obj['institute']) full_name = "{}({})".format(panel_obj['display_name'], panel_obj['version']) panel_obj['name_and_version'] = full_name return dict(panel=panel_obj)