Get the CDS position mapped onto the chromosome position

@param exonStarts
@param exonEnds
@param cdsStart
@param cdsEnd
@return
323959
public static ChromPos getChromPosForward(int cdsPos, List<Integer> exonStarts, List<Integer> exonEnds, int cdsStart, int cdsEnd) {
		boolean inCoding = false;
		int codingLength = 0;

		@SuppressWarnings("unused")
		int lengthExons = 0;
		// map forward
		for (int i = 0; i < exonStarts.size(); i++) {

			// start can include UTR
			int start = exonStarts.get(i);
			int end = exonEnds.get(i);

			lengthExons += end - start;

			if (start <= cdsStart +1 && end >= cdsStart+1) {
				// first exon with UTR
				if (codingLength + (end - cdsStart-1) >= cdsPos) {
					// we are reaching our target position
					int tmp = cdsPos - codingLength;


					logger.debug(cdsStart + " | " + codingLength + " | " + tmp);
					logger.debug(" -> found position in UTR exon:  #"+(i+1)+ " cdsPos:" + cdsPos +
							" return:"+(cdsStart +1 + tmp) +" start:" + format(start + 1) + " " + format(tmp) + " " + cdsStart + " " + codingLength);

					// we start 1 after cdsStart...
					return new ChromPos((cdsStart +1 + tmp),-1);
				}
				inCoding = true;
				codingLength += (end - cdsStart);

				logger.debug("     UTR         : " + format(start+1) + " - " + (cdsStart ));
				logger.debug(" ->  Exon        : " + format(cdsStart+1) + " - " + format(end) + " | " + format(end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3));

			} else if (start+1 <= cdsEnd && end >= cdsEnd) {
				// LAST EXON with UTR
				//logger.debug(" <-- CDS end at: " + cdsEnd );
				inCoding = false;
				if (codingLength + (cdsEnd - start-1) >= cdsPos) {
					int tmp = cdsPos - codingLength;

					logger.debug(" <-  Exon        : " + format(start+1) + " - " + format(cdsEnd) + " | " + format(cdsEnd - start) + " | " + codingLength + " | " + (codingLength % 3));
					logger.debug("     UTR         : " + format(cdsEnd + 1) + " - " + format(end));
					logger.debug( codingLength + " | " + tmp + " | " + format(start+1));
					logger.debug(" -> chromPosForward found position in non coding exon:  " + cdsPos + " " + format(start+1) + " " + format(tmp) + " " + format(cdsStart) + " " + codingLength);

					return new ChromPos((start +1 + tmp),cdsPos%3);
				}
				codingLength += (cdsEnd - start-1);

				logger.debug(" <-  Exon        : " + format(start+1) + " - " + format(cdsEnd) + " | " + format(cdsEnd - start) + " | " + codingLength + " | " + (codingLength % 3));
				logger.debug("     UTR         : " + format(cdsEnd + 1) + " - " + format(end));


			} else if (inCoding) {
				// A standard coding Exon
				// tests for the maximum length of this coding exon
				if (codingLength + (end - start -1)  >= cdsPos) {

					// we are within the range of this exon
					int tmp = cdsPos - codingLength ;

					logger.debug("     Exon        : " + format(start+1) + " - " + format(end) + " | " + format(end - start) + " | " + tmp + " | " + codingLength);
					logger.debug(" -> found chr position in coding exon #" + (i+1) + ":  cdsPos:" + format(cdsPos) + " s:" + format(start) + "-" + format(end) + " tmp:" + format(tmp) + " cdsStart:" + format(cdsStart) + " codingLength:" + codingLength);

					return new ChromPos((start +1 + tmp),cdsPos%3);
				}
				// full exon is coding
				codingLength += (end - start );

				logger.debug("     Exon        : " + format(start+1) + " - " + format(end) + " | " + format(end - start) + " | " + codingLength + " | " + (codingLength % 3));
			}
		}
		return new ChromPos(-1,-1);
	}
