Constructor for a GenomicRange object that takes a string
775023
def GenomicRangeFromString(range_string,payload=None,dir=None):
  """"""
  m = re.match('^(.+):(\d+)-(\d+)$',range_string)
  if not m:  
    sys.stderr.write("ERROR bad genomic range string\n"+range_string+"\n")
    sys.exit()
  chr = m.group(1)
  start = int(m.group(2))
  end = int(m.group(3))
  return GenomicRange(chr,start,end,payload,dir)
9278
def from_str(cls, s):
        """"""
        ast_obj = ast.parse(s).body[0]
        if not isinstance(ast_obj, cls._expected_ast_type):
            raise AssertionError(
                'Expected ast of type {!r} but got {!r}'.format(
                    cls._expected_ast_type,
                    ast_obj
                )
            )
        return cls(ast_obj)
1284551
def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords
313873
function (cpon, obj) {
  if (typeof cpon !== 'string')
    throw new Error('expected CPON string');

  if (obj === undefined)
    obj = {};

  var caret = cpon.indexOf('^');
  if (caret < 0)
    throw new Error('caret (^) not found in garden');

  var key = left(cpon, caret);
  var value = cpon.substring(caret + 1);
  var pipe = value.indexOf('|');
  if (pipe > -1) {
    obj = (value.substring(pipe + 1),obj);
    value = left(value,pipe);
  }
  obj[key] = value;
  return obj;
}
105993
@SuppressWarnings({"unchecked", "rawtypes"})
    protected Object constructFromString( final String stringValue, final String argumentName) {
        final Class clazz = getUnderlyingFieldClass();
        try {
            if (clazz.isEnum()) {
                try {
                    return Enum.valueOf(clazz, stringValue);
                } catch (final IllegalArgumentException e) {
                    throw new CommandLineException.BadArgumentValue(
                            argumentName,
                            stringValue,
                            String.format("'%s' is not a valid value for %s. Allowed values are %s",
                                    stringValue,
                                    clazz.getSimpleName(),
                                    getEnumOptions(clazz)));
                }
            }
            // Need to use getDeclaredConstructor() instead of getConstructor() in case the constructor
            // is non-public. Set it to be accessible if it isn't already.
            final Constructor<?> ctor = clazz.getDeclaredConstructor(String.class);
            ctor.setAccessible(true);
            return ctor.newInstance(stringValue);
        } catch (final NoSuchMethodException e) {
            // Shouldn't happen because we've checked for presence of ctor
            throw new CommandLineException.ShouldNeverReachHereException(
                    String.format("Cannot find string ctor for %s", clazz.getName()), e);
        } catch (final InstantiationException e) {
            throw new CommandLineException.CommandLineParserInternalException(
                    String.format("Abstract class '%s' cannot be used for an argument value type.", clazz.getSimpleName()), e);
        } catch (final IllegalAccessException e) {
            throw new CommandLineException.CommandLineParserInternalException(
                    String.format("String constructor for argument value type '%s' must be public.", clazz.getSimpleName()), e);
        } catch (final InvocationTargetException e) {
            throw new CommandLineException.BadArgumentValue(
                    argumentName,
                    stringValue,
                    String.format("Failure constructing '%s' from the string '%s'.", clazz.getSimpleName(), stringValue));
        }
    }
371798
function fillRange(value) {
  var start = value.split('~')[0];
  var end   = value.split('~')[1];

  var decimals = (start.split('.')[1] || '').length;
  var mult = Math.pow(10, decimals);

  var range = _.range(start * mult, end * mult + 1)
                  // round errors to required decimal precision
                  .map(function (val) {
                    return (val / mult).toFixed(decimals);
                  });

  var last = range[range.length - 1];

  // Stupid self check
  if (+end !== +last) {
    throw new Error(format('Range create error for %s: last value is %s', value, last));
  }

  // Now we have array of string samples. Add integers when possible.
  var result = [];

  range.forEach(function (val) {
    // push test data as String
    result.push(val);
    // push test data as Number if the same
    if (String(+val) === val) { result.push(+val); }
  });

  return result;
}
38916
def from_string(self, source, globals=None, template_class=None):
        
        globals = self.make_globals(globals)
        cls = template_class or self.template_class
        return cls.from_code(self, self.compile(source), globals, None)
