//getResNum for the UV. public int getResidueNum(Vector2 uv) { int result; Debug.Log("Splitting.cs: getResidueNum(uv): " + uv); if (DNA_Panel == null) { DNA_Panel = DNAPanelController.Instance.DNA_Panel; } if (DNA_Panel.GetComponent <Renderer>().enabled) { if (seqModel == null) { seqModel = new SequenceModel(); } int DNASeqNum = DNAPanelController.Instance.getSeqPos(uv); string nuc = DNAPanelController.Instance.getNucAcidForUV(uv); Debug.Log("Pos: " + DNASeqNum + ", DNA: " + nuc + ", seqModel: " + seqModel); string nucStr = nuc.Split(':')[0]; //string niceName, int pos, Nuc n, Seq type int pos = seqModel.getPeptidePos("Rattus norvegicus", DNASeqNum, Nucleotide.StrToNuc(nucStr), Seq.DNA); // residueSeq[x].name; return(pos); } else { //do it Debug.Log("RNA panel"); } return(0); }
void OnTriggerExit(Collider other) { if (other.tag == "Nucleotide") { waiting = null; } }
public NucleotideCouple buildHalfCoupleChainFromOneSingle(Nucleotide chain) { if (chain.isPaired) { return(null); } chain = getHeadOfSingleChain(chain); Nucleotide nhead = chain; NucleotideCouple n = (Instantiate(couplePrefab) as GameObject).GetComponent <NucleotideCouple>(); NucleotideCouple head = n; n.setLeftColor(chain.getColor()); n.setType(chain.type, Nucleotide.Type.Empty); n.needHelix = false; while (chain.next) { chain = chain.next; n.next = (Instantiate(couplePrefab) as GameObject).GetComponent <NucleotideCouple>(); n.next.setLeftColor(chain.getColor()); n.next.setType(chain.type, Nucleotide.Type.Empty); n.next.prev = n; n.next.needHelix = false; n.next.transform.rotation = nhead.transform.rotation; n = n.next; } head.transform.rotation = nhead.transform.rotation; head.transform.position = nhead.transform.position; head.broadcastUpdateTransform(); destroySingleChain(chain); return(head); }
public static int[][] GetWeightMatrix(Nucleotide[][] map) { var w = new int[map.Length][]; for (int i = 0; i < map.Length; i++) w[i] = new int[map.Length]; if (map.Length < 100) { for (int i = 0; i < map.Length; i++) for (int j = 0; j < i; j++) { var a = Alignment.Align(map[i], map[j], i, j); w[i][j] = a.Weight; w[j][i] = a.Weight; } } else { Parallel.ForEach(Enumerable.Range(0, map.Length), new ParallelOptions {MaxDegreeOfParallelism = 8}, i => { for (int j = 0; j < i; j++) { var a = Align(map[i], map[j], i, j); w[i][j] = a.Weight; w[j][i] = a.Weight; } }); } return w; }
public BasicSmEncoding(string symbols, string name, MoleculeType moleculeType, bool hasGaps, bool hasAmbiguity, bool hasTerminations) { Name = name; HasGaps = hasGaps; HasAmbiguity = hasAmbiguity; HasTerminations = hasTerminations; // Load the symbols into items string trimmed = symbols.Trim().ToUpper(CultureInfo.InvariantCulture); // should be no leading or trailing whitespace, but why take chances? _symbols = new ISequenceItem[trimmed.Length]; byte i = 0; // index into mappings foreach (char c in trimmed) { if (moleculeType == MoleculeType.DNA || moleculeType == MoleculeType.RNA || moleculeType == MoleculeType.NA) { Nucleotide item = new Nucleotide(i, c, c.ToString()); _symbols[i] = item; _values.Add(c, item); } else if (moleculeType == MoleculeType.Protein) { AminoAcid item = new AminoAcid(i, c, c.ToString()); _symbols[i] = item; _values.Add(c, item); } i++; } }
/// <summary> /// Создаёт мотив по выровненным цепочкам. /// </summary> public static Motiff ExtractMotiff(Nucleotide[][] map, int[] mapFactor = null) { bool started = false; var len = map.Max(p => p.Length); var freq = new List<int[]>(); if (mapFactor == null) mapFactor = Enumerable.Repeat(1, map.Length).ToArray(); var cnt = mapFactor.Sum(); for (int i = 0; i < len; i++) { var tmp = new int[4]; for (int k = 0; k < map.Length; k++) { var m = map[k]; if (m.Length <= i || (int) m[i] > 3) continue; tmp[(int) m[i]] += mapFactor[k]; } if (!started) { if (tmp.Sum() > cnt / 2) started = true; else continue; } freq.Add(tmp); } var drop = freq.ToArray().Reverse().TakeWhile(p => p.Sum() < cnt / 2).Count(); freq.RemoveRange(freq.Count - drop, drop); return new Motiff(cnt, freq.ToArray(), new string(freq.Select(p => GetMaskChar(p, cnt)).ToArray())); }
public void BuildTexture() //, ParseDNA parseDNA) { //this.DNA_Model = parseDNA; { Debug.Log("inside build texture"); string[] val = DNA_Model.data[key]; string sequence = val[1]; var texture = new Texture2D(textureX, textureY, TextureFormat.BGRA32, true); GetComponent <Renderer>().material.mainTexture = texture; texture.SetPixel(textureX, textureY, Color.black); // mark the end of this texture. Debug.Log("sequence: " + sequence); for (int i = 0; i < sequence.Length; i++) { Nuc n = Nucleotide.CharToNuc(sequence[i]); texture.SetPixel(i % textureX, i / textureX, Nucleotide.defaultColor[n]); } texture.filterMode = FilterMode.Point; texture.Apply(); }
static void Main(string[] args) { /*MemoryCache.Default.Add( * "complement", new byte[] { * 0, 8, 4, 12, 2, * 10, 9, 14, 1, 6, * 5, 13, 3, 11, 7, 15 * }, new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable } * );*/ Stopwatch timer = Stopwatch.StartNew(); Nucleotide complement = Nucleotide.Zero; for (int i = 0; i < 1000; ++i) { for (byte j = 0; j < 16; ++j) { //complement = (byte)Constants.COMPLEMENTS[(Nucleotide)j]; //complement = ((byte[])MemoryCache.Default.Get("complement"))[j]; complement = (Nucleotide)bytes[j]; } } timer.Stop(); Console.WriteLine(timer.Elapsed); Console.WriteLine(timer.ElapsedMilliseconds); Console.WriteLine(timer.ElapsedTicks); Console.ReadLine(); }
public Style getStyle(Nucleotide nuc) { var index = nuc.value.lerp(0, Enum.GetValues(typeof(Style)).Length - 1); foreach (Style style in Enum.GetValues(typeof(Style))) { if ((int)style == Math.Floor(index)) { return(style); } } if (nuc.value <= .33) { return(Style.FillAndStroke); } else if (nuc.value <= .66 && nuc.value >= .34) { return(Style.Fill); } else { return(Style.Stroke); } }
public NucleotideCouple buildCoupleFromOneSingle(Nucleotide n, bool reverse = false) { if (n.isPaired) { return(null); } GameObject couple = Instantiate(couplePrefab) as GameObject; couple.transform.position = n.transform.position; couple.transform.rotation = n.transform.rotation; if (!reverse) { couple.gameObject.GetComponent <NucleotideCouple>().setType(n.type, getPairType(n.type)); Color c = n.getColor(); couple.gameObject.GetComponent <NucleotideCouple>().setLeftColor(c); couple.gameObject.GetComponent <NucleotideCouple>().setRightColor(Color.white); } else { couple.gameObject.GetComponent <NucleotideCouple>().setType(getPairType(n.type), n.type); Color c = n.getColor(); couple.gameObject.GetComponent <NucleotideCouple>().setRightColor(c); couple.gameObject.GetComponent <NucleotideCouple>().setLeftColor(Color.white); } couple.gameObject.GetComponent <NucleotideCouple>().tag = "NucleotideCouple"; Destroy(n.gameObject); return(couple.gameObject.GetComponent <NucleotideCouple>()); }
public float GetScore(Nucleotide[] nucs) { if (nucs.Length != Length) throw new ArgumentException("nucs.Len != " + Length); if (_cache == null) _cache = new ProbMotifCache(_data); var norm = _cache.NormFactor; var max = 0.0; foreach (var ds in _cache.DataInversions) { var cur = 1.0; for (int i = 0; i < Length; i++) { var nicId = (int)nucs[i]; var d = ds[i]; if (nicId < 4) cur *= d[nicId]; else if (nicId == (int) Nucleotide.Any) cur *= 0.1; else throw new NotSupportedException(); } if (cur > max) max = cur; } return (float)(max*norm); }
public void SparseSequenceClone() { SparseSequence sparseSeq = new SparseSequence(Alphabets.DNA); sparseSeq.Count = 50; sparseSeq[0] = Alphabets.DNA.C; sparseSeq[5] = Alphabets.DNA.G; sparseSeq[30] = Alphabets.DNA.C; sparseSeq[44] = Alphabets.DNA.A; sparseSeq[45] = new Nucleotide('A', "Nucleotide A"); CompoundNucleotide cn = new CompoundNucleotide('M', "Compound"); cn.Add(new Nucleotide('A', "Item A"), 30); cn.Add(new Nucleotide('C', "Item C"), 20); sparseSeq[46] = cn; Assert.AreEqual(sparseSeq.Count, 50); Assert.AreEqual(sparseSeq.Alphabet, Alphabets.DNA); Assert.AreSame(sparseSeq[0], Alphabets.DNA.C); Assert.AreSame(sparseSeq[5], Alphabets.DNA.G); Assert.AreSame(sparseSeq[30], Alphabets.DNA.C); Assert.AreSame(sparseSeq[44], Alphabets.DNA.A); Assert.AreEqual(sparseSeq[45].Symbol, 'A'); Assert.AreSame(sparseSeq[46], cn); Assert.AreNotSame(sparseSeq[46], Alphabets.DNA.AC); for (int i = 0; i < sparseSeq.Count; i++) { if (i != 0 && i != 5 && i != 30 && i != 44 && i != 45 && i != 46) { Assert.IsNull(sparseSeq[i]); } } SparseSequence sparseSeqClone = sparseSeq.Clone(); Assert.AreEqual(sparseSeqClone.Count, 50); Assert.AreEqual(sparseSeqClone.Alphabet, Alphabets.DNA); Assert.AreSame(sparseSeqClone[0], Alphabets.DNA.C); Assert.AreSame(sparseSeqClone[5], Alphabets.DNA.G); Assert.AreSame(sparseSeqClone[30], Alphabets.DNA.C); Assert.AreSame(sparseSeqClone[44], Alphabets.DNA.A); Assert.AreNotSame(sparseSeqClone[46], cn); Assert.AreNotSame(sparseSeqClone[46], Alphabets.DNA.AC); Assert.AreEqual(sparseSeqClone[46].Symbol, 'M'); cn = sparseSeqClone[46] as CompoundNucleotide; IList <ISequenceItem> sequenceItems = cn.SequenceItems; Assert.AreEqual(sequenceItems.Count, 2); Assert.IsTrue(sequenceItems.First(I => I.Symbol == 'A') != null); Assert.IsTrue(sequenceItems.First(I => I.Symbol == 'C') != null); for (int i = 0; i < sparseSeqClone.Count; i++) { if (i != 0 && i != 5 && i != 30 && i != 44 && i != 45 && i != 46) { Assert.IsNull(sparseSeqClone[i]); } } }
private void buildNucleotide() { Nucleotide n = (Instantiate(prefab) as GameObject).GetComponent <Nucleotide>(); n.setType(type); n.transform.position = this.transform.position; n.transform.rotation = this.transform.rotation; }
public float GetScore(Nucleotide[] nucs) { if(nucs.Length != Length) throw new ArgumentException("nucs.Len != " + Length); return _data.Select(ds => ds.Zip(nucs, (a, b) => (a == b || a == Nucleotide.Any) ? 1 : 0).Sum()) .Concat(new[] {0}) .Max()/(float)Length; }
/// <summary> /// Lookup an amino acid based on a triplet of nucleotides. U U U for instance /// will result in Phenylalanine. /// </summary> public static AminoAcid Lookup(Nucleotide n1, Nucleotide n2, Nucleotide n3) { StringBuilder source = new StringBuilder(); source.Append(n1.Symbol); source.Append(n2.Symbol); source.Append(n3.Symbol); return(codonMap[source.ToString()]); }
public StrictMotif(Nucleotide[] data) { Length = data.Length; _data = new Nucleotide[4][]; _data[0] = data; _data[1] = data.Reverse().ToArray(); _data[2] = data.Select(p => p.Inverse()).ToArray(); _data[3] = _data[2].Reverse().ToArray(); }
public virtual long NucleotideCount(Nucleotide nucleotide) { if (!AllowedSymbols.Contains(nucleotide)) { throw new ArgumentException(String.Format(InvalidNucleotideForAlphabetType, nucleotide, ActiveAlphabet)); } return(!SymbolCounts.ContainsKey(nucleotide) ? 0 : SymbolCounts[nucleotide]); }
public void setType(Nucleotide.Type t) { if (!this.attach) { this.attach = (Instantiate(nucleotidePrefab, this.transform.position, this.transform.rotation) as GameObject).GetComponent <Nucleotide>(); } this.attach.attach(); this.attach.setType(t); }
public static SuffixArray BuildOne(Nucleotide[] fragments) { var tmp = new byte[fragments.Length + 1]; for (int i = 0; i < fragments.Length; i++) tmp[i] = (byte)fragments[i]; tmp[tmp.Length - 1] = (byte)Nucleotide.End; var sfx = new SuffixArray(tmp); return sfx; }
void OnTriggerExit(Collider other) { if (this.attach && other.gameObject.GetComponent <Nucleotide>() == this.attach) { this.attach.detach(); this.attach = null; this.parent.detach(this); } }
public void cutPrev() { if (this.prev) { this.prev.nextBond.SetActive(false); this.prev.next = null; } this.prevBond.SetActive(false); this.prev = null; }
/// <summary> /// Indication of whether or not an ISequenceItem is in the encoding. This is /// a simple lookup and will only match exactly with items of this encoding. It /// will not compare items from other encodings that match the same nucleotide. /// </summary> public bool Contains(ISequenceItem item) { Nucleotide nucleo = item as Nucleotide; if (nucleo == null) { return(false); } return(values.Contains(nucleo)); }
public NucleotideCouple buildCoupleChainFromOneSingleAnimation(Nucleotide chain, float timeGap = 0.8F) { NucleotideCouple head = buildHalfCoupleChainFromOneSingle(chain); if (head == null) { return(null); } StartCoroutine(fillHalfCoupleChainRoutine(head, timeGap)); return(head); }
public Nucleotide getTailOfSingleChain(Nucleotide n) { Nucleotide tail = n; while (tail.next) { tail = tail.next; } return(tail); }
public Nucleotide getHeadOfSingleChain(Nucleotide n) { Nucleotide head = n; while (head.prev) { head = head.prev; } return(head); }
/// <summary> /// Выравнивание двух последовательностей. /// Учитывает перестановки A-T и G-C, а также реверсии. /// </summary> public static AlignmentResult Align(Nucleotide[] a0, Nucleotide[] b0, int id1 = 0, int id2 = 0) { var bestDir = Direction.Straight; var bestMask = string.Empty; int bestWeight = -1; int bestShift1 = 0; int bestShift2 = 0; var tmp = new StringBuilder(Math.Max(a0.Length, b0.Length)); foreach (Direction direction in Enum.GetValues(typeof(Direction))) { var a = a0; var b = b0.GetChain(direction); for (int s = 0; s < b.Length + a.Length - 1; s++) // s - смещение a относительно b { int w = 0; var sa = Math.Max(0, a.Length - s - 1); // откуда начинать отсчёт от a var sb = Math.Max(0, s + 1 - a.Length); // откуда начинать отсчёт от b var len = Math.Min(a.Length - sa, b.Length - sb); for (int i = 0; i < len; i++) // безим по смещённым последовательностям { var na = a[sa + i]; var nb = b[sb + i]; if (na == nb) { tmp.Append(na); w++; } else tmp.Append("?"); } if (w > bestWeight) { bestWeight = w; bestMask = tmp.ToString(); bestDir = direction; bestShift1 = sa; bestShift2 = sb; } tmp.Clear(); } } if (bestMask.StartsWith("?")) { var cnt = bestMask.TakeWhile(p => p == '?').Count(); bestShift1 += cnt; bestShift2 += cnt; bestMask = bestMask.Trim('?'); } else bestMask = bestMask.TrimEnd('?'); return new AlignmentResult(bestWeight, bestMask, bestDir, bestShift1, bestShift2, id1, id2); }
public void getResidueForUV(Vector2 uv) { Debug.Log("Splitting.cs: getResidueForUV(uv): " + uv); if (DNAPanelController.Instance.DNA_Panel == null) { //do it Debug.Log("RNA panel"); if (seqModel == null) { seqModel = new SequenceModel(); } int RNASeqNum = RNAPanelController.Instance.getSeqPos(uv); string nuc = RNAPanelController.Instance.getNucAcidForUV(uv); Debug.Log("Pos: " + RNASeqNum + ", RNA: " + nuc + ", seqModel: " + seqModel); string nucStr = nuc.Split(':')[0]; //string niceName, int pos, Nuc n, Seq type int num = seqModel.getPeptidePos("Rattus norvegicus", RNASeqNum, Nucleotide.StrToNuc(nucStr), Seq.RNA); Debug.Log("peptidePos: " + num); if (ProteinFocus != null) { GameObject.Destroy(ProteinFocus); } updateSplit(num); Residue r = residueSeq[num]; string resName = r.name; RNAPanelController.Instance.setSeqPos(resName); } else { if (DNAPanelController.Instance.DNA_Panel.GetComponent <Renderer>().enabled) { if (seqModel == null) { seqModel = new SequenceModel(); } int DNASeqNum = DNAPanelController.Instance.getSeqPos(uv); string nuc = DNAPanelController.Instance.getNucAcidForUV(uv); Debug.Log("Pos: " + DNASeqNum + ", DNA: " + nuc + ", seqModel: " + seqModel); string nucStr = nuc.Split(':')[0]; //string niceName, int pos, Nuc n, Seq type int num = seqModel.getPeptidePos("Rattus norvegicus", DNASeqNum, Nucleotide.StrToNuc(nucStr), Seq.DNA); Debug.Log("peptidePos: " + num); } } }
public string SingleChain2String(Nucleotide chain) { Nucleotide n = getHeadOfSingleChain(chain); string result = "1"; while (n) { result += Type2Char(n.type); n = n.next; } return(result); }
public void destroySingleChain(Nucleotide chain) { Nucleotide prev, head = getHeadOfSingleChain(chain); while (head) { prev = head; head = head.next; Destroy(prev.gameObject); } Debug.Log("Destroyed"); }
public int getLengthOfSingleChain(Nucleotide n) { Nucleotide head = getHeadOfSingleChain(n); int cnt = 1; while (n.next) { cnt += 1; n = n.next; } return(cnt); }
public int getResNum(int pos, Nuc n) { if (nucXaa.Count == 0) { AAConsensusNucList(); } Debug.Log("pos: " + pos); Debug.Log("nucXaa[0]: " + nucXaa[0]); Debug.Log(" nucXaa[0].Length: " + nucXaa[0].Length); string nuc = Char.ToString(nucXaa[0][pos]); if (Nucleotide.NucToStr(n).Equals(nuc)) //matches our data struct, implying correct alignment { return(pos / 3); } else { //something wrong //NOTE: it could be the case that the alignment went like so: // 012 345 678 9 // ATG | GAG | --- | GTA | GGT | //sequence mRNA // M | somehting | L | something | something //sequence according to 3D protein // ^ // therefore getResNum(6, G) now refers to ---, L. instead of G of the original pos 6. // such cases all fall into this branch. string _1stStr = nucXaa[0]; int numDashes = 0; for (int i = 0; i < pos; i++) { if (_1stStr[i].Equals('-')) { numDashes++; } if (i == pos - 1 && numDashes % 3 != 0) //eg : --- | -- - | { numDashes = ((numDashes / 3) + 1) * 3; // ^ } } Debug.Log("numDashes: " + numDashes); nuc = Char.ToString(nucXaa[0][pos + numDashes]); if (Nucleotide.NucToStr(n).Equals(nuc)) { return((pos + numDashes) / 3); } Debug.Log("residue can't be found in Consensus for the given seq position in RNA."); return(-1); } }
public bool addPrev(Nucleotide n) { if (n.next != null) { return(false); } n.nextBond.SetActive(true); n.next = this; this.prevBond.SetActive(true); this.prev = n; broadcastUpdateTransform(); return(true); }
public double CalcMaxScore(Nucleotide[] data, CalcMode? mode = null) { var ret = 0.0; foreach (Direction direction in Enum.GetValues(typeof (Direction))) { var b = data.GetChain(direction); for (int i = 0; i < data.Length - Length; i++) { var tmp = CalcScore(b, i, mode); if (tmp > ret) ret = tmp; } } return ret; }
void OnTriggerEnter(Collider other) { if (other.tag == "Nucleotide") { Nucleotide n = other.gameObject.GetComponent <Nucleotide>(); if (waiting) { NucleotideDirector.getInstance().buildCoupleChainFromTwoSingles(waiting, n, transform.position); waiting = null; } else { waiting = n; } } }
public static string NucleotideAbbrString(Nucleotide nuc) { switch (nuc) { case Nucleotide.Adenine: return("A"); case Nucleotide.Cytosine: return("C"); case Nucleotide.Guanine: return("G"); case Nucleotide.Thymine: return("T"); } return(""); }
public void updateTransform(Vector3 position, Quaternion rotation, Nucleotide from) { this.transform.position = position; this.transform.rotation = rotation; if (prev && from != prev) { Quaternion prevRotation = rotation; Vector3 prevPosition = position + rotation * Vector3.up * gap; prev.updateTransform(prevPosition, prevRotation, this); } if (next && from != next) { Quaternion nextRotation = rotation; Vector3 nextPosition = position + rotation * Vector3.down * gap; next.updateTransform(nextPosition, nextRotation, this); } }
public NucleotideCouple buildCoupleChainFromTwoSingles(Nucleotide c1, Nucleotide c2, Vector3 position = default(Vector3)) { if (c1.isPaired || c2.isPaired) { return(null); } if (getLengthOfSingleChain(c1) != getLengthOfSingleChain(c2)) { return(null); } c1 = getHeadOfSingleChain(c1); if (c1 == getHeadOfSingleChain(c2)) { return(null); } c2 = getTailOfSingleChain(c2); NucleotideCouple n = (Instantiate(couplePrefab) as GameObject).GetComponent <NucleotideCouple>(); NucleotideCouple head = n; n.setLeftColor(c1.getColor()); n.setRightColor(c2.getColor()); n.setType(c1.type, c2.type); while (c1.next) { c1 = c1.next; c2 = c2.prev; n.next = (Instantiate(couplePrefab) as GameObject).GetComponent <NucleotideCouple>(); n.next.setLeftColor(c1.getColor()); n.next.setRightColor(c2.getColor()); n.next.setType(c1.type, c2.type); n.next.prev = n; n = n.next; } head.transform.position = position; head.broadcastUpdateTransform(); destroySingleChain(c1); destroySingleChain(c2); return(n); }
//核苷酸之间氢键角度不知道怎么归位,deHelix先注释掉了 //public void deHelix(NucleotideCouple n) //{ // if(n.needHelix == true) // { // n.needHelix = false; // } //} public NucleotideCouple buildCoupleChainFromOneSingle(Nucleotide n, bool reverse = false) { if (n.isPaired) { return(null); } Nucleotide head = getHeadOfSingleChain(n); Nucleotide next = head.next; if (next == null) { return(buildCoupleFromOneSingle(head)); } else { NucleotideCouple coupleHead = buildCoupleFromOneSingle(head); NucleotideCouple couple = coupleHead; while (next.next) { next = next.next; couple.next = buildCoupleFromOneSingle(next.prev, reverse); couple.next.prev = couple; couple = couple.next; } couple.next = buildCoupleFromOneSingle(next); couple.next.prev = couple; if (!reverse) { coupleHead.broadcastUpdateTransform(); } else { couple.next.broadcastUpdateTransform(); } return(coupleHead); } }
/// <summary> /// Добавление прецедента в мотив. /// </summary> public void AddItem(Nucleotide[] nucs, int factor = 1) { if(nucs == null || nucs.Length != Length) throw new ArgumentException("nucs"); for (int i = 0; i < nucs.Length; i++) { var nucId = (int) nucs[i]; if (nucId < 4) { var d = _data[i]; d[nucId] += factor; d[4] += factor; } else if (nucId == (int) Nucleotide.Any) _data[i][4] += factor; else throw new NotSupportedException(); } _cache = null; }
public MultiAlignmentResult Align() { var parent = Nodes[0]; var directions = new Direction[Nodes.Length]; var shifts = new int[Nodes.Length]; var w = Alignment.GetWeightMatrix(Nodes.Select(p => p.NucleoChain).ToArray()); var baseId = w.FirstIndexWhereMax(a => a.Sum()); directions[baseId] = Direction.Straight; shifts[baseId] = 0; for (int i = 0; i < Nodes.Length; i++) { if(i == baseId) continue; var a = Alignment.Align(parent.NucleoChain, Nodes[i].NucleoChain); directions[i] = a.Direction; shifts[i] = a.Shift1 - a.Shift2; } var minShift = shifts.Min(); Debug.Assert(minShift <= 0); var map = new Nucleotide[Nodes.Length][]; var mapFactors = new int[Nodes.Length]; for (int i = 0; i < Nodes.Length; i++) { var s = shifts[i] -= minShift; var chain = Nodes[i].NucleoChain.GetChain(directions[i]); if (s > 0) chain = Enumerable.Repeat(Nucleotide.All, s).Concat(chain).ToArray(); map[i] = chain; mapFactors[i] = Nodes[i].Count; } return new MultiAlignmentResult(shifts, directions, map, mapFactors); }
public double CalcMaxScore(Nucleotide[] data, int startPos, int endPos, CalcMode? mode = null) { Debug.Assert(startPos > 0); var ret = 0.0; var end = Math.Min(data.Length - Length, endPos); for (int i = startPos; i < end; i++) { var tmp = CalcScore(data, i, mode); if (tmp > ret) ret = tmp; } return ret; }
/// <summary> /// Gets simple distance estimate for 2 nucleotides /// </summary> /// <param name="n1">The nucleotide 1.</param> /// <param name="n2">The nucleotide 2.</param> /// <returns>Distance estimate</returns> public override double NucleotideDistance(Nucleotide n1, Nucleotide n2) { return this.DistanceMap[new NucleotidePair(n1, n2)]; }
/// <summary> /// Вычисляет коэффициент близости. /// Степенной алгоритм: /// * Если задано All, то берёт наименее вероятный нуклеотид; /// * Если нуклеотид не встречался, то считает, что совпадения вообще нет. /// * Если в конкретной позиции при формировании распределения участвовали не все элементарные мотивы, то сокращает вклад степенным алгоритмом. /// </summary> /// <returns>1 - точное совпадение, 0 - отсутствие совпадения.</returns> public double CalcScoreDegree(Nucleotide[] data, int pos) { var ret = 1.0; if (pos < 0 || data.Length <= pos + Length) return 0; for (int i = 0; i < Length; i++) { var d = data[pos + i]; var c = (double)((d == Nucleotide.All) ? Freq[i].Min() : Freq[i][(byte)d]); if (c <= 0) c = 0.1; var n = Norm[i]; if (n != Count) c = Math.Pow(c, n/(double) Count); ret *= c; } return ret * CalcDegreeScoreNormFactor; }
/// <summary> /// Gets simple distance estimate for 2 nucleotides /// </summary> /// <param name="n1">The nucleotide 1.</param> /// <param name="n2">The nucleotide 2.</param> /// <returns>Distance estimate</returns> public override double NucleotideDistance(Nucleotide n1, Nucleotide n2) { return n1 == n2 ? 0 : 1; }
public static IList<Nucleotide> ParseNucleotides(IList<char> data) { Nucleotide[] result = new Nucleotide[data.Count]; for (int i = 0; i < data.Count; i++) { switch (data[i]) { case 'A': result[i] = Nucleotide.Adenine; break; case 'G': result[i] = Nucleotide.Guanine; break; case 'C': result[i] = Nucleotide.Cytosine; break; case 'T': result[i] = Nucleotide.Thymine; break; default: throw new InvalidOperationException(string.Format("The table contents must be valid nucleotides. Row {0} value {1}", i + 1, data[i])); } } return result; }
public Nucleotide[] GetPack(int start, int count) { Debug.Assert(start + count <= Count); var ret = new Nucleotide[count]; if (count == 0) return ret; var byteId = start/4; var lastByteId = (start + count)/4; var packId = start%4; var b = _data[byteId]; var cnt = 0; for (int i = packId; i < 4; i++) { ret[cnt] = (Nucleotide)((b >> (2*(i))) & 0x03); if (++cnt == count) break; } byteId++; for (; byteId <= lastByteId && cnt != count; byteId++) { b = _data[byteId]; for (int i = 0; i < 4; i++) { ret[cnt] = (Nucleotide)(b & 0x03); if (++cnt == count) break; b = (byte) (b >> 2); } } return ret; }
public double[] CalcMaxScore(Nucleotide[][] data, CalcMode? mode = null) { return data.Select(p => CalcMaxScore(p, mode)).ToArray(); }
public double CalcScore(Nucleotide[] data, int pos, CalcMode? mode) { switch (mode ?? DefaultCalcMode) { case CalcMode.Degree: return CalcScoreDegree(data, pos); case CalcMode.Eps: return CalcScoreEps(data, pos); case CalcMode.Strict: return CalcScoreStrict(data, pos); default: throw new NotSupportedException(); } }
/// <summary> /// Gets distance estimate for 2 nucleotides /// </summary> /// <param name="n1">The nucleotide 1.</param> /// <param name="n2">The nucleotide 2.</param> /// <returns>Distance estimate</returns> public abstract double NucleotideDistance(Nucleotide n1, Nucleotide n2);
public Nucleotide[] GetPack(int start, int count) { Debug.Assert(start >= 0); Debug.Assert(count >= 0); Debug.Assert(start + count <= Count); var ret = new Nucleotide[count]; if (count == 0) return ret; var byteId = start / 4; var lastByteId = (start + count) / 4; var packId = start % 4; var b = _data[byteId]; var cnt = 0; for (int i = packId; i < 4; i++) { ret[cnt] = (Nucleotide)((b >> (2 * (i))) & 0x03); if (++cnt == count) break; } byteId++; for (; byteId <= lastByteId && cnt != count; byteId++) { b = _data[byteId]; for (int i = 0; i < 4; i++) { ret[cnt] = (Nucleotide)(b & 0x03); if (++cnt == count) break; b = (byte)(b >> 2); } } // добавим маску for (int i = 0; i < ret.Length; i++) { var mId = start + i; if(((_mask[mId/8] >> (mId%8)) & 1) != 1) ret[i] = Nucleotide.Any; } return ret; }
/// <summary> /// Gets distance estimate for nucleotide and profile /// </summary> /// <param name="nucleotide">The nucleotide.</param> /// <param name="profileItem">The profile item.</param> /// <returns>Distance estimate</returns> public double ProfileItemNucleotideDistance(Nucleotide nucleotide, ProfileItem profileItem) { return profileItem.Sum(n => n.Value * this.NucleotideDistance(n.Key, nucleotide)); }
public double CalcScore(Nucleotide[] data, int pos, CalcMode? mode) { double ret = 0.0; var mo = mode ?? DefaultCalcMode; foreach (var ms in new[] {_posMotiffs, _negMotiffs}) { var sum = new List<double>(); foreach (var m in ms) { switch (mo) { case CalcMode.Degree: sum.Add(m.CalcScoreDegree(data, pos)); break; case CalcMode.Eps: sum.Add(m.CalcScoreEps(data, pos)); break; case CalcMode.Strict: sum.Add(m.CalcScoreStrict(data, pos)); break; default: throw new NotSupportedException(); } } var tmp = Mode == DiffMode.Avg ? sum.Average() : sum.Max(); if (ms == _posMotiffs) ret += tmp; else ret -= tmp; } return (ret + 1.0)/2.0; }
public MultiAlignmentResult(int[] shifts, Direction[] directions, Nucleotide[][] map, int[] mapFactors) { Shifts = shifts; Directions = directions; Map = map; MapFactors = mapFactors; Prepare(); }
/// <summary> /// Вычисляет коэффициент близости. /// Жёсткий алгоритм: /// * Если задано All, то берёт наименее вероятный нуклеотид; /// * Если нуклеотид не встречался, то считает, что совпадения вообще нет. /// </summary> /// <returns>1 - точное совпадение, 0 - отсутствие совпадения.</returns> public double CalcScoreStrict(Nucleotide[] data, int pos) { var ret = 1.0; if (pos < 0 || data.Length <= pos + Length) return 0; for (int i = 0; i < Length; i++) { var d = data[pos + i]; var c = (d == Nucleotide.All) ? Freq[i].Min() : Freq[i][(byte)d]; if (c == 0) return 0; ret *= c; } return ret * CalcScoreNormFactor; }