1149171
def c_to_n(self, c_interval):
        """"""

        if self.cds_start_i is None:    # cds_start_i defined iff cds_end_i defined; see assertion above
            raise HGVSUsageError(
                "CDS is undefined for {self.tx_ac}; cannot map from c. coordinate (non-coding transcript?)"
                .format(self=self))

        # start
        if c_interval.start.datum == Datum.CDS_START and c_interval.start.base < 0:
            rs = c_interval.start.base + self.cds_start_i + 1
        elif c_interval.start.datum == Datum.CDS_START and c_interval.start.base > 0:
            rs = c_interval.start.base + self.cds_start_i
        elif c_interval.start.datum == Datum.CDS_END:
            rs = c_interval.start.base + self.cds_end_i
        # end
        if c_interval.end.datum == Datum.CDS_START and c_interval.end.base < 0:
            re = c_interval.end.base + self.cds_start_i + 1
        elif c_interval.end.datum == Datum.CDS_START and c_interval.end.base > 0:
            re = c_interval.end.base + self.cds_start_i
        elif c_interval.end.datum == Datum.CDS_END:
            re = c_interval.end.base + self.cds_end_i

        if rs <= 0 or re > self.tgt_len:
            raise HGVSError("The given coordinate is outside the bounds of the reference sequence.")

        n_interval = hgvs.location.BaseOffsetInterval(
            start=hgvs.location.BaseOffsetPosition(
                base=rs, offset=c_interval.start.offset, datum=Datum.SEQ_START),
            end=hgvs.location.BaseOffsetPosition(
                base=re, offset=c_interval.end.offset, datum=Datum.SEQ_START),
            uncertain=c_interval.uncertain)
        return n_interval
670651
Map<String, DefineInfo> collectDefines(Node externs, Node root) {
    GlobalNamespace namespace = null;
    if (namespaceSupplier != null) {
      namespace = namespaceSupplier.get();
    }
    if (namespace == null) {
      namespace = new GlobalNamespace(compiler, externs, root);
    }

    // namespace =
    //     namespaceSupplier != nul
    //         ? namespaceSupplier.get()
    //         : new GlobalNamespace(compiler, externs, root);

    // Find all the global names with a @define annotation
    List<Name> listOfDefines = new ArrayList<>();
    for (Name name : namespace.getNameIndex().values()) {
      Ref decl = name.getDeclaration();
      if (name.getJSDocInfo() != null && name.getJSDocInfo().isDefine()) {
        // Process defines should not depend on check types being enabled,
        // so we look for the JSDoc instead of the inferred type.
        if (isValidDefineType(name.getJSDocInfo().getType())) {
          listOfDefines.add(name);
        } else {
          JSError error = JSError.make(decl.getNode(), INVALID_DEFINE_TYPE_ERROR);
          compiler.report(error);
        }
      } else {
        for (Ref ref : name.getRefs()) {
          if (ref == decl) {
            // Declarations were handled above.
            continue;
          }

          Node n = ref.getNode();
          Node parent = ref.getNode().getParent();
          JSDocInfo info = n.getJSDocInfo();
          if (info == null && parent.isVar() && parent.hasOneChild()) {
            info = parent.getJSDocInfo();
          }

          if (info != null && info.isDefine()) {
            listOfDefines.add(name);
            break;
          }
        }
      }
    }

    CollectDefines pass = new CollectDefines(namespace, listOfDefines);
    NodeTraversal.traverseRoots(compiler, pass, externs, root);
    return pass.allDefines;
  }
1251760
public final boolean getSet(char src[], int srcStart) {
        // leave most argument checking up to Java exceptions
        array=null;
        arrayOffset=bmpLength=length=0;

        length=src[srcStart++];
        
        if ((length&0x8000) != 0) {
            /* there are supplementary values */
            length&=0x7fff;
            if(src.length<(srcStart+1+length)) {
                length=0;
                throw new IndexOutOfBoundsException();
            }
            bmpLength=src[srcStart++];
        } else {
            /* only BMP values */
            if(src.length<(srcStart+length)) {
                length=0;
                throw new IndexOutOfBoundsException();
            }
            bmpLength=length;
        }
        array = new char[length];
        System.arraycopy(src,srcStart,array,0,length);
        //arrayOffset=srcStart;
        return true;
    }
1029252
private static boolean isStartWith(String testString, String[] targetStrings) {
        for (String s : targetStrings) {
            if (testString.startsWith(s)) {
                return true;
            }
        }

        return false;
    }