295940
def _handle_special_inputs(inputs, variables):
    
    from bcbio import structural
    optional = [["config", "algorithm", "coverage"],
                ["config", "algorithm", "variant_regions"],
                ["config", "algorithm", "sv_regions"],
                ["config", "algorithm", "validate"],
                ["config", "algorithm", "validate_regions"]]
    all_vs = set([get_base_id(v["id"]) for v in variables])
    out = []
    for input in inputs:
        if input == ["reference", "aligner", "indexes"]:
            for v in variables:
                vid = get_base_id(v["id"]).split("__")
                if vid[0] == "reference" and vid[1] in alignment.TOOLS:
                    out.append(vid)
        elif input == ["reference", "snpeff", "genome_build"]:
            found_indexes = False
            for v in variables:
                vid = get_base_id(v["id"]).split("__")
                if vid[0] == "reference" and vid[1] == "snpeff":
                    out.append(vid)
                    found_indexes = True
            assert found_indexes, "Found no snpEff indexes in %s" % [v["id"] for v in variables]
        elif input == ["config", "algorithm", "background", "cnv_reference"]:
            for v in variables:
                vid = get_base_id(v["id"]).split("__")
                if (vid[:4] == ["config", "algorithm", "background", "cnv_reference"] and
                      structural.supports_cnv_reference(vid[4])):
                    out.append(vid)
        elif input in optional:
            if _get_string_vid(input) in all_vs:
                out.append(input)
        else:
            out.append(input)
    return out
846384
@Override
	protected R parseValueFromString(String s)
	{
		Class<R> range = this.getRange();
		R value = null;
		try
		{
			if (range.equals(double.class))
			{
				value= (R) Double.valueOf(s);
			}
			else if (range.equals(float.class))
			{
				value=  (R) Float.valueOf(s);
			}
			else if (range.equals(int.class))
			{
				value= (R) Integer.valueOf(s);
			}
			else if (range.equals(Boolean.class))
			{
				value= (R) Boolean.valueOf(s);
			}
		}

		catch (NumberFormatException e)

		{
			throw new IllegalBioPAXArgumentException(
					"Failed to convert literal " + s +
					" to " + range.getSimpleName()
					+ " for " + property, e);
		}
		return value;
	}
