$ErrorActionPreference = "Stop" # 1. GitHub repository raw base URL $RepoBaseUrl = "https://raw.githubusercontent.com/ramapithecus29/admixSA/main" # 2. Component labels in exact column order of C.15.P $ComponentNames = @( "Andamanese", "Papuans", "Greenland", "NE Europe", "America", "Caucasian", "Mediterrenean", "Balochi", "Pygmies", "Siberian", "Mandenka Africa", "S India", "Mozabites", "SW Asian", "NE Asian" ) # Helper: returns clean Win32 or UNC path without PowerShell's FileSystem:: provider prefix function Resolve-CleanPath([string]$p) { $resolved = Resolve-Path -LiteralPath $p return ($resolved.ProviderPath -replace '^Microsoft\.PowerShell\.Core\\FileSystem::', '') } # 3. Prompt user to drag and drop their DNA file (or accept optional CLI argument) $dnaPath = $null if ($args.Count -gt 0 -and -not [string]::IsNullOrWhiteSpace($args[0])) { $cleanedArg = $args[0].Trim().Trim('"').Trim("'").Trim() if (Test-Path -LiteralPath $cleanedArg -PathType Leaf) { $dnaPath = Resolve-CleanPath $cleanedArg } } while (-not $dnaPath) { Write-Host "" $rawInput = Read-Host "Drag and drop your DNA file (.txt, .csv, .gz, or .zip) into this window and press Enter" if ([string]::IsNullOrWhiteSpace($rawInput)) { continue } $cleanedPath = $rawInput.Trim().Trim('"').Trim("'").Trim() if (Test-Path -LiteralPath $cleanedPath -PathType Leaf) { $dnaPath = Resolve-CleanPath $cleanedPath } else { Write-Host "File not found: $cleanedPath — please try dragging the file again." -ForegroundColor Red } } Write-Host "Selected file: $dnaPath" -ForegroundColor Cyan # 4. Download & cache C.bim and C.15.P from GitHub if not already present [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $cacheDir = Join-Path $env:LOCALAPPDATA "AdmixSACache" if (-not (Test-Path -LiteralPath $cacheDir)) { New-Item -ItemType Directory -Path $cacheDir | Out-Null } function Get-RefFile([string]$fileName) { if (Test-Path -LiteralPath $fileName) { return (Resolve-CleanPath $fileName) } $cachedFile = Join-Path $cacheDir $fileName if (-not (Test-Path -LiteralPath $cachedFile)) { $url = "$RepoBaseUrl/$fileName" Write-Host "Downloading $fileName from admixSA (cached for future runs)..." -ForegroundColor Yellow $wc = New-Object System.Net.WebClient $wc.DownloadFile($url, $cachedFile) } return $cachedFile } $bimPath = Get-RefFile "C.bim" $pPath = Get-RefFile "C.15.P" # 5. Inline C# engine: multi-format parser (.txt/.csv/.gz/.zip) + SQUAREM EM projection $pipelineCSharp = @" using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; public class AdmixturePipeline { public struct PipelineResult { public double[] Q; public int Iterations; public int EmEvaluations; public double LogLikelihood; public int TotalBim; public int Matched; public int Flipped; public int Missing; public int Triallelic; public bool LineCountMismatch; public string DetectedFormat; } private static string NormalizeChr(string c) { c = c.Trim().ToUpperInvariant(); if (c.StartsWith("CHR")) c = c.Substring(3); switch (c) { case "23": return "X"; case "24": return "Y"; case "25": return "XY"; case "26": case "M": return "MT"; default: return c; } } private static bool IsBase(char c) { return c == 'A' || c == 'C' || c == 'G' || c == 'T'; } private static char Complement(char c) { switch (c) { case 'A': return 'T'; case 'T': return 'A'; case 'C': return 'G'; case 'G': return 'C'; default: return 'N'; } } private static StreamReader OpenDnaReader(string dnaPath, out IDisposable archiveToDispose) { archiveToDispose = null; string lower = dnaPath.ToLowerInvariant(); if (lower.EndsWith(".zip")) { ZipArchive zip = ZipFile.OpenRead(dnaPath); archiveToDispose = zip; ZipArchiveEntry bestEntry = null; foreach (ZipArchiveEntry entry in zip.Entries) { if (entry.Length == 0 || entry.FullName.EndsWith("/") || entry.FullName.EndsWith("\\")) continue; if (entry.FullName.IndexOf("__MACOSX", StringComparison.OrdinalIgnoreCase) >= 0) continue; string eLower = entry.Name.ToLowerInvariant(); bool isData = eLower.EndsWith(".txt") || eLower.EndsWith(".csv") || eLower.EndsWith(".tsv") || eLower.EndsWith(".gz"); if (bestEntry == null) { bestEntry = entry; } else { string bLower = bestEntry.Name.ToLowerInvariant(); bool bestIsData = bLower.EndsWith(".txt") || bLower.EndsWith(".csv") || bLower.EndsWith(".tsv") || bLower.EndsWith(".gz"); if ((isData && !bestIsData) || (isData == bestIsData && entry.Length > bestEntry.Length)) { bestEntry = entry; } } } if (bestEntry == null) { zip.Dispose(); archiveToDispose = null; throw new InvalidOperationException("No valid DNA file found inside the ZIP archive."); } Stream entryStream = bestEntry.Open(); if (bestEntry.Name.EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) { return new StreamReader(new GZipStream(entryStream, CompressionMode.Decompress)); } return new StreamReader(entryStream); } else if (lower.EndsWith(".gz")) { FileStream fs = File.OpenRead(dnaPath); return new StreamReader(new GZipStream(fs, CompressionMode.Decompress)); } else { return new StreamReader(dnaPath); } } private static double ParseDoubleSlice(string s, int start, int end) { int i = start; bool neg = false; if (s[i] == '-') { neg = true; i++; } else if (s[i] == '+') { i++; } int digitStart = i; double val = 0.0; while (i < end && s[i] >= '0' && s[i] <= '9') { val = val * 10.0 + (s[i] - '0'); i++; } if (i < end && s[i] == '.') { i++; double scale = 0.1; while (i < end && s[i] >= '0' && s[i] <= '9') { val += (s[i] - '0') * scale; scale *= 0.1; i++; } } if (i == digitStart) { return double.Parse(s.Substring(start, end - start), CultureInfo.InvariantCulture); } if (i < end && (s[i] == 'e' || s[i] == 'E')) { i++; bool expNeg = false; if (s[i] == '-') { expNeg = true; i++; } else if (s[i] == '+') { i++; } int exp = 0; while (i < end && s[i] >= '0' && s[i] <= '9') { exp = exp * 10 + (s[i] - '0'); i++; } val *= Math.Pow(10.0, expNeg ? -exp : exp); } return neg ? -val : val; } private static double EMStep( double[] fFlat, byte[] gArr, int n, int K, double denom, double[] qIn, double[] qOut, double[] acc) { Array.Clear(acc, 0, K); double logLik = 0.0; double sumW0 = 0.0; for (int j = 0; j < n; j++) { int rowOffset = j * K; double pHat = 0.0; for (int k = 0; k < K; k++) { pHat += qIn[k] * fFlat[rowOffset + k]; } byte g = gArr[j]; double w1 = 0.0; double w0 = 0.0; if (g == 0) { double oneMinusP = 1.0 - pHat; w0 = 2.0 / oneMinusP; logLik += 2.0 * Math.Log(oneMinusP); } else if (g == 1) { double oneMinusP = 1.0 - pHat; w1 = 1.0 / pHat; w0 = 1.0 / oneMinusP; logLik += Math.Log(pHat * oneMinusP); } else { w1 = 2.0 / pHat; logLik += 2.0 * Math.Log(pHat); } sumW0 += w0; double diffW = w1 - w0; for (int k = 0; k < K; k++) { acc[k] += diffW * fFlat[rowOffset + k]; } } double sumQ = 0.0; for (int k = 0; k < K; k++) { double val = (qIn[k] * (sumW0 + acc[k])) / denom; if (val < 1e-5) val = 1e-5; qOut[k] = val; sumQ += val; } double invSumQ = 1.0 / sumQ; for (int k = 0; k < K; k++) { qOut[k] *= invSumQ; } return logLik; } public static PipelineResult Run(string bimPath, string pPath, string dnaPath) { PipelineResult res = new PipelineResult(); res.DetectedFormat = "Standard 4-col (23andMe / Living DNA)"; var byId = new Dictionary(700000, StringComparer.OrdinalIgnoreCase); var byPos = new Dictionary(700000, StringComparer.OrdinalIgnoreCase); char[] dnaSep = new char[] { '\t', ',' }; IDisposable archiveToDispose = null; try { using (var dnaReader = OpenDnaReader(dnaPath, out archiveToDispose)) { string line; while ((line = dnaReader.ReadLine()) != null) { if (line.Length == 0 || line[0] == '#') { if (line.IndexOf("AncestryDNA", StringComparison.OrdinalIgnoreCase) >= 0) res.DetectedFormat = "AncestryDNA (5-col TSV)"; else if (line.IndexOf("Living DNA", StringComparison.OrdinalIgnoreCase) >= 0) res.DetectedFormat = "Living DNA (4-col TSV)"; else if (line.IndexOf("23andMe", StringComparison.OrdinalIgnoreCase) >= 0) res.DetectedFormat = "23andMe (4-col TSV)"; continue; } string clean = line.Replace("\"", "").Trim(); if (clean.Length == 0) continue; if (clean.StartsWith("rsid", StringComparison.OrdinalIgnoreCase)) { if (clean.IndexOf("RESULT", StringComparison.OrdinalIgnoreCase) >= 0) res.DetectedFormat = "FTDNA / MyHeritage (4-col CSV)"; else if (clean.IndexOf("allele1", StringComparison.OrdinalIgnoreCase) >= 0) res.DetectedFormat = "AncestryDNA (5-col TSV)"; continue; } string[] cols = clean.Split(dnaSep); if (cols.Length < 4) continue; string rsid = cols[0].Trim(); string chr = NormalizeChr(cols[1]); string pos = cols[2].Trim(); string gt = (cols.Length >= 5) ? (cols[3].Trim() + cols[4].Trim()).ToUpperInvariant() : cols[3].Trim().ToUpperInvariant(); if (gt.Length == 1 && IsBase(gt[0])) { gt = new string(gt[0], 2); } if (gt.Length != 2 || !IsBase(gt[0]) || !IsBase(gt[1])) continue; if (rsid.Length > 0 && !byId.ContainsKey(rsid)) byId[rsid] = gt; string posKey = chr + ":" + pos; if (!byPos.ContainsKey(posKey)) byPos[posKey] = gt; } } } finally { if (archiveToDispose != null) archiveToDispose.Dispose(); } var fList = new List(4000000); var gList = new List(600000); int K = 0; char[] bimSep = new char[] { ' ', '\t' }; using (var bimReader = new StreamReader(bimPath)) using (var pReader = new StreamReader(pPath)) { string bimLine, pLine; while ((bimLine = bimReader.ReadLine()) != null && (pLine = pReader.ReadLine()) != null) { if (string.IsNullOrWhiteSpace(bimLine)) continue; res.TotalBim++; string[] cols = bimLine.Trim().Split(bimSep, StringSplitOptions.RemoveEmptyEntries); string chr = NormalizeChr(cols[0]); string id = cols[1].Trim(); string pos = cols[3].Trim(); string a1Str = cols[4].Trim().ToUpperInvariant(); string a2Str = cols[5].Trim().ToUpperInvariant(); if (a1Str.Length != 1 || a2Str.Length != 1 || !IsBase(a1Str[0]) || !IsBase(a2Str[0])) { res.Triallelic++; continue; } char a1 = a1Str[0]; char a2 = a2Str[0]; bool isPalindromic = (a1 == 'A' && a2 == 'T') || (a1 == 'T' && a2 == 'A') || (a1 == 'C' && a2 == 'G') || (a1 == 'G' && a2 == 'C'); string gt; if (!byId.TryGetValue(id, out gt)) { byPos.TryGetValue(chr + ":" + pos, out gt); } if (gt == null) { res.Missing++; continue; } char b1 = gt[0]; char b2 = gt[1]; int dosage = -1; if ((b1 == a1 || b1 == a2) && (b2 == a1 || b2 == a2)) { dosage = (b1 == a2 ? 1 : 0) + (b2 == a2 ? 1 : 0); res.Matched++; } else if (!isPalindromic) { char c1 = Complement(b1); char c2 = Complement(b2); if ((c1 == a1 || c1 == a2) && (c2 == a1 || c2 == a2)) { dosage = (c1 == a2 ? 1 : 0) + (c2 == a2 ? 1 : 0); res.Matched++; res.Flipped++; } } if (dosage < 0) { res.Triallelic++; continue; } int len = pLine.Length; int idx = 0; int colCount = 0; while (idx < len) { while (idx < len && (pLine[idx] == ' ' || pLine[idx] == '\t')) idx++; if (idx >= len) break; int tokStart = idx; while (idx < len && pLine[idx] != ' ' && pLine[idx] != '\t') idx++; double fVal = ParseDoubleSlice(pLine, tokStart, idx); if (fVal < 1e-5) fVal = 1e-5; else if (fVal > 0.99999) fVal = 0.99999; fList.Add(fVal); colCount++; } if (K == 0) K = colCount; gList.Add((byte)dosage); } if (bimReader.ReadLine() != null || pReader.ReadLine() != null) { res.LineCountMismatch = true; } } int n = gList.Count; if (n == 0 || K == 0) { throw new InvalidOperationException("No valid overlapping genotypes found."); } double[] fFlat = fList.ToArray(); byte[] gArr = gList.ToArray(); double denom = 2.0 * n; double[] q0 = new double[K]; double[] q1 = new double[K]; double[] q2 = new double[K]; double[] qPrime = new double[K]; double[] qNext = new double[K]; double[] rVec = new double[K]; double[] vVec = new double[K]; double[] acc = new double[K]; for (int k = 0; k < K; k++) q0[k] = 1.0 / K; double finalLL = 0.0; int emEvals = 0; int iter = 1; for (; iter <= 200; iter++) { double ll0 = EMStep(fFlat, gArr, n, K, denom, q0, q1, acc); double ll1 = EMStep(fFlat, gArr, n, K, denom, q1, q2, acc); emEvals += 2; double rNormSq = 0.0; double vNormSq = 0.0; double maxStepDiff = 0.0; for (int k = 0; k < K; k++) { double rVal = q1[k] - q0[k]; double vVal = (q2[k] - q1[k]) - rVal; rVec[k] = rVal; vVec[k] = vVal; rNormSq += rVal * rVal; vNormSq += vVal * vVal; double absR = Math.Abs(rVal); if (absR > maxStepDiff) maxStepDiff = absR; } if (maxStepDiff < 1e-7) { Array.Copy(q2, q0, K); finalLL = ll1; break; } double alpha = (vNormSq > 1e-24) ? -Math.Sqrt(rNormSq / vNormSq) : -1.0; if (alpha > -1.0) alpha = -1.0; while (true) { bool allNonNeg = true; double sumPrime = 0.0; for (int k = 0; k < K; k++) { double qVal = q0[k] - 2.0 * alpha * rVec[k] + alpha * alpha * vVec[k]; if (qVal < -1e-12) { allNonNeg = false; break; } if (qVal < 1e-5) qVal = 1e-5; qPrime[k] = qVal; sumPrime += qVal; } if (allNonNeg && sumPrime > 0.0) { double invSum = 1.0 / sumPrime; for (int k = 0; k < K; k++) qPrime[k] *= invSum; break; } alpha = (alpha - 1.0) * 0.5; if (Math.Abs(alpha + 1.0) < 1e-8) { Array.Copy(q2, qPrime, K); alpha = -1.0; break; } } while (true) { double llPrime = EMStep(fFlat, gArr, n, K, denom, qPrime, qNext, acc); emEvals++; if (llPrime >= (ll1 - 1e-9) || alpha == -1.0) { finalLL = llPrime; break; } alpha = (alpha - 1.0) * 0.5; if (Math.Abs(alpha + 1.0) < 1e-8) { Array.Copy(q2, qPrime, K); alpha = -1.0; } else { double sumPrime = 0.0; for (int k = 0; k < K; k++) { double qVal = q0[k] - 2.0 * alpha * rVec[k] + alpha * alpha * vVec[k]; if (qVal < 1e-5) qVal = 1e-5; qPrime[k] = qVal; sumPrime += qVal; } double invSum = 1.0 / sumPrime; for (int k = 0; k < K; k++) qPrime[k] *= invSum; } } double maxDiff = 0.0; for (int k = 0; k < K; k++) { double diff = Math.Abs(qNext[k] - q0[k]); if (diff > maxDiff) maxDiff = diff; } Array.Copy(qNext, q0, K); if (maxDiff < 1e-7) break; } res.Q = q0; res.Iterations = iter; res.EmEvaluations = emEvals; res.LogLikelihood = finalLL; return res; } } "@ if (-not ([System.Management.Automation.PSTypeName]'AdmixturePipeline').Type) { Add-Type -TypeDefinition $pipelineCSharp -ReferencedAssemblies System.IO.Compression, System.IO.Compression.FileSystem } $sw = [System.Diagnostics.Stopwatch]::StartNew() $result = [AdmixturePipeline]::Run($bimPath, $pPath, $dnaPath) $sw.Stop() Write-Host "" Write-Host ("Format: {0}" -f $result.DetectedFormat) -ForegroundColor Cyan Write-Host ("Matched {0:N0} / {1:N0} SNPs ({2:N0} strand-flipped) | Converged in {3:F2}s ({4} SQUAREM iters)" -f ` $result.Matched, $result.TotalBim, $result.Flipped, $sw.Elapsed.TotalSeconds, $result.Iterations) -ForegroundColor Green Write-Host "--------------------------------------------------" for ($popIdx = 0; $popIdx -lt $result.Q.Length; $popIdx++) { $label = if ($popIdx -lt $ComponentNames.Length) { $ComponentNames[$popIdx] } else { "Pop_$($popIdx + 1)" } $val = $result.Q[$popIdx] "{0,-18} {1,7:F2}% ({2:F6})" -f $label, ($val * 100.0), $val } Write-Host "--------------------------------------------------"