1187796
private String getSphereCode(List<TreeNode> sphereNodes) throws CDKException {
        if (sphereNodes == null || sphereNodes.size() < 1) {
            return sphereDelimiters[sphere - 1];
        }
        TreeNode treeNode = null;
        StringBuffer code = new StringBuffer();
        /*
         * append the tree node code to the HOSECode in their now determined
         * order, using commas to separate nodes from different branches
         */
        IAtom branch = sphereNodes.get(0).source.atom;
        StringBuffer tempCode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = sphereNodes.get(i);
            tempCode = new StringBuffer();
            if (!treeNode.source.stopper && !treeNode.source.atom.equals(branch)) {
                branch = treeNode.source.atom;
                code.append(',');
            }

            if (!treeNode.source.stopper && treeNode.source.atom.equals(branch)) {
                if (treeNode.bondType <= 4) {
                    tempCode.append(bondSymbols[(int) treeNode.bondType]);
                } else {
                    throw new CDKException("Unknown bond type");
                }
                if (treeNode.atom != null && !treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append(getElementSymbol(treeNode.symbol));
                } else if (treeNode.atom != null && treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append('&');
                    treeNode.stopper = true;
                }
                code.append(tempCode + createChargeCode(treeNode.atom));
                treeNode.hSymbol = tempCode.toString();
            }
            if (treeNode.atom != null) treeNode.atom.setFlag(CDKConstants.VISITED, true);
            if (treeNode.source.stopper) treeNode.stopper = true;
        }
        code.append(sphereDelimiters[sphere - 1]);
        return code.toString();
    }
4460
public int getMinStartPosition(int docId, int position) throws IOException {
    if (ignoreSpans != null && docId == currentDocId) {
      if (position < minimumPosition) {
        throw new IOException(
            "Unexpected position, should be >= " + minimumPosition + "!");
      } else {
        computeFullStartPositionMinimum(position);
        if (minFullStartPosition.containsKey(position)) {
          return minFullStartPosition.get(position);
        } else {
          return 0;
        }
      }
    } else {
      return 0;
    }
  }
1003661
@SuppressWarnings("unchecked")
	public static <T> T[] flip(final T[] src, T[] dest, final int start, final int length)
	{
		if (dest == null || dest.length < length)
			dest = (T[]) Array.newInstance(src.getClass().getComponentType(), length);

		int srcIndex = start + length;
		for (int i = 0; i < length; i++)
		{
			dest[i] = src[--srcIndex];
		}

		return dest;
	}
298556
def CDSReader( fh, format='gff' ):
    

    known_formats = ( 'gff', 'gtf', 'bed')
    if format not in known_formats: 
        print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr)
        raise Exception('?')

    if format == 'bed':
        for line in fh:    
            f = line.strip().split()
            chrom = f[0]
            chrom_start = int(f[1])
            name = f[4]
            strand = f[5]
            cdsStart = int(f[6])
            cdsEnd = int(f[7])
            blockCount = int(f[9])
            blockSizes = [ int(i) for i in f[10].strip(',').split(',') ]
            blockStarts = [ chrom_start + int(i) for i in f[11].strip(',').split(',') ]

            # grab cdsStart - cdsEnd
            cds_exons = []
            cds_seq = ''
            genome_seq_index = []
            for base,offset in zip( blockStarts, blockSizes ):
                if (base + offset) < cdsStart: continue
                if base > cdsEnd: continue
                exon_start = max( base, cdsStart )
                exon_end = min( base+offset, cdsEnd ) 
                cds_exons.append( (exon_start, exon_end) )
            

    genelist = {}
    grouplist = []
    if format == 'gff' or format == 'gtf':
        for line in fh:
            if line.startswith('#'): continue
            fields = line.strip().split('\t')
            if len( fields ) < 9: continue
            if fields[2] not in ('CDS', 'stop_codon', 'start_codon'): continue

            # fields

            chrom = fields[0]
            ex_st = int( fields[3] ) - 1 # make zero-centered
            ex_end = int( fields[4] ) #+ 1 # make exclusive
            strand = fields[6]

            if format == 'gtf':
                group = fields[8].split(';')[0]
            else:
                group = fields[8]

            if group not in grouplist: grouplist.append( group )
            if group not in genelist:
                genelist[group] = (chrom, strand, [])
            
            genelist[group][2].append( ( ex_st, ex_end ) )

        sp = lambda a,b: cmp( a[0], b[0] )

        #for gene in genelist.values():
        for gene in grouplist:
            chrom, strand, cds_exons = genelist[ gene ]
            seqlen = sum([ a[1]-a[0] for a in cds_exons ])
            overhang = seqlen % 3
            if overhang > 0:
                #print >>sys.stderr, "adjusting ", gene  
                if strand == '+': 
                    cds_exons[-1] = ( cds_exons[-1][0], cds_exons[-1][1] - overhang )
                else:
                    cds_exons[0] = ( cds_exons[0][0] + overhang, cds_exons[0][1] )
            cds_exons = bitset_union( cds_exons )
            yield chrom, strand, cds_exons, gene