1228431
def _construct(self, strings_collection):
        
        
        # 1. Add a unique character to each string in the collection
        strings_collection = utils.make_unique_endings(strings_collection)
    
        ############################################################
        # 2. Build the GST using modified Ukkonnen's algorithm     #
        ############################################################
        
        root = ast.AnnotatedSuffixTree.Node()
        root.strings_collection = strings_collection
        # To preserve simplicity
        root.suffix_link = root
        root._arc = (0,-1,0)
        # For constant updating of all leafs, see [Gusfield {RUS}, p. 139]
        root._e = [0 for _ in xrange(len(strings_collection))]
        
        
        def _ukkonen_first_phases(string_ind):
            """
            Looks for the part of the string which is already encoded.
            Returns a tuple of form
            ([length of already encoded string preffix],
             [tree node to start the first explicit phase with],
             [path to go down at the beginning of the first explicit phase]).
            
            """
            already_in_tree = 0
            suffix = strings_collection[string_ind]
            starting_path = (0, 0, 0)
            starting_node = root
            child_node = starting_node.chose_arc(suffix)
            while child_node:
                (str_ind, substr_start, substr_end) = child_node.arc()
                match = utils.match_strings(
                            suffix, strings_collection[str_ind][substr_start:substr_end])
                already_in_tree += match
                if match == substr_end-substr_start:
                    # matched the arc, proceed with child node
                    suffix = suffix[match:]
                    starting_node = child_node
                    child_node = starting_node.chose_arc(suffix)
                else:
                    # otherwise we will have to proceed certain path at the beginning
                    # of the first explicit phase
                    starting_path = (str_ind, substr_start, substr_start+match)
                    break
            # For constant updating of all leafs, see [Gusfield {RUS}, p. 139]
            root._e[string_ind] = already_in_tree
                
            return (already_in_tree, starting_node, starting_path)
        
        def _ukkonen_phase(string_ind, phase, starting_node, starting_path, starting_continuation):
            """
            Ukkonen's algorithm single phase.
            Returns a tuple of form:
            ([tree node to start the next phase with],
             [path to go down at the beginning of the next phase],
             [starting continuation for the next phase]).
            
            """
            current_suffix_end = starting_node
            suffix_link_source_node = None
            path_str_ind, path_substr_start, path_substr_end = starting_path
            # Continuations [starting_continuation..(i+1)]
            for continuation in xrange(starting_continuation, phase+1):
                # Go up to the first node with suffix link [no more than 1 pass]
                if continuation > starting_continuation:
                    path_str_ind, path_substr_start, path_substr_end = 0, 0, 0
                    if not current_suffix_end.suffix_link:
                        (path_str_ind, path_substr_start, path_substr_end) = current_suffix_end.arc()
                        current_suffix_end = current_suffix_end.parent
                    if current_suffix_end.is_root():
                        path_str_ind = string_ind
                        path_substr_start = continuation
                        path_substr_end = phase
                    else:
                        # Go through the suffix link
                        current_suffix_end = current_suffix_end.suffix_link
                        
                # Go down the path (str_ind, substr_start, substr_end)
                # NB: using Skip/Count trick,
                # see [Gusfield {RUS} p.134] for details
                g = path_substr_end - path_substr_start
                if g > 0:
                    current_suffix_end = current_suffix_end.chose_arc(strings_collection
                                         [path_str_ind][path_substr_start])
                (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc()
                g_ = cs_ss_end - cs_ss_start
                while g >= g_:
                    path_substr_start += g_
                    g -= g_
                    if g > 0:
                        current_suffix_end = current_suffix_end.chose_arc(strings_collection
                                             [path_str_ind][path_substr_start])
                    (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc()
                    g_ = cs_ss_end - cs_ss_start
                    
                # Perform continuation by one of three rules,
                # see [Gusfield {RUS} p. 129] for details
                if g == 0:
                    # Rule 1
                    if current_suffix_end.is_leaf():
                        pass
                    # Rule 2a
                    elif not current_suffix_end.chose_arc(strings_collection[string_ind][phase]):
                        if suffix_link_source_node:
                            suffix_link_source_node.suffix_link = current_suffix_end
                        new_leaf = current_suffix_end.add_new_child(string_ind, phase, -1)
                        new_leaf.weight = 1
                        if continuation == starting_continuation:
                            starting_node = new_leaf
                            starting_path = (0, 0, 0)
                    # Rule 3a
                    else:
                        if suffix_link_source_node:
                            suffix_link_source_node.suffix_link = current_suffix_end
                        starting_continuation = continuation
                        starting_node = current_suffix_end
                        starting_path = (string_ind, phase, phase+1)
                        break
                    suffix_link_source_node = None
                else:
                    (si, ss, se) = current_suffix_end._arc
                    # Rule 2b
                    if strings_collection[si][ss + g] != strings_collection[string_ind][phase]:
                        parent = current_suffix_end.parent
                        parent.remove_child(current_suffix_end)
                        current_suffix_end._arc = (si, ss+g, se)
                        new_node = parent.add_new_child(si, ss, ss + g)
                        new_leaf = new_node.add_new_child(string_ind, phase, -1)
                        new_leaf.weight = 1
                        if continuation == starting_continuation:
                            starting_node = new_leaf
                            starting_path = (0, 0, 0)
                        new_node.add_child(current_suffix_end)
                        if suffix_link_source_node:
                            # Define new suffix link
                            suffix_link_source_node.suffix_link = new_node
                        suffix_link_source_node = new_node
                        current_suffix_end = new_node
                    # Rule 3b
                    else:
                        suffix_link_source_node = None
                        starting_continuation = continuation
                        starting_node = current_suffix_end.parent
                        starting_path = (si, ss, ss+g+1)
                        break
            
            # Constant updating of all leafs, see [Gusfield {RUS}, p. 139]
            starting_node._e[string_ind] += 1
            
            return starting_node, starting_path, starting_continuation
                        
        for m in xrange(len(strings_collection)):
            # Check for phases 1..x that are already in tree
            starting_phase, starting_node, starting_path = _ukkonen_first_phases(m)
            starting_continuation = 0
            # Perform phases (x+1)..n explicitly
            for phase in xrange(starting_phase, len(strings_collection[m])):
                starting_node, starting_path, starting_continuation = \
                    _ukkonen_phase(m, phase, starting_node, starting_path, starting_continuation)
                    
        
        ############################################################
        ############################################################
        ############################################################
        
        # 3. Delete degenerate first-level children
        for k in root.children.keys():
            (ss, si, se) = root.children[k].arc()
            if (se - si == 1 and
                ord(strings_collection[ss][si]) >= consts.String.UNICODE_SPECIAL_SYMBOLS_START):
                del root.children[k]
        
        # 4. Make a depth-first bottom-up traversal and annotate
        #    each node by the sum of its children;
        #    each leaf is already annotated with '1'.
        def _annotate(node):
            weight = 0
            for k in node.children:
                if node.children[k].weight > 0:
                    weight += node.children[k].weight
                else:
                    weight += _annotate(node.children[k])
            node.weight = weight
            return weight
        _annotate(root)
        
        return root
856563
def generate_validator_constructor(ns, data_type):
    
    dt, nullable_dt = unwrap_nullable(data_type)
    if is_list_type(dt):
        v = generate_func_call(
            'bv.List',
            args=[
                generate_validator_constructor(ns, dt.data_type)],
            kwargs=[
                ('min_items', dt.min_items),
                ('max_items', dt.max_items)],
        )
    elif is_map_type(dt):
        v = generate_func_call(
            'bv.Map',
            args=[
                generate_validator_constructor(ns, dt.key_data_type),
                generate_validator_constructor(ns, dt.value_data_type),
            ]
        )
    elif is_numeric_type(dt):
        v = generate_func_call(
            'bv.{}'.format(dt.name),
            kwargs=[
                ('min_value', dt.min_value),
                ('max_value', dt.max_value)],
        )
    elif is_string_type(dt):
        pattern = None
        if dt.pattern is not None:
            pattern = repr(dt.pattern)
        v = generate_func_call(
            'bv.String',
            kwargs=[
                ('min_length', dt.min_length),
                ('max_length', dt.max_length),
                ('pattern', pattern)],
        )
    elif is_timestamp_type(dt):
        v = generate_func_call(
            'bv.Timestamp',
            args=[repr(dt.format)],
        )
    elif is_user_defined_type(dt):
        v = fmt_class(dt.name) + '_validator'
        if ns.name != dt.namespace.name:
            v = '{}.{}'.format(fmt_namespace(dt.namespace.name), v)
    elif is_alias(dt):
        # Assume that the alias has already been declared elsewhere.
        name = fmt_class(dt.name) + '_validator'
        if ns.name != dt.namespace.name:
            name = '{}.{}'.format(fmt_namespace(dt.namespace.name), name)
        v = name
    elif is_boolean_type(dt) or is_bytes_type(dt) or is_void_type(dt):
        v = generate_func_call('bv.{}'.format(dt.name))
    else:
        raise AssertionError('Unsupported data type: %r' % dt)

    if nullable_dt:
        return generate_func_call('bv.Nullable', args=[v])
    else:
        return v
121087
def from_string(cls, s):
        """"""
        stream = cStringIO(s)
        stream.seek(0)
        return cls(**yaml.safe_load(stream))
1215464
def actual_query_range(self):
    
    a = self.alignment_ranges
    #return GenomicRange(a[0][1].chr,a[0][1].start,a[-1][1].end,self.get_strand())
    if self.get_strand() == '+':
      return GenomicRange(a[0][1].chr,a[0][1].start,a[-1][1].end,self.get_strand())
    #must be - strand
    return GenomicRange(a[0][1].chr,self.query_sequence_length-a[-1][1].end+1,self.query_sequence_length-a[0][1].start+1,dir=self.strand)
1351483
def parse_chromosome_string(job, chromosome_string):
    
    if chromosome_string is None:
        return []
    else:
        assert isinstance(chromosome_string, str)
        chroms = [c.strip() for c in chromosome_string.split(',')]
        if 'canonical' in chroms:
            assert 'canonical_chr' not in chroms, 'Cannot have canonical and canonical_chr'
            chr_prefix = False
            chroms.remove('canonical')
            out_chroms = [str(c) for c in range(1, 23)] + ['X', 'Y']
        elif 'canonical_chr' in chroms:
            assert 'canonical' not in chroms, 'Cannot have canonical and canonical_chr'
            chr_prefix = True
            chroms.remove('canonical_chr')
            out_chroms = ['chr' + str(c) for c in range(1, 23)] + ['chrX', 'chrY']
        else:
            chr_prefix = None
            out_chroms = []
        for chrom in chroms:
            if chr_prefix is not None and chrom.startswith('chr') is not chr_prefix:
                job.fileStore.logToMaster('chromosome %s does not match the rest that %s begin '
                                          'with "chr".' % (chrom,
                                                           'all' if chr_prefix else 'don\'t'),
                                          level=logging.WARNING)
            out_chroms.append(chrom)
        return chrom_sorted(out_chroms)
1150256
void genCatch(JCCatch tree,
                      Env<GenContext> env,
                      int startpc, int endpc,
                      List<Integer> gaps) {
            if (startpc != endpc) {
                List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs
                        = catchTypesWithAnnotations(tree);
                while (gaps.nonEmpty()) {
                    for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
                        JCExpression subCatch = subCatch1.snd;
                        int catchType = makeRef(tree.pos(), subCatch.type);
                        int end = gaps.head.intValue();
                        registerCatch(tree.pos(),
                                      startpc,  end, code.curCP(),
                                      catchType);
                        for (Attribute.TypeCompound tc :  subCatch1.fst) {
                                tc.position.setCatchInfo(catchType, startpc);
                        }
                    }
                    gaps = gaps.tail;
                    startpc = gaps.head.intValue();
                    gaps = gaps.tail;
                }
                if (startpc < endpc) {
                    for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
                        JCExpression subCatch = subCatch1.snd;
                        int catchType = makeRef(tree.pos(), subCatch.type);
                        registerCatch(tree.pos(),
                                      startpc, endpc, code.curCP(),
                                      catchType);
                        for (Attribute.TypeCompound tc :  subCatch1.fst) {
                            tc.position.setCatchInfo(catchType, startpc);
                        }
                    }
                }
                VarSymbol exparam = tree.param.sym;
                code.statBegin(tree.pos);
                code.markStatBegin();
                int limit = code.nextreg;
                code.newLocal(exparam);
                items.makeLocalItem(exparam).store();
                code.statBegin(TreeInfo.firstStatPos(tree.body));
                genStat(tree.body, env, CRT_BLOCK);
                code.endScopes(limit);
                code.statBegin(TreeInfo.endPos(tree.body));
            }
        }
