package consensus; import java.io.Serializable; import java.util.Arrays; import aligner.Aligner; import aligner.AlignmentResult; import aligner.FlatAligner2; import dna.AminoAcid; import prok.GeneCaller; import shared.KillSwitch; import shared.Tools; import shared.TrimRead; import stream.FASTQ; import stream.Read; import structures.ByteBuilder; import structures.IntList; /** * A graph of the possible alignments of a reference sequence. * * @author Brian Bushnell * @date September 6, 2019 * */ public class BaseGraph extends ConsensusObject implements Serializable { /** * */ private static final long serialVersionUID = 3000198119165515066L; /*--------------------------------------------------------------*/ /*---------------- Initialization ----------------*/ /*--------------------------------------------------------------*/ public BaseGraph(String name_, byte[] bases_, byte[] quals_, long numericID_, int pad_){ name=name_; pad=pad_; original=pad(bases_, pad, (byte)'N'); refWeights=makeWeightsFromQual(quals_); numericID=numericID_; ref=new BaseNode[original.length]; del=new BaseNode[original.length]; for(int i=0; i=ref.length) : rpos+", "+ref.length+", "+r.start+"\n"+new String(bases)+"\n"+new String(original)+"\n"+new String(match); next=null; q=(quals==null ? fakeQuality : quals[qpos]); qpos++; rpos++; }else{ next=null; q=1; assert(false) : Character.toString((char)m)+"\n"+new String(match)+"\n"+r.id; } if(next!=null && qpos>=leftBorder && qpos<=maxQpos){ assert(qpos>=leftBorder && qpos<=maxQpos):qpos+", "+leftBorder+", "+maxQpos+", "+r.length(); // System.err.println("Adding "+Character.toString(b)+" to "+next); int weight=q+1; if(useMapq){ weight=(int)(Math.ceil(Math.sqrt(q*mapq))); } if(invertIdentity){ weight=weight+Tools.max(0, identityCeiling-identity); } synchronized(next){ next.add(b, weight); } } prevNode=next; prevState=m; } synchronized(this){ readTotal++; baseTotal+=bases.length; symbolTotal+=match.length; msTotal+=msSum; insTotal+=insSum; delTotal+=delSum; qualTotal+=qualSum; } } /** * Generates a score indicating how well the alignment matches the model. * Scores range from 1 to -1 times the alignment length; a random sequence * might be around 0. Less-conserved models result in lower scores, * even for optimally-matching alignments. * A relative score divides by the alignment length. */ public float scoreOld(Read r, boolean local, boolean relative){ float sum=0; float minSum=0; float maxSum=0; float peak=0; float minPeak=0; float maxPeak=0; // new Exception().printStackTrace(); r.toLongMatchString(false); final byte[] match=r.match; final byte[] bases=r.bases; assert(match!=null && bases!=null); final int start=r.start; int qpos=0, rpos=start; byte prevState='?'; BaseNode prevNode=(rpos<=0 ? null : ref[rpos-1]); int msSum=0; int delSum=0; int insSum=0; for(int mpos=0; mpospeak){ peak=sum; minPeak=minSum; maxPeak=maxSum; } } } boolean oldMode=false; if(oldMode){ float score=local ? peak : sum; int length=msSum+delSum+insSum; return relative ? (1+(score/length))*0.5f : score;//Relative score does not play well with local alignments }else{ // System.err.println(minSum+", "+maxSum+", "+sum); float a=local ? peak : sum; float b=local ? minPeak : minSum; float c=local ? maxPeak : maxSum; return relative ? (a-b)/(c-b) : a; //This changes to a 0-1 scale of worst to best possible alignment } } /** * Generates a score indicating how well the alignment matches the model. * Scores range from 1 to -1 times the alignment length; a random sequence * might be around 0. Less-conserved models result in lower scores, * even for optimally-matching alignments. * A relative score divides by the alignment length. */ public float score(Read r, boolean local, boolean relative){ float sum=0; float minSum=0; float maxSum=0; float peak=0; float minPeak=0; float maxPeak=0; // new Exception().printStackTrace(); r.toLongMatchString(false); final byte[] match=r.match; final byte[] bases=r.bases; assert(match!=null && bases!=null); final int start=r.start; int qpos=0, rpos=start; byte prevState='?'; BaseNode prevNode=(rpos<=0 ? null : ref[rpos-1]); int msSum=0; int delSum=0; int insSum=0; for(int mpos=0; mpospeak){ peak=sum; minPeak=minSum; maxPeak=maxSum; } } } boolean oldMode=false; if(oldMode){ float score=local ? peak : sum; int length=msSum+delSum+insSum; return relative ? (1+(score/length))*0.5f : score;//Relative score does not play well with local alignments }else{ // System.err.println(minSum+", "+maxSum+", "+sum); float a=local ? peak : sum; float b=local ? minPeak : minSum; float c=local ? maxPeak : maxSum; return relative ? (a-b)/(c-b) : a; //This changes to a 0-1 scale of worst to best possible alignment } } /** Count of alignments over this reference position. */ int countSum(int rpos){ assert(rpos>=0 && rpos=ref.length){return 0;} BaseNode dnode=del[rpos]; BaseNode rnode=ref[rpos]; int sum=(dnode==null ? 0 : dnode.countSum)+(rnode==null ? 0 : rnode.countSum); return sum; } @Override public ByteBuilder toText() { System.err.println("..."); ByteBuilder bb=new ByteBuilder(); bb.append(name).append(':'); bb.append('{'); if(ref.length>0){bb.append(ref[0].toText());} for(int i=0; i0){bb.comma();} bb.append(ref[i].toText()); } bb.append('}'); return bb; } int maxDepth(){ int maxDepth=0; for(int i=0; i=dw || daf=(weightSum-inode.weightSum) && inode.countSum*afMult>=MAF_ins){ inode.consensus(temp); byte b=temp[0]; byte q=temp[1]; assert(b!='.') : inode+", "+inode.weightSum+", "+weightSum; bb.append(b); depthList.add(depth); // System.err.println(i+": "+Character.toString(b)); if(qualityByMS){ byte quality=(byte)Tools.mid(2, 41, Math.round(39*inode.alleleDif())); bq.append(quality); }else{ double quality=Tools.mid(2, 41, 10*Math.log10(inode.weightSum/(rw+dw))); bq.append((byte)(Tools.min(q, quality)+FASTQ.ASCII_OFFSET)); } insCount++; inode=inode.insEdge; } }else{ //Deletion, do nothing delCount++; } } Read r=new Read(bb.toBytes(), bq.toBytes(), name, numericID); if(trimDepthFraction>0 || trimNs){ final int trimDepth=Tools.max(1, (int)(trimDepthFraction*maxDepth)); int left=0, right=0; while(left0 || right>0){ TrimRead.trimByAmount(r, left, right, 1); } // System.err.println(left+", "+right); } return r; } public void makeWeights() { refWeights=new float[ref.length]; // insWeights=new float[ref.length]; // delWeights=new float[ref.length]; for(int i=0; i=ar1.ratio ? ar0 : ar1); return ar==null ? -1 : ar==ar0 ? 0 : 1; } /** Generates match string and returns identity */ public float alignAndGenerateMatch(Read r, Aligner ssa){ return alignAndGenerateMatch(r, ssa, false, -1); } /** Generates match string and returns identity */ public float alignAndGenerateMatch(Read r, Aligner ssa, boolean findOrientation, float minRatio){ if(findOrientation){ int orientation=findBestOrientation(r, minRatio); if(orientation<0){return 0;} else if(orientation==1){ r.reverseComplement(); r.setStrand(r.strand()^1); } } if(ssa==null){ssa=GeneCaller.getSSA();} byte[] query=r.bases; int a=0, b=ref.length-1; int[] max=ssa.fillUnlimited(query, original, a, b, -9999); if(max==null){return 0;} final int rows=max[0]; final int maxCol=max[1]; final int maxState=max[2]; final byte[] match=ssa.traceback(query, original, a, b, rows, maxCol, maxState); int[] score=ssa.score(query, original, a, b, rows, maxCol, 0); r.match=match; r.start=score[1]; r.stop=score[2]; r.setMapped(true); final float identity=Read.identity(match); return identity; } void calcProbs(){ for(BaseNode n : ref){ for(BaseNode i=n; i!=null; i=i.insEdge){ i.calcProbs(); } } } // void makeWeights(){ //// assert(insWeights==null); //// refWeights=new float[ref.length]; // insWeights=new float[ref.length]; // delWeights=new float[ref.length]; //// Arrays.fill(refWeights, 1f); // Arrays.fill(insWeights, 1f); // Arrays.fill(delWeights, 1f); // } /*--------------------------------------------------------------*/ /*---------------- Fields ----------------*/ /*--------------------------------------------------------------*/ public long readTotal; public long baseTotal; public long symbolTotal; public long msTotal; public long insTotal; public long delTotal; public long qualTotal; public int subCount=0; public int refCount=0; public int delCount=0; public int insCount=0; /*--------------------------------------------------------------*/ /*---------------- Final Fields ----------------*/ /*--------------------------------------------------------------*/ public final String name; public final byte[] original; public final long numericID; public final int pad; //For ref nodes, calculate total outgoing weight. //Choose ins only if it is plurality allele. (or alternatively, majority allele). //But return to ref once it is no longer the majority/plurality of the outgoing weight. public final BaseNode[] ref; public final BaseNode[] del; //Original weights corresponding to conservation of sequence //This is for alignment, not scoring or updating, and is a simplified version of the graph //based on quality scores. public float[] refWeights; // public float[] insWeights; // public float[] delWeights; /*--------------------------------------------------------------*/ /*---------------- Static Fields ----------------*/ /*--------------------------------------------------------------*/ public static final BaseNode dummy=new BaseNode('.', INS, 0); public static byte fakeQuality=15; public static boolean qualityByMS=true; }