896131
public int getEndPosition(Tree node) {
    JCCompilationUnit compilationUnit = (JCCompilationUnit) getPath().getCompilationUnit();
    if (compilationUnit.endPositions == null) {
      return -1;
    }
    return ((JCTree) node).getEndPosition(compilationUnit.endPositions);
  }
1115463
static Positions newDisjointPositions(Matches matches) {
		if (matches == null) throw new IllegalArgumentException("null matches");
		return new BitStorePositions(matches, true, 0);
	}
325315
def iosequence(seq):
        
        lines = Lines()
        lines.add(1, 'cdef public bint _%s_diskflag' % seq.name)
        lines.add(1, 'cdef public str _%s_path' % seq.name)
        lines.add(1, 'cdef FILE *_%s_file' % seq.name)
        lines.add(1, 'cdef public bint _%s_ramflag' % seq.name)
        ctype = 'double' + NDIM2STR[seq.NDIM+1]
        lines.add(1, 'cdef public %s _%s_array' % (ctype, seq.name))
        return lines
63662
def coding_exons(self):
        
        # drop the trailing comma
        starts = (long(s) for s in self.exonStarts[:-1].split(","))
        ends = (long(s) for s in self.exonEnds[:-1].split(","))
        return [(s, e) for s, e in zip(starts, ends)
                                          if e > self.cdsStart and
                                             s < self.cdsEnd]
363141
public static int getStartPos(JCTree tree) {
        if (tree == null)
            return Position.NOPOS;

        switch(tree.getTag()) {
            case MODULEDEF: {
                JCModuleDecl md = (JCModuleDecl)tree;
                return md.mods.annotations.isEmpty() ? md.pos :
                       md.mods.annotations.head.pos;
            }
            case PACKAGEDEF: {
                JCPackageDecl pd = (JCPackageDecl)tree;
                return pd.annotations.isEmpty() ? pd.pos :
                       pd.annotations.head.pos;
            }
            case APPLY:
                return getStartPos(((JCMethodInvocation) tree).meth);
            case ASSIGN:
                return getStartPos(((JCAssign) tree).lhs);
            case BITOR_ASG: case BITXOR_ASG: case BITAND_ASG:
            case SL_ASG: case SR_ASG: case USR_ASG:
            case PLUS_ASG: case MINUS_ASG: case MUL_ASG:
            case DIV_ASG: case MOD_ASG:
            case OR: case AND: case BITOR:
            case BITXOR: case BITAND: case EQ:
            case NE: case LT: case GT:
            case LE: case GE: case SL:
            case SR: case USR: case PLUS:
            case MINUS: case MUL: case DIV:
            case MOD:
            case POSTINC:
            case POSTDEC:
                return getStartPos(((JCOperatorExpression) tree).getOperand(LEFT));
            case CLASSDEF: {
                JCClassDecl node = (JCClassDecl)tree;
                if (node.mods.pos != Position.NOPOS)
                    return node.mods.pos;
                break;
            }
            case CONDEXPR:
                return getStartPos(((JCConditional) tree).cond);
            case EXEC:
                return getStartPos(((JCExpressionStatement) tree).expr);
            case INDEXED:
                return getStartPos(((JCArrayAccess) tree).indexed);
            case METHODDEF: {
                JCMethodDecl node = (JCMethodDecl)tree;
                if (node.mods.pos != Position.NOPOS)
                    return node.mods.pos;
                if (node.typarams.nonEmpty()) // List.nil() used for no typarams
                    return getStartPos(node.typarams.head);
                return node.restype == null ? node.pos : getStartPos(node.restype);
            }
            case SELECT:
                return getStartPos(((JCFieldAccess) tree).selected);
            case TYPEAPPLY:
                return getStartPos(((JCTypeApply) tree).clazz);
            case TYPEARRAY:
                return getStartPos(((JCArrayTypeTree) tree).elemtype);
            case TYPETEST:
                return getStartPos(((JCInstanceOf) tree).expr);
            case ANNOTATED_TYPE: {
                JCAnnotatedType node = (JCAnnotatedType) tree;
                if (node.annotations.nonEmpty()) {
                    if (node.underlyingType.hasTag(TYPEARRAY) ||
                            node.underlyingType.hasTag(SELECT)) {
                        return getStartPos(node.underlyingType);
                    } else {
                        return getStartPos(node.annotations.head);
                    }
                } else {
                    return getStartPos(node.underlyingType);
                }
            }
            case NEWCLASS: {
                JCNewClass node = (JCNewClass)tree;
                if (node.encl != null)
                    return getStartPos(node.encl);
                break;
            }
            case VARDEF: {
                JCVariableDecl node = (JCVariableDecl)tree;
                if (node.mods.pos != Position.NOPOS) {
                    return node.mods.pos;
                } else if (node.vartype == null) {
                    //if there's no type (partially typed lambda parameter)
                    //simply return node position
                    return node.pos;
                } else {
                    return getStartPos(node.vartype);
                }
            }
            case ERRONEOUS: {
                JCErroneous node = (JCErroneous)tree;
                if (node.errs != null && node.errs.nonEmpty())
                    return getStartPos(node.errs.head);
            }
        }
        return tree.pos;
    }