1324249
function createRange(desc) {
  var fields = ['exact', 'offset', 'selector'];
  utils.check(fields, desc);
  return { exact: desc.exact, offset: desc.offset, selector: desc.selector};
}
54099
def _importGenomeObjects(gtfFilePath, chroSet, genome, batchSize, verbose = 0) :
    """"""

    class Store(object) :
        
        def __init__(self, conf) :
            self.conf = conf
            self.chromosomes = {}
            
            self.genes = {}
            self.transcripts = {}
            self.proteins = {}
            self.exons = {}

        def batch_save(self) :
            self.conf.db.beginTransaction()
            
            for c in self.genes.itervalues() :
                c.save()
                conf.removeFromDBRegistery(c)
                
            for c in self.transcripts.itervalues() :
                c.save()
                conf.removeFromDBRegistery(c.exons)
                conf.removeFromDBRegistery(c)
            
            for c in self.proteins.itervalues() :
                c.save()
                conf.removeFromDBRegistery(c)
            
            self.conf.db.endTransaction()
            
            del(self.genes)
            del(self.transcripts)
            del(self.proteins)
            del(self.exons)
            
            self.genes = {}
            self.transcripts = {}
            self.proteins = {}
            self.exons = {}

            gc.collect()

        def save_chros(self) :
            pBar = ProgressBar(nbEpochs = len(self.chromosomes))
            for c in self.chromosomes.itervalues() :
                pBar.update(label = 'Chr %s' % c.number)
                c.save()
            pBar.close()
        
    printf('Importing gene set infos from %s...' % gtfFilePath)
    
    printf('Backuping indexes...')
    indexes = conf.db.getIndexes()
    printf("Droping all your indexes, (don't worry i'll restore them later)...")
    Genome_Raba.flushIndexes()
    Chromosome_Raba.flushIndexes()
    Gene_Raba.flushIndexes()
    Transcript_Raba.flushIndexes()
    Protein_Raba.flushIndexes()
    Exon_Raba.flushIndexes()
    
    printf("Parsing gene set...")
    gtf = GTFFile(gtfFilePath, gziped = True)
    printf('Done. Importation begins!')
    
    store = Store(conf)
    chroNumber = None
    pBar = ProgressBar(nbEpochs = len(gtf))
    for line in gtf :
        chroN = line['seqname']
        pBar.update(label = "Chr %s" % chroN)
        
        if (chroN.upper() in chroSet or chroN.lower() in chroSet):
            strand = line['strand']
            gene_biotype = line['gene_biotype']
            regionType = line['feature']
            frame = line['frame']

            start = int(line['start']) - 1
            end = int(line['end'])
            if start > end :
                start, end = end, start

            chroNumber = chroN.upper()
            if chroNumber not in store.chromosomes :
                store.chromosomes[chroNumber] = Chromosome_Raba()
                store.chromosomes[chroNumber].set(genome = genome, number = chroNumber)
            
            try :
                geneId = line['gene_id']
                geneName =  line['gene_name']
            except KeyError :
                geneId = None
                geneName = None
                if verbose :
                    printf('Warning: no gene_id/name found in line %s' % gtf[i])
            
            if geneId is not None :
                if geneId not in store.genes :
                    if len(store.genes) > batchSize :
                        store.batch_save()
                    
                    if verbose > 0 :
                        printf('\tGene %s, %s...' % (geneId, geneName))
                    store.genes[geneId] = Gene_Raba()
                    store.genes[geneId].set(genome = genome, id = geneId, chromosome = store.chromosomes[chroNumber], name = geneName, strand = strand, biotype = gene_biotype)
                if start < store.genes[geneId].start or store.genes[geneId].start is None :
                        store.genes[geneId].start = start
                if end > store.genes[geneId].end or store.genes[geneId].end is None :
                    store.genes[geneId].end = end
            try :
                transId = line['transcript_id']
                transName = line['transcript_name']
                try :
                    transcript_biotype = line['transcript_biotype']
                except KeyError :
                    transcript_biotype = None
            except KeyError :
                transId = None
                transName = None
                if verbose > 2 :
                    printf('\t\tWarning: no transcript_id, name found in line %s' % gtf[i])
            
            if transId is not None :
                if transId not in store.transcripts :
                    if verbose > 1 :
                        printf('\t\tTranscript %s, %s...' % (transId, transName))
                    store.transcripts[transId] = Transcript_Raba()
                    store.transcripts[transId].set(genome = genome, id = transId, chromosome = store.chromosomes[chroNumber], gene = store.genes.get(geneId, None), name = transName, biotype=transcript_biotype)
                if start < store.transcripts[transId].start or store.transcripts[transId].start is None:
                    store.transcripts[transId].start = start
                if end > store.transcripts[transId].end or store.transcripts[transId].end is None:
                    store.transcripts[transId].end = end
            
                try :
                    protId = line['protein_id']
                except KeyError :
                    protId = None
                    if verbose > 2 :
                        printf('Warning: no protein_id found in line %s' % gtf[i])

                # Store selenocysteine positions in transcript
                if regionType == 'Selenocysteine':
                    store.transcripts[transId].selenocysteine.append(start)
                        
                if protId is not None and protId not in store.proteins :
                    if verbose > 1 :
                        printf('\t\tProtein %s...' % (protId))
                    store.proteins[protId] = Protein_Raba()
                    store.proteins[protId].set(genome = genome, id = protId, chromosome = store.chromosomes[chroNumber], gene = store.genes.get(geneId, None), transcript = store.transcripts.get(transId, None), name = transName)
                    store.transcripts[transId].protein = store.proteins[protId]

                try :
                    exonNumber = int(line['exon_number']) - 1
                    exonKey = (transId, exonNumber)
                except KeyError :
                    exonNumber = None
                    exonKey = None
                    if verbose > 2 :
                        printf('Warning: no exon number or id found in line %s' % gtf[i])
                
                if exonKey is not None :
                    if verbose > 3 :
                        printf('\t\t\texon %s...' % (exonId))
                    
                    if exonKey not in store.exons and regionType == 'exon' :
                        store.exons[exonKey] = Exon_Raba()
                        store.exons[exonKey].set(genome = genome, chromosome = store.chromosomes[chroNumber], gene = store.genes.get(geneId, None), transcript = store.transcripts.get(transId, None), protein = store.proteins.get(protId, None), strand = strand, number = exonNumber, start = start, end = end)
                        store.transcripts[transId].exons.append(store.exons[exonKey])
                    
                    try :
                        store.exons[exonKey].id = line['exon_id']
                    except KeyError :
                        pass
                    
                    if regionType == 'exon' :
                        if start < store.exons[exonKey].start or store.exons[exonKey].start is None:
                            store.exons[exonKey].start = start
                        if end > store.transcripts[transId].end or store.exons[exonKey].end is None:
                            store.exons[exonKey].end = end
                    elif regionType == 'CDS' :
                        store.exons[exonKey].CDS_start = start
                        store.exons[exonKey].CDS_end = end
                        store.exons[exonKey].frame = frame
                    elif regionType == 'stop_codon' :
                        if strand == '+' :
                            if store.exons[exonKey].CDS_end != None :
                                store.exons[exonKey].CDS_end += 3
                                if store.exons[exonKey].end < store.exons[exonKey].CDS_end :
                                    store.exons[exonKey].end = store.exons[exonKey].CDS_end
                                if store.transcripts[transId].end < store.exons[exonKey].CDS_end :
                                    store.transcripts[transId].end = store.exons[exonKey].CDS_end
                                if store.genes[geneId].end < store.exons[exonKey].CDS_end :
                                    store.genes[geneId].end = store.exons[exonKey].CDS_end
                        if strand == '-' :
                            if store.exons[exonKey].CDS_start != None :
                                store.exons[exonKey].CDS_start -= 3
                                if store.exons[exonKey].start > store.exons[exonKey].CDS_start :
                                    store.exons[exonKey].start = store.exons[exonKey].CDS_start
                                if store.transcripts[transId].start > store.exons[exonKey].CDS_start :
                                    store.transcripts[transId].start = store.exons[exonKey].CDS_start
                                if store.genes[geneId].start > store.exons[exonKey].CDS_start :
                                    store.genes[geneId].start = store.exons[exonKey].CDS_start
    pBar.close()
    
    store.batch_save()
    
    conf.db.beginTransaction()
    printf('almost done saving chromosomes...')
    store.save_chros()
    
    printf('saving genome object...')
    genome.save()
    conf.db.endTransaction()
    
    conf.db.beginTransaction()
    printf('restoring core indexes...')
    # Genome.ensureGlobalIndex(('name', 'species'))
    # Chromosome.ensureGlobalIndex('genome')
    # Gene.ensureGlobalIndex('genome')
    # Transcript.ensureGlobalIndex('genome')
    # Protein.ensureGlobalIndex('genome')
    # Exon.ensureGlobalIndex('genome')
    Transcript.ensureGlobalIndex('exons')
    
    printf('commiting changes...')
    conf.db.endTransaction()
    
    conf.db.beginTransaction()
    printf('restoring user indexes')
    pBar = ProgressBar(label = "restoring", nbEpochs = len(indexes))
    for idx in indexes :
        pBar.update()
        conf.db.execute(idx[-1].replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS'))
    pBar.close()
    
    printf('commiting changes...')
    conf.db.endTransaction()
    
    return store.chromosomes.values()