656350
private boolean includeInStartPosition(final int currentColumn, final int currentRow) {
        
        if(startColumn >=0 && startRow >= 0
                && currentColumn == startColumn && currentRow == startRow) {
            // 行と列の両方の指定がある場合
            return true;
            
        } else if(startColumn >= 0 && startRow < 0 && currentColumn == startColumn) {
            // 列の指定のみ
            return true;
            
        } else if(startColumn < 0 && startRow >= 0 && currentRow == startRow) {
            // 行の指定のみ
            return true;
            
        }
        
        return false;
        
    }
829562
function _extensionsToAsn1(exts) {
  // create top-level extension container
  var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);

  // create extension sequence (stores a sequence for each extension)
  var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  rval.value.push(seq);

  var ext, extseq;
  for(var i = 0; i < exts.length; ++i) {
    ext = exts[i];

    // create a sequence for each extension
    extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
    seq.value.push(extseq);

    // extnID (OID)
    extseq.value.push(asn1.create(
      asn1.Class.UNIVERSAL, asn1.Type.OID, false,
      asn1.oidToDer(ext.id).getBytes()));

    // critical defaults to false
    if(ext.critical) {
      // critical BOOLEAN DEFAULT FALSE
      extseq.value.push(asn1.create(
        asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
        String.fromCharCode(0xFF)));
    }

    var value = ext.value;
    if(typeof ext.value !== 'string') {
      // value is asn.1
      value = asn1.toDer(value).getBytes();
    }

    // extnValue (OCTET STRING)
    extseq.value.push(asn1.create(
      asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
  }

  return rval;
}
221566
int specialFind(int startPos, int position)
  {
          // We have to look all the way up the ancestor chain
          // to make sure we don't have an ancestor.
          int ancestor = startPos;
          while(ancestor > 0)
          {
                // Get the node whose index == ancestor
                ancestor*=slotsize;
                int chunkpos = ancestor >> lowbits;
                int slotpos = ancestor & lowmask;
                int[] chunk = chunks.elementAt(chunkpos);
                                                        
                // Get that node's parent (Note that this assumes w[1]
                // is the parent node index. That's really a DTM feature
                // rather than a ChunkedIntArray feature.)
                ancestor = chunk[slotpos + 1];

                if(ancestor == position)
                         break;
          }

          if (ancestor <= 0) 
          {
                  return position;
          }
          return -1;
  }