/// <summary>Cria um array de Scans com base num DataSet</summary> /// <remarks> /// Tem em conta um dataset com os campos na seguinte ordem: /// Id, 0 /// SourcePlanetId, 1 /// TargetPlanetId, 2 /// ScanLevel, 3 /// Intercepted, 4 /// Succeded, 5 /// Turn 6 /// Culture 7 /// HasCommsSatellite 8 /// HasGate 9 /// HasStarGate 10 /// HasStarPort 11 /// InBattle 12 /// FleetCount 13 /// TargetPlanetOwner 14 /// TotalShips 15 /// </remarks> public virtual Scan[] DataSetToScans( DataSet ds ) { ArrayList list = new ArrayList(); foreach( DataRow row in ds.Tables[0].Rows ) { Scan scan = new Scan(); scan.Id = (int) row[0]; scan.SourcePlanetId = (int) row[1]; scan.Target = Coordinate.translateCoordinate(row[2].ToString()); scan.ScanLevel = (int) row[3]; scan.Intercepted = GetBool(row[4]); scan.Success = GetBool(row[5]); scan.Turn = (int)row[6]; scan.Culture = (int) row[7]; scan.HasCommsSatellite = GetBool(row[8]); scan.HasGate = GetBool(row[9]); scan.HasStarGate = GetBool(row[10]); scan.HasStarPort = GetBool(row[11]); scan.InBattle = GetBool(row[12]); scan.NumberOfFleets = (int) row[13]; scan.TargetPlanetOwner = (int) row[14]; scan.TotalShips = (int) row[15]; list.Add(scan); } return (Scan[]) list.ToArray(typeof(Scan)); }
/// <summary> /// Add mapping files by scanning assemblies for files with the mapping file naming convention /// </summary> public Scan Scan() { var scan = new Scan { ScanFor = Enum.ScanFor.MappingFiles, Configuration = Configuration }; return scan; }
/// <summary> /// converte um conjunto de rows em binrio para um array de objectos do tipo scan; /// </summary> /// <param name="ds">DataSet com as Rows</param> /// <returns>Array com todos os Scans</returns> public override Scan[] DataSetToScans(DataSet ds) { Scan[] list = new Scan[ds.Tables[0].Rows.Count]; int i = -1; foreach( DataRow row in ds.Tables[0].Rows ) { Scan scan = ConvertBinaryToScan( row["scans_data"] ); scan.Id = (int)row["scans_id"]; list[++i] = scan; } return list; }
/// <summary>Regista um scan</summary> public override void Register( Scan scan ) { MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, scan); byte[] data = stream.ToArray(); Hashtable parameters = new Hashtable(); parameters.Add("@sourcePlanetId",scan.SourcePlanetId); parameters.Add("@data",data); SqlServerUtility.executeNonQuery("OrionsBelt_InsertScans",parameters); }
/// <summary>Regista um scan</summary> public override void Register( Scan scan ) { string script = string.Format("INSERT INTO Scans VALUES('', {0}, '{1}', {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14} )", scan.SourcePlanetId, scan.Target.ToString(), scan.ScanLevel, scan.Intercepted?1:0, scan.Success?1:0, scan.Turn, scan.Culture, scan.HasCommsSatellite, scan.HasGate, scan.HasStarGate, scan.HasStarPort, scan.InBattle, scan.NumberOfFleets, scan.TargetPlanetOwner, scan.TotalShips ); Chronos.Utils.Log.log(script); MySqlUtility.executeNonQuery(script); }
public void RunningSum() { // NOTE: fully qualifying the type name matters. If this were a real thing, you could put in default namespaces. var summer = new Scan<Event<long>>("(sum, @event) => new RoslynRx.Tests.Event<long>(0, sum.Data + @event.Data)"); var testInterval = new TestInterval(); long sum = long.MinValue; testInterval.Interval.Link(summer).Subscribe(i => { sum = i.Data; Console.WriteLine(i.Data); }); var oldSum = 0L; for (int i = 0; i < testInterval.ExpectedCount; i++) { Console.WriteLine("Advancing. {0} {1}", i, oldSum); testInterval.Scheduler.AdvanceBy(TimeSpan.TicksPerSecond); oldSum = oldSum + i; sum.Should().Be(oldSum); } sum.Should().Be(1770); }
/// <summary> /// converte um conjunto de rows em binrio para um array de objectos do tipo scan; /// </summary> /// <param name="ds">DataSet com as Rows</param> /// <returns>Array com todos os Scans</returns> public override Scan[] DataSetToScans(DataSet ds) { Scan[] list = null; int i = -1; foreach( DataRow row in ds.Tables[0].Rows ) { if(row[0] is System.DBNull ) { continue; } if( list == null ) { list = new Scan[ds.Tables[0].Rows.Count]; } Scan scan = ConvertBinaryToScan( row[1] ); scan.Id = (int)row[0]; list[++i] = scan; } return list; }
protected bool CollectScan (bool collectBkgnd) { bool bRet = true; if (collectBkgnd || (darkScan == null) || (lightScan == null)) { bRet = CollectBackground(); } if (bRet) { bRet = GetNormalScans (); } if (bRet) { UpdateSystemStatus("Analyzing data"); AddOutputText(string.Format("Sample Scan:\r{0}\r", sampleScan.ToString("\r"))); /* string scanStr = sampleScan.ToString("\r"); textviewOutput.Buffer.Text += "Sample Scan:\r" + scanStr + "\r"; */ AddOutputText("Computing absorbance\r"); RefreshUI(); ComputeAbsorbance (); AddOutputText("Performing spline interpolation\r"); RefreshUI(); double[] newX, newY; bRet = SplineInterpolate (xAxis, absorbanceSpectrum.yVals, (double)Math.Ceiling(xAxis[0]), Math.Floor(xAxis[xAxis.Length - 1]), 1.0, out newX, out newY); if (bRet) { AddOutputText("Clipping spectra\r"); RefreshUI(); xAxisInterp = new double[newX.Length]; newX.CopyTo(xAxisInterp, 0); absorbanceSpectrumSplined = new Scan(xAxisInterp, newY); // Now clip the spectra int siz = (int)(clippingEnd - clippingStart) + 1; // this assumes spacing is 1 double[] x = new double[siz]; double[] y = new double[siz]; double[,] yMatrix = new double[1, siz]; int nIndex = 0; for (int i = 0; i < xAxisInterp.Length; i++) { if (xAxisInterp[i] >= clippingStart && xAxisInterp[i] <= clippingEnd) { x[nIndex] = xAxisInterp[i]; y[nIndex] = newY[i]; yMatrix[0,nIndex] = newY[i]; nIndex++; } } absorbanceSpectrumClipped = new Scan(x, y); System.Text.StringBuilder sb = new System.Text.StringBuilder("Absorbance spectra after spline and clip\r"); //AddOutputText("Absorbance spectra after spline and clip\r"); for( int i = 0; i < x.Length; i++) { sb.AppendFormat("X: {0} Y: {1}\r", x[i], y[i]); //textviewOutput.Buffer.Text += "X: " + x[i].ToString() + " Y: " + y[i].ToString() + "\r"; } AddOutputText(sb.ToString()); RunEigenvectorModel("./01_Density.xml", yMatrix); RunEigenvectorModel("./02_FlashPoint.xml", yMatrix); RunEigenvectorModel("./03_FreezePoint.xml", yMatrix); } } UpdateSystemStatus("Ready"); return bRet; }
protected bool GetNormalScans () { int nResp = MPFQA.MessageBoxEx.Show ("Insert sample vial\nPress Ok to proceed", display, new List<string> (new string[] { "Insert sample vial", "Hit Enter to proceed" })); display.Clear(); display.Add(" RTA M-PFQA", false); if (nResp != (int)Gtk.ResponseType.Ok) { UpdateSystemStatus("Ready"); return false; } bool bRet = false; UpdateSystemStatus("Collecting sample"); /* // Flush pending events to keep the GUI reponsive while (Gtk.Application.EventsPending ()) Gtk.Application.RunIteration (); if (displayComm != null && displayComm.IsOpen ()) { displayComm.Write ("\rCollect sample "); } */ TurnOnLamp (); AddOutputText("Getting Normal Scan\r"); RefreshUI(); UInt16[] data; if (GetCoaddedScans (out data)) { bRet = true; sampleScan = new Scan(xAxis, data); RemoveDark(ref sampleScan); } TurnOffLamp(); UpdateSystemStatus("Ready"); return bRet; }
protected void RemoveDark (ref Scan scan) { for( int i = 0; i < scan.yVals.Length; i++) { if (scan.yVals[i] > darkScan.yVals[i]) { scan.yVals[i] -= darkScan.yVals[i]; } else { scan.yVals[i] = 0; } } }
private void GeneralDetailsPlots() { try { Scan s = new Scan(); GridView dv = s.GeneralDetailsPlots(email); campaignShareGeneral.InnerHtml = dv.Rows[0].Cells[0].Text; campignTotalShare.InnerHtml = dv.Rows[0].Cells[0].Text; amountOfScans.InnerHtml = dv.Rows[0].Cells[1].Text; } catch (Exception) { throw; } }
/// <summary> /// Insert a scan record /// </summary> /// <param name="conn"></param> /// <param name="scan"></param> public void InsertScan(SQLiteConnection conn, Scan scan) { string sql = "INSERT INTO Scans (Wallet, Type) VALUES ('" + scan.Wallet + "', '" + scan.scanType.ToString() + "');"; DoNoResultQuery(conn, sql); }
/// <summary> /// Take single image from stream<para/> /// Получение текстуры из потока /// </summary> /// <param name="f">Stream<para/>Поток</param> /// <returns>Texture entry<para/>Запись текстуры</returns> Entry ReadTexture(BinaryReader f) { Entry tx = new Entry(); // Texture platform flag // Платформа текстуры uint platform = f.ReadUInt32(); if (platform != 8) { throw new Exception("[TextureFile] Specified platform does not match VC: " + platform); } // Filtering flags // Флаги фильтрации tx.Filtering = (FilterMode)f.ReadByte(); byte wrapd = f.ReadByte(); tx.AddressU = (AddressMode)(wrapd & 0x0F); tx.AddressV = (AddressMode)(wrapd >> 4); f.BaseStream.Position += 2; // Texture and mask names // Имена текстуры и её маски tx.Name = f.ReadVCString(32).ToLower(); tx.Mask = f.ReadVCString(32).ToLower(); // Raster format // Формат растра tx.Flags = f.ReadUInt32(); // Does alpha present // Есть ли альфаканал uint hasAlpha = f.ReadUInt32(); // Texture dimensions // Размеры текстуры int texW = f.ReadUInt16(); int texH = f.ReadUInt16(); // Bit depth // Глубина цвета int depth = f.ReadByte(); // Mipmap number // Количество MIP-уровней int mipcount = f.ReadByte(); // Raster type (must be 4) // Тип растра (должен быть 4) int type = f.ReadByte(); // DXT compression // DXT-сжатие tx.ScanCompression = (Compression)f.ReadByte(); // Special palette // Палитра byte[] palette = null; List<Scan> scans = new List<Scan>(); // Reading palette, if needed // Чтение палитры если требуется if ((tx.Flags & (int)RasterFlags.Palette8) > 0 || (tx.Flags & (int)RasterFlags.Palette4) > 0) { int paletteSize = 1024; if ((tx.Flags & (int)RasterFlags.Palette4) > 0) { paletteSize = 64; } palette = f.ReadBytes(paletteSize); } // Reading data for all mipmaps // Чтение MIP-уровней for (int mip = 0; mip < mipcount; mip++) { // Size of data (may be 0) // Размер данных (может быть равен 0) int dataSize = (int)f.ReadUInt32(); if (dataSize == 0) { // Computing size // Вычисление размера if ((tx.Flags & (int)RasterFlags.Palette8) > 0 || (tx.Flags & (int)RasterFlags.Palette4) > 0) { // Format is paletted // Формат задан палитрой dataSize = texW * texH; if ((tx.Flags & (int)RasterFlags.Palette4) > 0) { dataSize /= 2; } } else if (tx.ScanCompression != Compression.Uncompressed) { // Format is compressed // Кадры подвержены сжатию int ttw = texW; int tth = texH; if (ttw < 4) ttw = 4; if (tth < 4) tth = 4; if (tx.ScanCompression == Compression.DXT3) { dataSize = (ttw / 4) * (tth / 4) * 16; } else { dataSize = (ttw / 4) * (tth / 4) * 8; } } } // Reading raw data, corresponding to size // Чтение данных byte[] data = f.ReadBytes(dataSize); Scan scan = new Scan(); scan.Size = new Vector2(texW, texH); if ((tx.Flags & (int)RasterFlags.Palette8) > 0) { // Decoding paletted textures // Раскодирование текстур с палитрой byte[] output = new byte[texW * texH * 4]; for (int i = 0; i < data.Length; i++) { Array.Copy(palette, data[i] * 4, output, i * 4, 4); } scan.Data = output; } else { // Generic textures, may be compressed // Обычные текстуры, возмножно сжатые scan.Data = data; } scans.Add(scan); texW /= 2; texH /= 2; } tx.Scans = scans.ToArray(); return tx; }
public static Project GetProjectInfo(Scan scan) { return(entityRepository.GetProjectInfo(scan)); }
public void Set2ScanComparisons(Scan scanOne, Scan scanOther) { Set2Scans(scanOne, scanOther); DataBind2Scans(); }
/// <summary> /// Add information about scan to visualize it. /// </summary> /// <param name="scan"></param> public void AddScan(Scan scan) { scans.Add(scan); }
public async void Cop(string choice = "") { try { items.Choice = choice; //Return the documents list and create a Folder named 'Arranger' //Move all the documents to arranger folder //Console.Clear(); //Console.WriteLine("Please wait..."); //Console.WriteLine(); Scan sc = new Scan(); string pathname = ""; switch (items.Choice) { case "Documents": list = await sc.DocList(); pathname = "Documents"; break; case "Videos": list = await sc.VidList(); pathname = "Videos"; break; case "Images": list = await sc.ImgList(); pathname = "Images"; break; } string fullPath = items.Path + $"\\Arranger{pathname}\\"; string filename = ""; string ext = ""; foreach (var i in list) { Directory.CreateDirectory(fullPath + Path.GetExtension(i).Substring(1).ToUpper()); filename = Path.GetFileName(i); ext = Path.GetExtension(i); if (items.Choice == "Documents") { string[] ps = { "txt", "docx", "doc", "xls", "xlsx", "ppt", "pptx,", "pdf" }; switch (ext) { case ".txt": File.Copy(i, Path.Combine(fullPath + ps[0].ToString(), filename), true); break; case ".docx": File.Copy(i, Path.Combine(fullPath + ps[1].ToString(), filename), true); break; case ".doc": File.Copy(i, Path.Combine(fullPath + ps[2].ToString(), filename), true); break; case ".xls": File.Copy(i, Path.Combine(fullPath + ps[3].ToString(), filename), true); break; case ".xlsx": File.Copy(i, Path.Combine(fullPath + ps[4].ToString(), filename), true); break; case ".ppt": File.Copy(i, Path.Combine(fullPath + ps[5].ToString(), filename), true); break; case ".pptx": File.Copy(i, Path.Combine(fullPath + ps[6].ToString(), filename), true); break; case ".pdf": File.Copy(i, Path.Combine(fullPath + ps[7].ToString(), filename), true); break; } } if (items.Choice == "Videos") { string[] ps = { "mp4", "flv", "avi", "mkv", "vob", "wmv" }; switch (ext) { case ".mp4": File.Copy(i, Path.Combine(fullPath + ps[0].ToString(), filename), true); break; case ".flv": File.Copy(i, Path.Combine(fullPath + ps[1].ToString(), filename), true); break; case ".avi": File.Copy(i, Path.Combine(fullPath + ps[2].ToString(), filename), true); break; case ".mkv": File.Copy(i, Path.Combine(fullPath + ps[3].ToString(), filename), true); break; case ".vob": File.Copy(i, Path.Combine(fullPath + ps[4].ToString(), filename), true); break; case ".wmv": File.Copy(i, Path.Combine(fullPath + ps[5].ToString(), filename), true); break; } } if (items.Choice == "Images") { string[] ps = { "bimp", "jpg", "jpeg", "gif", "png" }; switch (ext) { case ".bimp": File.Copy(i, Path.Combine(fullPath + ps[0].ToString(), filename), true); break; case ".jpg": File.Copy(i, Path.Combine(fullPath + ps[1].ToString(), filename), true); break; case ".jpeg": File.Copy(i, Path.Combine(fullPath + ps[2].ToString(), filename), true); break; case ".gif": File.Copy(i, Path.Combine(fullPath + ps[3].ToString(), filename), true); break; case ".png": File.Copy(i, Path.Combine(fullPath + ps[4].ToString(), filename), true); break; } } System.Threading.Thread.Sleep(300); Console.WriteLine(Path.GetFileName(i)); items.FullPath = fullPath; } //Console.Clear(); //Console.WriteLine($"Success...Please check the folder named Arranger{pathname}"); //Console.WriteLine(); //Console.WriteLine("Press enter to exit."); } catch (Exception ex) { Console.Write("Error " + ex.Message + " " + ex.Data); } }
static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var sc = new Scan(); int lim2 = 110000, lim3 = 2200; var isp = new bool[lim2]; var pr1 = new SortedSet <int>(); var pr2 = new SortedDictionary <long, int>(); var dic = new SortedDictionary <long, long>(); var cnt = new SortedDictionary <long, int>(); var pr = new List <int>(); for (int i = 2; i < lim2; i++) { isp[i] = true; } pr2.Add(1, 1); for (int i = 2; i < lim2; i++) { if (isp[i]) { pr.Add(i); pr1.Add(i); pr2.Add(i * (long)i, i); for (long j = i * (long)i; j < lim2; j += i) { isp[j] = false; } } } int n = sc.Int, ans = 0, one = 0; for (int i = 0; i < n; i++) { long a = sc.Long, b = 1, p = 1; foreach (var item in pr) { if (item > lim3 || a < item) { break; } long i3 = item * (long)item * item; int i2 = item * item; while (a % i3 == 0) { a /= i3; } if (a % i2 == 0) { a /= i2; b *= i2; p *= item; } if (a % item == 0) { a /= item; b *= item; p *= i2; } if (p > 1e11) { ++ans; goto A; } } if (a * b == 1) { one = 1; continue; } if (pr2.ContainsKey(a)) { long nor = a * b, pir = p * pr2[a]; if (pir > 1e11) { ++ans; continue; } if (!dic.ContainsKey(nor)) { dic.Add(nor, pir); } if (!cnt.ContainsKey(nor)) { cnt.Add(nor, 1); } else { ++cnt[nor]; } } else if (a < lim2 && pr1.Contains((int)a)) { if (p * a > 1e11 || p * a * a > 1e11) { ++ans; continue; } long nor = a * b, pir = p * a * a; if (!dic.ContainsKey(nor)) { dic.Add(nor, pir); } if (!cnt.ContainsKey(nor)) { cnt.Add(nor, 1); } else { ++cnt[nor]; } } else { ++ans; } A: continue; } int half = 0; foreach (var item in cnt) { var pir = dic[item.Key]; int c = cnt.ContainsKey(pir) ? cnt[pir] : 0; if (item.Value > c) { ans += item.Value; } else if (item.Value == c) { half += c; } } sw.WriteLine(ans + one + half / 2); sw.Flush(); }
public override IDisposable Load(Scan <byte, byte> scan) { base.Load(scan); from = -1; errs.Clear(); return(this); }
// lexer results keep available public virtual void Dispose() { scan.Dispose(); scan = null; Array.Fill(tokens, default, 0, tokenn);
public override void WriteScan(Scan scan) { writer.Flush(); long pos = output.BaseStream.Position; scanIndex.Add(scan.ScanNumber, pos); writer.WriteStartElement("scan"); writer.WriteAttributeString("num", scan.ScanNumber.ToString()); writer.WriteAttributeString("msLevel", scan.MsOrder.ToString()); writer.WriteAttributeString("scanEvent", scan.ScanEvent.ToString()); writer.WriteAttributeString("masterIndex", scan.MasterIndex.ToString()); writer.WriteAttributeString("peaksCount", scan.PeakCount.ToString()); writer.WriteAttributeString("ionInjectionTime", scan.IonInjectionTime.ToString()); writer.WriteAttributeString("elapsedScanTime", scan.ElapsedScanTime.ToString()); writer.WriteAttributeString("polarity", scan.Polarity == Polarity.Positive ? "+" : "-"); writer.WriteAttributeString("scanType", scan.ScanType.ToString()); writer.WriteAttributeString("filterLine", scan.FilterLine); if (scan.Description.Length > 0) { writer.WriteAttributeString("description", scan.Description); } writer.WriteAttributeString("retentionTime", MakeRetentionTimeString(scan.RetentionTime)); writer.WriteAttributeString("startMz", scan.StartMz.ToString()); writer.WriteAttributeString("endMz", scan.EndMz.ToString()); writer.WriteAttributeString("lowMz", scan.LowestMz.ToString()); writer.WriteAttributeString("highMz", scan.HighestMz.ToString()); writer.WriteAttributeString("basePeakMz", scan.BasePeakMz.ToString()); writer.WriteAttributeString("basePeakIntensity", scan.BasePeakIntensity.ToString()); writer.WriteAttributeString("totIonCurrent", scan.TotalIonCurrent.ToString()); writer.WriteAttributeString("faimsState", scan.FaimsState.ToString()); writer.WriteAttributeString("compensationVoltage", scan.FaimsCV.ToString()); //tSIM/MSX methods could be MS1s with "SPS" ions so no ms order consideration here if (scan.MsOrder > 1 && scan.Precursors.Count > 0) { writer.WriteAttributeString("collisionEnergy", scan.CollisionEnergy.ToString()); foreach (Precursor precursor in scan.Precursors) { writer.WriteStartElement("precursorMz"); writer.WriteAttributeString("precursorScanNum", scan.PrecursorMasterScanNumber.ToString()); writer.WriteAttributeString("precursorIntensity", precursor.Intensity.ToString()); writer.WriteAttributeString("precursorCharge", precursor.Charge.ToString()); writer.WriteAttributeString("activationMethod", scan.PrecursorActivationMethod.ToString()); writer.WriteAttributeString("isolationWidth", precursor.IsolationWidth.ToString()); writer.WriteAttributeString("isolationMz", precursor.IsolationMz.ToString()); writer.WriteString(precursor.Mz.ToString()); writer.WriteEndElement(); // precursorMz } } writer.WriteStartElement("peaks"); writer.WriteAttributeString("precision", "32"); writer.WriteAttributeString("byteOrder", "network"); writer.WriteAttributeString("contentType", "m/z-int"); writer.WriteAttributeString("compressionType", "none"); writer.WriteAttributeString("compressedLen", "0"); writer.WriteString(EncodePeaks(scan)); writer.WriteEndElement(); // peaks writer.WriteStartElement("labelData"); writer.WriteAttributeString("precision", "32"); writer.WriteAttributeString("byteOrder", "network"); writer.WriteAttributeString("contentType", "m/z-int"); writer.WriteAttributeString("compressionType", "none"); writer.WriteAttributeString("compressedLen", "0"); writer.WriteString(EncodeLabelData(scan)); writer.WriteEndElement(); // peaks writer.WriteEndElement(); // scan }
void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("sol") || other.CompareTag("mur") ){ if (controller.teleport == true) { Teleportation(); } else { Retourner(); } //Debug.Log (other); } if (other.CompareTag("Ennemi")){ Retourner(); //Debug.Log (other); if (ennemi != other.gameObject){ ennemi = other.gameObject; scan = ennemi.GetComponent<Scan> (); rigidEnemy = ennemi.GetComponent<Rigidbody2D> (); } if (transform.position.x >= ennemi.transform.position.x){ rigidEnemy.AddForce(Vector3.left * recul); } else if (transform.position.x <= ennemi.transform.position.x){ rigidEnemy.AddForce(Vector3.right * recul); } scan.vie -= 25; } if(other.CompareTag("coin")){ controller.coins = controller.coins +1; Destroy(other.gameObject); } if (other.CompareTag("key")) { controller.key = true; GUI.Label( new Rect(200, 200, 85, 25), "KEY"); Destroy(other.gameObject); } //Debug.Log (other); }
/// <summary>Regista um scan</summary> public abstract void Register( Scan scan );
public ScannerInfo(Scan s) { Scan = s; }
public byte[] CameraScan(uint deviceAddress,Scan scan) { byte mByte = AutoManualScan; if(scan == Scan.Auto) mByte = AutoManualScan+Sense; return Message.GetMessage(deviceAddress,mByte,0x00,0x00,0x00); }
public ProjectScan(Scan s, ICollection <string> fieldlist) {//构造一个有指定底层scan和字段名称列表的“投影”扫描 this.s = s; this.fieldlist = fieldlist; }
private void ProcessSos(int n) { if (nComp == 0){ throw new Exception("missing SOF marker"); } if (n < 6 || 4 + (2*nComp) < n || n%2 != 0){ throw new Exception("SOS has wrong length"); } ReadFull(tmp, 0, n); byte lnComp = tmp[0]; if (n != 4 + (2*lnComp)){ throw new Exception("SOS length inconsistent with number of components"); } Scan[] scan = new Scan[maxComponents]; int totalHv = 0; for (int i = 0; i < lnComp; i++){ int cs = tmp[1 + (2*i)]; int compIndex = -1; for (int j = 0; j < nComp; j++){ Component compv = comp[j]; if (cs == compv.c){ compIndex = j; } } if (compIndex < 0){ throw new Exception("Unknown component selector"); } scan[i].compIndex = (byte) compIndex; for (int j = 0; j < i; j++){ if (scan[i].compIndex == scan[j].compIndex){ throw new Exception("Repeated component selector"); } } totalHv += comp[compIndex].h*comp[compIndex].v; scan[i].td = (byte) (tmp[2 + (2*i)] >> 4); if (scan[i].td > maxTh){ throw new Exception("bad Td value"); } scan[i].ta = (byte) (tmp[2 + (2*i)] & 0x0f); if (scan[i].ta > maxTh){ throw new Exception("bad Ta value"); } } if (nComp > 1 && totalHv > 10){ throw new Exception("Total sampling factors too large."); } int zigStart = 0; int zigEnd = Block.blockSize - 1; int ah = 0; int al = 0; if (progressive){ zigStart = tmp[1 + (2*lnComp)]; zigEnd = tmp[2 + (2*lnComp)]; ah = tmp[3 + (2*lnComp)] >> 4; al = tmp[3 + (2*lnComp)] & 0x0f; if ((zigStart == 0 && zigEnd != 0) || zigStart > zigEnd || Block.blockSize <= zigEnd){ throw new Exception("Bad spectral selection bounds"); } if (zigStart != 0 && lnComp != 1){ throw new Exception("Progressive AC coefficients for more than one component"); } if (ah != 0 && ah != al + 1){ throw new Exception("Bad successive approximation values"); } } int h0 = comp[0].h; int v0 = comp[0].v; int mxx = (width + (8*h0) - 1)/(8*h0); int myy = (height + (8*v0) - 1)/(8*v0); if (grayImage == null && ycbcrImage == null){ MakeImg(mxx, myy); } if (progressive){ for (int i = 0; i < lnComp; i++){ int compIndex = scan[i].compIndex; if (progCoeffs[compIndex] == null){ progCoeffs[compIndex] = new Block[mxx*myy*comp[compIndex].h*comp[compIndex].v]; for (int j = 0; j < progCoeffs[compIndex].Length; j++){ progCoeffs[compIndex][j] = new Block(); } } } } bits = new BitsClass(); int mcu = 0; byte expectedRst = JpegConstants.Markers.RST0; Block b = new Block(); int[] dc = new int[maxComponents]; int blockCount = 0; for (int my = 0; my < myy; my++){ for (int mx = 0; mx < mxx; mx++){ for (int i = 0; i < lnComp; i++){ int compIndex = scan[i].compIndex; int hi = comp[compIndex].h; int vi = comp[compIndex].v; Block qt = quant[comp[compIndex].tq]; for (int j = 0; j < hi*vi; j++){ int bx; int by; if (lnComp != 1){ bx = hi*mx + j%hi; by = vi*my + j/hi; } else{ int q = mxx*hi; bx = blockCount%q; by = blockCount/q; blockCount++; if (bx*8 >= width || by*8 >= height){ continue; } } b = progressive ? progCoeffs[compIndex][@by*mxx*hi + bx] : new Block(); if (ah != 0){ Refine(b, huff[acTable, scan[i].ta], zigStart, zigEnd, 1 << al); } else{ int zig = zigStart; if (zig == 0){ zig++; byte value = DecodeHuffman(huff[dcTable, scan[i].td]); if (value > 16){ throw new Exception("Excessive DC component"); } int dcDelta = ReceiveExtend(value); dc[compIndex] += dcDelta; b[0] = dc[compIndex] << al; } if (zig <= zigEnd && eobRun > 0){ eobRun--; } else{ var huffv = huff[acTable, scan[i].ta]; for (; zig <= zigEnd; zig++){ byte value = DecodeHuffman(huffv); byte val0 = (byte) (value >> 4); byte val1 = (byte) (value & 0x0f); if (val1 != 0){ zig += val0; if (zig > zigEnd){ break; } int ac = ReceiveExtend(val1); b[unzig[zig]] = ac << al; } else{ if (val0 != 0x0f){ eobRun = (ushort) (1 << val0); if (val0 != 0){ eobRun |= (ushort) DecodeBits(val0); } eobRun--; break; } zig += 0x0f; } } } } if (progressive){ if (zigEnd != Block.blockSize - 1 || al != 0){ progCoeffs[compIndex][by*mxx*hi + bx] = b; continue; } } for (int zig = 0; zig < Block.blockSize; zig++){ b[unzig[zig]] *= qt[zig]; } IDCT.Transform(b); byte[] dst; int offset; int stride; if (nComp == 1){ dst = grayImage.pixels; stride = grayImage.stride; offset = grayImage.offset + 8*(by*grayImage.stride + bx); } else{ switch (compIndex){ case 0: dst = ycbcrImage.pix_y; stride = ycbcrImage.y_stride; offset = ycbcrImage.y_offset + 8*(by*ycbcrImage.y_stride + bx); break; case 1: dst = ycbcrImage.pix_cb; stride = ycbcrImage.c_stride; offset = ycbcrImage.c_offset + 8*(by*ycbcrImage.c_stride + bx); break; case 2: dst = ycbcrImage.pix_cr; stride = ycbcrImage.c_stride; offset = ycbcrImage.c_offset + 8*(by*ycbcrImage.c_stride + bx); break; case 3: throw new Exception("Too many components"); default: throw new Exception("Too many components"); } } for (int y = 0; y < 8; y++){ int y8 = y*8; int yStride = y*stride; for (int x = 0; x < 8; x++){ int c = b[y8 + x]; if (c < -128){ c = 0; } else if (c > 127){ c = 255; } else{ c += 128; } dst[yStride + x + offset] = (byte) c; } } } // for j } // for i mcu++; if (ri > 0 && mcu%ri == 0 && mcu < mxx*myy){ ReadFull(tmp, 0, 2); if (tmp[0] != 0xff || tmp[1] != expectedRst){ throw new Exception("Bad RST marker"); } expectedRst++; if (expectedRst == JpegConstants.Markers.RST7 + 1){ expectedRst = JpegConstants.Markers.RST0; } bits = new BitsClass(); dc = new int[maxComponents]; eobRun = 0; } } // for mx } // for my }
private MassSpectrum ReadMassSpectrum(UInt64 spectrumId) { BafSqlSpectrum bafSpec = linq2BafSql.GetBafSqlSpectrum(this.linq2BafSql.Core, spectrumId); if (bafSpec == null) { throw new MzLiteIOException("No spectrum found for id: " + spectrumId); } MassSpectrum ms = new MassSpectrum(spectrumId.ToString()); // determine ms level BafSqlAcquisitionKey aqKey = linq2BafSql.GetBafSqlAcquisitionKey(this.linq2BafSql.Core, bafSpec.AcquisitionKey); Nullable <int> msLevel = null; if (aqKey != null && aqKey.MsLevel.HasValue) { // bruker starts ms level by 0, must be added by 1 msLevel = aqKey.MsLevel.Value + 1; ms.SetMsLevel(msLevel.Value); } // determine type of spectrum and read peak data // if profile data available we prefer to get profile data otherwise centroided data (line spectra) if (bafSpec.ProfileMzId.HasValue && bafSpec.ProfileIntensityId.HasValue) { ms.SetProfileSpectrum(); } else if (bafSpec.LineMzId.HasValue && bafSpec.LineIntensityId.HasValue) { ms.SetCentroidSpectrum(); } if (msLevel == 1) { ms.SetMS1Spectrum(); } else if (msLevel > 1) { ms.SetMSnSpectrum(); } // scan if (bafSpec.Rt.HasValue) { Scan scan = new Scan(); scan.SetScanStartTime(bafSpec.Rt.Value).UO_Second(); ms.Scans.Add(scan); } // precursor if (msLevel > 1) { SpectrumVariableCollection spectrumVariables = SpectrumVariableCollection.ReadSpectrumVariables(linq2BafSql, bafSpec.Id); Precursor precursor = new Precursor(); decimal value; if (spectrumVariables.TryGetValue("Collision_Energy_Act", supportedVariables, out value)) { precursor.Activation.SetCollisionEnergy(Decimal.ToDouble(value)); } if (spectrumVariables.TryGetValue("MSMS_IsolationMass_Act", supportedVariables, out value)) { precursor.IsolationWindow.SetIsolationWindowTargetMz(Decimal.ToDouble(value)); } if (spectrumVariables.TryGetValue("Quadrupole_IsolationResolution_Act", supportedVariables, out value)) { double width = Decimal.ToDouble(value) * 0.5d; precursor.IsolationWindow.SetIsolationWindowUpperOffset(width); precursor.IsolationWindow.SetIsolationWindowLowerOffset(width); } Nullable <int> charge = null; if (spectrumVariables.TryGetValue("MSMS_PreCursorChargeState", supportedVariables, out value)) { charge = Decimal.ToInt32(value); } IEnumerable <BafSqlStep> ions = linq2BafSql.GetBafSqlSteps(this.linq2BafSql.Core, bafSpec.Id); foreach (BafSqlStep ion in ions) { if (ion.Mass.HasValue) { SelectedIon selectedIon = new SelectedIon(); precursor.SelectedIons.Add(selectedIon); selectedIon.SetSelectedIonMz(ion.Mass.Value); selectedIon.SetUserParam("Number", ion.Number.Value); selectedIon.SetUserParam("IsolationType", ion.IsolationType.Value); selectedIon.SetUserParam("ReactionType", ion.ReactionType.Value); selectedIon.SetUserParam("MsLevel", ion.MsLevel.Value); if (charge.HasValue) { selectedIon.SetChargeState(charge.Value); } } } // set parent spectrum as reference if (bafSpec.Parent.HasValue) { precursor.SpectrumReference = new SpectrumReference(bafSpec.Parent.ToString()); } ms.Precursors.Add(precursor); } return(ms); }
/// <summary> /// The time that an analyzer started a scan, relative to the start of the MS run. [PSI:MS] /// </summary> public static IHasUnit <Scan> SetScanStartTime( this Scan scan, double value) { return(scan.SetCvParam(ScanStartTime, value)); }
/// <summary> /// </summary> /// <param name="rawFile"></param> /// <param name="filename"></param> /// <param name="L"></param> public static void WriteSpectrumAsRcode(this IRawDataPlus rawFile, string filename, List <int> L) { int count = 1; using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename)) { foreach (int scanNumber in L) { var trailerFields = rawFile.GetTrailerExtraHeaderInformation(); var basepeakMass = -1.0; var basepeakIntensity = -1.0; var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber); var centroidStream = rawFile.GetCentroidStream(scanNumber, false); var scanTrailer = rawFile.GetTrailerExtraInformation(scanNumber); var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber); int indexCharge = -1; int indexMonoisotopicmZ = -1; try { indexMonoisotopicmZ = trailerFields .Select((item, index) => new { name = item.Label.ToString().CleanRawfileTrailerHeader(), Position = index }) .First(x => x.name.Contains("MonoisotopicmZ")).Position; } catch { indexMonoisotopicmZ = -1; } try { indexCharge = trailerFields .Select((item, index) => new { name = item.Label.ToString(), Position = index }) .First(x => x.name.Contains("Charge State")).Position; } catch { indexCharge = -1; } var scan = Scan.FromFile(rawFile, scanNumber); file.WriteLine("e$Spectrum[[{0}]] <- list(", count++); file.WriteLine("\tscan = {0},", scanNumber); try { basepeakMass = (scanStatistics.BasePeakMass); basepeakIntensity = Math.Round(scanStatistics.BasePeakIntensity); file.WriteLine("\tbasePeak = c({0}, {1}),", basepeakMass, basepeakIntensity); } catch { file.WriteLine("\tbasePeak = c(NA, NA),"); } file.WriteLine("\tTIC = {0},", scanStatistics.TIC.ToString()); file.WriteLine("\tmassRange = c({0}, {1}),", scanStatistics.LowMass.ToString(), scanStatistics.HighMass.ToString()); file.WriteLine("\tscanType = \"{0}\",", scanStatistics.ScanType.ToString()); file.WriteLine("\trtinseconds = {0},", Math.Round(scanStatistics.StartTime * 60 * 1000) / 1000); try { var reaction0 = scanEvent.GetReaction(0); file.WriteLine("\tpepmass = {0},", reaction0.PrecursorMass); } catch { file.WriteLine("\tpepmass = NA,"); } if (scanStatistics.IsCentroidScan && centroidStream.Length > 0) { // Get the centroid (label) data from the RAW file for this scan file.WriteLine("\tcentroidStream = TRUE,"); file.WriteLine("\tHasCentroidStream = '{0}, Length={1}',", scan.HasCentroidStream, scan.CentroidScan.Length); if (scan.HasCentroidStream) { file.WriteLine("\tcentroid.mZ = c(" + string.Join(", ", scan.CentroidScan.Masses.ToArray()) + "),"); file.WriteLine("\tcentroid.intensity = c(" + string.Join(", ", scan.CentroidScan.Intensities.ToArray()) + "),"); } file.WriteLine("\ttitle = \"File: {0}; SpectrumID: {1}; scans: {2}\",", Path.GetFileName(rawFile.FileName), null, scanNumber); if (indexMonoisotopicmZ > 0) { file.WriteLine("\tmonoisotopicMz = {0},", Convert.ToDouble(scanTrailer.Values.ToArray()[indexMonoisotopicmZ])); } else { file.WriteLine("\tmonoisotopicMz = NA,"); } if (indexCharge > 0) { file.WriteLine("\tcharge = {0},", int.Parse(scanTrailer.Values.ToArray()[indexCharge])); } else { file.WriteLine("\tcharge = NA,"); } file.WriteLine("\tmZ = c(" + string.Join(", ", centroidStream.Masses) + "),"); file.WriteLine("\tintensity = c(" + string.Join(", ", centroidStream.Intensities) + "),"); file.WriteLine("\tnoises = c(" + string.Join(", ", centroidStream.Noises) + "),"); file.WriteLine("\tresolutions = c(" + string.Join(", ", centroidStream.Resolutions.ToArray()) + "),"); file.WriteLine("\tcharges = c(" + string.Join(", ", centroidStream.Charges) + "),"); file.WriteLine("\tbaselines = c(" + string.Join(", ", centroidStream.Baselines) + "),"); } else { file.WriteLine("\tcentroidStream = FALSE,"); file.WriteLine("\tHasCentroidStream = '{0}, Length={1}',", scan.HasCentroidStream, scan.CentroidScan.Length); if (scan.HasCentroidStream) { file.WriteLine("\tcentroid.mZ = c(" + string.Join(",", scan.CentroidScan.Masses.ToArray()) + "),"); file.WriteLine("\tcentroid.intensity = c(" + string.Join(",", scan.CentroidScan.Intensities.ToArray()) + "),"); } file.WriteLine("\ttitle = \"File: {0}; SpectrumID: {1}; scans: {2}\",", Path.GetFileName(rawFile.FileName), null, scanNumber); if (indexCharge > 0) { file.WriteLine("\tcharge = {0},", int.Parse(scanTrailer.Values.ToArray()[indexCharge])); } else { file.WriteLine("\tcharge = NA,"); } if (indexMonoisotopicmZ > 0) { file.WriteLine("\tmonoisotopicMz = {0},", Convert.ToDouble(scanTrailer.Values.ToArray()[indexMonoisotopicmZ])); } else { file.WriteLine("\tmonoisotopicMz = NA,"); } file.WriteLine("\tmZ = c(" + string.Join(",", scan.SegmentedScan.Positions) + "),"); file.WriteLine("\tintensity = c(" + string.Join(",", scan.SegmentedScan.Intensities) + "),"); } // ============= Instrument Data ============= // write scan Trailer var trailerValues = scanTrailer.Values; var trailerLabels = scanTrailer.Labels; var zipTrailer = trailerLabels.ToArray().Zip(trailerValues, (a, b) => string.Format("\t\"{0}\" = \"{1}\"", a, b)); file.WriteLine(string.Join(", \n", zipTrailer)); file.WriteLine(")"); } } return; }
protected bool GetDarkScan () { bool bRet = false; TurnOffLamp (); AddOutputText("Getting Dark Scan\r"); RefreshUI(); UInt16[] data; if (GetCoaddedScans (out data)) { bRet = true; darkScan = new Scan(xAxis, data); } return bRet; }
public void Initialize() { string tempPath = Path.GetTempPath(); Scan ms2scan1 = new Scan(false, 1, 1, 0, 2, 2, 1, 100.00, tempPath) { }; Scan ms2scan2 = new Scan(false, 1, 1, 20, 2, 2, 1, 100000.02, tempPath) { }; Scan ms2scan3 = new Scan(false, 5, 5, 30, 2, 4, 2, 30, tempPath) { }; Scan ms2scan4 = new Scan(false, 5, 5, 32, 2, 4, 2, 20010.33, tempPath) { }; Scan ms2scan5 = new Scan(false, 5, 5, 34, 2, 4, 2, 50.33, tempPath) { }; Scan ms2scan6 = new Scan(false, 1, 1, 35, 2, 4, 2, 4000, tempPath) { }; Scan ms2scan7 = new Scan(false, 1, 1, 70, 2, 5, 3, 60000, tempPath) { }; Scan ms2scan8 = new Scan(false, 1, 1, 70, 2, 5, 3, 6000, tempPath) { }; Scan ms2scan9 = new Scan(false, tempPath) { ScanStartTime = 0, MsLevel = 2, Density = 5, TotalIonCurrent = 8000 }; //MS1scans Scan ms1scan1 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 1, IsolationWindowUpperOffset = 1, ScanStartTime = 0, MsLevel = 1, Density = 2, Cycle = 1, TotalIonCurrent = 1000, BasePeakIntensity = 1000, BasePeakMz = 1058 }; Scan ms1scan2 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowUpperOffset = 5, ScanStartTime = 30, MsLevel = 1, Density = 4, Cycle = 2, TotalIonCurrent = 3050, BasePeakIntensity = 1500, BasePeakMz = 459 }; Scan ms1scan3 = new Scan(false, tempPath) { IsolationWindowLowerOffset = 5, IsolationWindowUpperOffset = 5, ScanStartTime = 70, MsLevel = 1, Density = 4, Cycle = 3, TotalIonCurrent = 3050, BasePeakIntensity = 5000, BasePeakMz = 150 }; //BasePeaks: var spectrumpoint1 = new SpectrumPoint(2000, 150, 2.58F) { }; var spectrumpoint2 = new SpectrumPoint(3000, 150.01F, 3.00F) { }; var spectrumpoint3 = new SpectrumPoint(3000, 150.01F, 60F) { }; var basePeak1 = new BasePeak(150, 2.5, 150) { BpkRTs = new List <double>() { 2.5 }, Spectrum = new List <SpectrumPoint>() { spectrumpoint1, spectrumpoint2 }, Mz = 150 }; basePeak1.RTsegments.Add(2); basePeak1.FWHMs.Add(1); basePeak1.FWHMs.Add(2); basePeak1.Peaksyms.Add(1); basePeak1.Peaksyms.Add(2); basePeak1.Intensities.Add(2); basePeak1.FullWidthBaselines.Add(1); basePeak1.FullWidthBaselines.Add(2); var basePeak2 = new BasePeak(300, 60, 150) { BpkRTs = new List <double>() { 60 }, Spectrum = new List <SpectrumPoint>() { spectrumpoint3 } }; basePeak2.FWHMs.Add(2); basePeak2.Peaksyms.Add(1); basePeak2.FullWidthBaselines.Add(1); //Runs: Ms2andms1Run = new Run <Scan> { AnalysisSettings = new AnalysisSettings { RtTolerance = 2.5 }, LastScanTime = 100, StartTime = 0 }; Ms2andms1Run.Ms2Scans.AddRange(new List <Scan>() { ms2scan1, ms2scan2, ms2scan3, ms2scan4, ms2scan5, ms2scan6, ms2scan7, ms2scan8 }); Ms2andms1Run.Ms1Scans.AddRange(new List <Scan>() { ms1scan1, ms1scan2, ms1scan3 }); Ms2andms1Run.BasePeaks.Add(basePeak1); Ms2andms1Run.BasePeaks.Add(basePeak2); Ms2andms1Run.SourceFileNames.Add(" "); Ms2andms1Run.SourceFileChecksums.Add(" "); Emptyms2scansRun = new Run <Scan> { AnalysisSettings = new AnalysisSettings { RtTolerance = 2.5 }, LastScanTime = 0, StartTime = 1000000 }; Emptyms2scansRun.Ms2Scans.AddRange(new List <Scan>() { ms2scan1, ms2scan2, ms2scan3, ms2scan4, ms2scan9 }); //9 does not have upper and lower offsets Emptyms2scansRun.BasePeaks.Add(basePeak1); Emptyms2scansRun.SourceFileNames.Add(" "); Emptyms2scansRun.SourceFileChecksums.Add(" "); RTGrouper = new RTGrouper(); Result = RTGrouper.DivideByRT(Ms2andms1Run, 2, 100); }
protected bool GetLightScan () { bool bRet = false; TurnOnLamp (); AddOutputText("Getting Light Scan\r"); RefreshUI(); UInt16[] data; if (GetCoaddedScans (out data)) { bRet = true; lightScan = new Scan(xAxis, data); RemoveDark(ref lightScan); } TurnOffLamp(); return bRet; }
/// <inheritdoc /> public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber) { ConfigureWriter(".mgf"); using (Writer) { Log.Info("Processing " + (lastScanNumber - firstScanNumber + 1) + " scans"); var lastScanProgress = 0; for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) { if (!ParseInput.Verbose) { var scanProgress = (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); if (scanProgress % ProgressPercentageStep == 0) { if (scanProgress != lastScanProgress) { Console.Write("" + scanProgress + "% "); lastScanProgress = scanProgress; } } } // Get each scan from the RAW file var scan = Scan.FromFile(rawFile, scanNumber); // Check to see if the RAW file contains label (high-res) data and if it is present // then look for any data that is out of order var time = rawFile.RetentionTimeFromScanNumber(scanNumber); // Get the scan filter for this scan number var scanFilter = rawFile.GetFilterForScanNumber(scanNumber); // Get the scan event for this scan number var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber); IReaction reaction = null; switch (scanFilter.MSOrder) { case MSOrderType.Ms: // Keep track of scan number for precursor reference _precursorScanNumber = scanNumber; break; case MSOrderType.Ms2: try { reaction = scanEvent.GetReaction(0); } catch (ArgumentOutOfRangeException exception) { Log.Warn("No reaction found for scan " + scanNumber); } goto default; case MSOrderType.Ms3: { try { reaction = scanEvent.GetReaction(1); } catch (ArgumentOutOfRangeException exception) { Log.Warn("No reaction found for scan " + scanNumber); } goto default; } default: Writer.WriteLine("BEGIN IONS"); Writer.WriteLine($"TITLE={ConstructSpectrumTitle(scanNumber)}"); Writer.WriteLine($"SCANS={scanNumber}"); Writer.WriteLine( $"RTINSECONDS={(time * 60).ToString(CultureInfo.InvariantCulture)}"); // trailer extra data list var trailerData = rawFile.GetTrailerExtraInformation(scanNumber); int? charge = null; double?monoisotopicMz = null; double?isolationWidth = null; for (var i = 0; i < trailerData.Length; i++) { if (trailerData.Labels[i] == "Charge State:") { if (Convert.ToInt32(trailerData.Values[i]) > 0) { charge = Convert.ToInt32(trailerData.Values[i]); } } if (trailerData.Labels[i] == "Monoisotopic M/Z:") { monoisotopicMz = double.Parse(trailerData.Values[i], NumberStyles.Any, CultureInfo.CurrentCulture); } if (trailerData.Labels[i] == "MS" + (int)scanFilter.MSOrder + " Isolation Width:") { isolationWidth = double.Parse(trailerData.Values[i], NumberStyles.Any, CultureInfo.CurrentCulture); } } if (reaction != null) { var selectedIonMz = CalculateSelectedIonMz(reaction, monoisotopicMz, isolationWidth); Writer.WriteLine("PEPMASS=" + selectedIonMz.ToString(CultureInfo.InvariantCulture)); } // charge if (charge != null) { // Scan polarity var polarity = PositivePolarity; if (scanFilter.Polarity == PolarityType.Negative) { polarity = NegativePolarity; } Writer.WriteLine($"CHARGE={charge}{polarity}"); } // write the filter string //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}"); // Check if the scan has a centroid stream if (scan.HasCentroidStream && (scanEvent.ScanData == ScanDataType.Centroid || (scanEvent.ScanData == ScanDataType.Profile && !ParseInput.NoPeakPicking))) { var centroidStream = rawFile.GetCentroidStream(scanNumber, false); if (scan.CentroidScan.Length > 0) { for (var i = 0; i < centroidStream.Length; i++) { Writer.WriteLine( centroidStream.Masses[i].ToString("0.0000000", CultureInfo.InvariantCulture) + " " + centroidStream.Intensities[i].ToString("0.0000000000", CultureInfo.InvariantCulture)); } } } // Otherwise take the profile data else { // Get the scan statistics from the RAW file for this scan number var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber); // Get the segmented (low res and profile) scan data var segmentedScan = rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics); for (var i = 0; i < segmentedScan.Positions.Length; i++) { Writer.WriteLine( segmentedScan.Positions[i].ToString("0.0000000", CultureInfo.InvariantCulture) + " " + segmentedScan.Intensities[i].ToString("0.0000000000", CultureInfo.InvariantCulture)); } } Writer.WriteLine("END IONS"); Log.Debug("Spectrum written to file -- SCAN " + scanNumber); break; } } if (!ParseInput.Verbose) { Console.WriteLine(); } } }
protected void ComputeAbsorbance () { double[] yVals = new double[pixelCount]; for (int i = 0; i < pixelCount; i++) { if (sampleScan.yVals[i] != 0) { yVals[i] = Math.Log(lightScan.yVals[i] / sampleScan.yVals[i]); } else { yVals[i] = 0; } } absorbanceSpectrum = new Scan(xAxis, yVals); }
/// <summary> /// Get the spectrum intensity. /// </summary> /// <param name="rawFile">the RAW file object</param> /// <param name="precursorScanNumber">the precursor scan number</param> protected static double?GetPrecursorIntensity(IRawDataPlus rawFile, int precursorScanNumber, double precursorMass, double retentionTime, double?isolationWidth) { double?precursorIntensity = null; // Get the scan from the RAW file var scan = Scan.FromFile(rawFile, precursorScanNumber); // Check if the scan has a centroid stream if (scan.HasCentroidStream) { var centroidStream = rawFile.GetCentroidStream(precursorScanNumber, false); if (scan.CentroidScan.Length > 0) { for (var i = 0; i < centroidStream.Length; i++) { if (Math.Abs(precursorMass - centroidStream.Masses[i]) < Tolerance) { //Console.WriteLine(Math.Abs(precursorMass - centroidStream.Masses[i])); //Console.WriteLine(precursorMass + " - " + centroidStream.Masses[i] + " - " + // centroidStream.Intensities[i]); precursorIntensity = centroidStream.Intensities[i]; break; } } } } else { rawFile.SelectInstrument(Device.MS, 1); var component = new Component { MassRange = new Limit { Low = (double)(precursorMass - isolationWidth / 2), High = (double)(precursorMass + isolationWidth / 2) }, RtRange = new Limit { Low = rawFile.RetentionTimeFromScanNumber(precursorScanNumber), High = rawFile.RetentionTimeFromScanNumber(precursorScanNumber) } }; ; IChromatogramSettings[] allSettings = { new ChromatogramTraceSettings(TraceType.MassRange) { Filter = Component.Filter, MassRanges = new[] { new Range(component.MassRange.Low, component.MassRange.High) } } }; var rtFilteredScans = rawFile.GetFilteredScansListByTimeRange("", component.RtRange.Low, component.RtRange.High); var data = rawFile.GetChromatogramData(allSettings, rtFilteredScans[0], rtFilteredScans[rtFilteredScans.Count - 1]); var chromatogramTrace = ChromatogramSignal.FromChromatogramData(data); } return(precursorIntensity); }
public Scan (Scan source) { xVals = new double[source.xVals.Length]; yVals = new double[source.yVals.Length]; source.xVals.CopyTo(xVals, 0); source.yVals.CopyTo(yVals, 0); }
// Todo: Make into array returning task public static void Run3(Scan scan) { //Scanning = true; var deltas = new float[FEATURE_COUNT_LIMIT]; using (var fileImageBase = new MagickImage(scan.CurrentFrame.Bitmap)) { Parallel.ForEach(CompiledFeatures.CWatchZones, (CWatchZone) => { var thumbGeo = CWatchZone.MagickGeometry; using (var fileImageCropped = fileImageBase.Clone(CWatchZone.MagickGeometry)) { Parallel.ForEach(CWatchZone.CWatches, (CWatcher) => { fileImageCropped.ColorSpace = CWatcher.ColorSpace; // Can safely change since it doesn't directly affect pixel data. using (var fileImageComposed = GetComposedImage(fileImageCropped, CWatcher.Channel)) { if (CWatcher.Equalize) { fileImageComposed.Equalize(); } if (CWatcher.IsStandardCheck) { Parallel.ForEach(CWatcher.CWatchImages, (CWatchImage) => { using (var deltaImage = CWatchImage.MagickImage.Clone()) using (var fileImageCompare = fileImageComposed.Clone()) { if (CWatchImage.HasAlpha) { fileImageCompare.Composite(deltaImage, CompositeOperator.CopyAlpha); } var imageDelta = (float)deltaImage.Compare(fileImageCompare, CWatcher.ErrorMetric); deltas[CWatchImage.Index] = imageDelta; /* * if (CurrentIndex % 300 == 0 && CWatchImage.Index == 0) * { * fileImageCompare.Write(@"E:\test2.png"); * deltaImage.Write(@"E:\test3.png"); * fileImageComposed.Write(@"E:\test4.png"); * fileImageCropped.Write(@"E:\test5.png"); * fileImageBase.Write(@"E:\test6.png"); * } */ } }); } else if (CWatcher.IsDuplicateFrameCheck) { using (var deltaImagePre = new MagickImage((Bitmap)scan.PreviousFrame.Bitmap.Clone())) using (var fileImageCompare = (MagickImage)fileImageComposed.Clone()) { if (NeedExtent) { deltaImagePre.Extent(TrueCropGeometry.ToMagick(), Gravity.Northwest, MagickColor.FromRgba(0, 0, 0, 0)); } else { deltaImagePre.Crop(TrueCropGeometry.ToMagick(), Gravity.Northwest); } deltaImagePre.RePage(); deltaImagePre.Crop(thumbGeo, Gravity.Northwest); deltaImagePre.ColorSpace = CWatcher.ColorSpace; using (var deltaImage = GetComposedImage(deltaImagePre, CWatcher.Channel)) { if (CWatcher.Equalize) { fileImageCompare.Equalize(); } var imageDelta = (float)deltaImage.Compare(fileImageCompare, CWatcher.ErrorMetric); deltas[31] = imageDelta; } } } } }); } }); } Scanning = false; deltas[19] = 456.789F; Interlocked.Exchange(ref Program.floatArray, deltas); Interlocked.Exchange(ref Program.timeDelta, scan.TimeDelta); Interlocked.Increment(ref Program.count); scan.Clean(); }
void Start(){ scan = gameObject.GetComponent<Scan>(); target = GameObject.Find ("Player"); }
public void WriteScan(Scan scan) { writer.WriteStartElement("spectrum"); // Get position of spectrum tag for index. // Flush after writing since the previous tag isnt closed // until the spectrum tag is written. writer.Flush(); long pos = output.BaseStream.Position - 9; // pos - length of "<spectrum" scanIndex.Add(scan.ScanNumber, pos); writer.WriteAttributeString("index", (scan.ScanNumber - 1).ToString()); writer.WriteAttributeString("id", "scan=" + scan.ScanNumber.ToString()); writer.WriteAttributeString("defaultArrayLength", scan.PeakCount.ToString()); WriteCVParam("MS:1000511", scan.MsOrder.ToString()); if (scan.MsOrder > 1) { WriteCVParam("MS:1000580", ""); } else { WriteCVParam("MS:1000579", ""); } switch (scan.Polarity) { case Polarity.Positive: WriteCVParam("MS:1000130", ""); break; case Polarity.Negative: WriteCVParam("MS:1000129", ""); break; default: break; } WriteCVParam("MS:1000127", ""); // centroid spectrum WriteCVParam("MS:1000504", scan.BasePeakMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); WriteCVParam("MS:1000505", scan.BasePeakIntensity.ToString(), "MS:1000131"); WriteCVParam("MS:1000285", scan.TotalIonCurrent.ToString()); WriteCVParam("MS:1000528", scan.LowestMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); WriteCVParam("MS:1000527", scan.HighestMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); // No support for combined scans yet. writer.WriteStartElement("scanList"); writer.WriteAttributeString("count", "1"); WriteCVParam("MS:1000795", ""); // not a combined scan writer.WriteStartElement("scan"); writer.WriteAttributeString("instrumentConfigurationRef", "IC1"); // time in minutes WriteCVParam("MS:1000016", scan.RetentionTime.ToString(), "UO:0000031"); WriteCVParam("MS:1000512", scan.FilterLine); writer.WriteStartElement("scanWindowList"); writer.WriteAttributeString("count", "1"); writer.WriteStartElement("scanWindow"); WriteCVParam("MS:1000501", scan.StartMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); WriteCVParam("MS:1000500", scan.EndMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); writer.WriteEndElement(); // scanWindow writer.WriteEndElement(); // scanWindowList writer.WriteEndElement(); // scan writer.WriteEndElement(); // scanList if (scan.Precursors.Count > 0) { writer.WriteStartElement("precursorList"); writer.WriteAttributeString("count", scan.Precursors.Count.ToString()); foreach (var precursor in scan.Precursors) { writer.WriteStartElement("precursor"); writer.WriteAttributeString("spectrumRef", "scan=" + scan.PrecursorMasterScanNumber.ToString()); writer.WriteStartElement("isolationWindow"); WriteCVParam("MS:1000827", precursor.IsolationMz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); WriteCVParam("MS:1000828", precursor.IsolationWidth.ToString(), "MS:1000040"); WriteCVParam("MS:1000829", precursor.IsolationWidth.ToString(), "MS:1000040"); writer.WriteEndElement(); // isolationWindow writer.WriteStartElement("selectedIonList"); writer.WriteAttributeString("count", "1"); writer.WriteStartElement("selectedIon"); WriteCVParam("MS:1000633", precursor.Charge.ToString()); WriteCVParam("MS:1000827", precursor.Mz.ToString("G17", CultureInfo.InvariantCulture), "MS:1000040"); writer.WriteEndElement(); // selectedIon writer.WriteEndElement(); // selectedIonList writer.WriteStartElement("activation"); WriteCVParam("MS:1000133", ""); // CID WriteCVParam("MS:1000045", scan.CollisionEnergy.ToString(), "UO:0000266"); writer.WriteEndElement(); // activation writer.WriteEndElement(); // precursor } writer.WriteEndElement(); // precursorList } writer.WriteStartElement("binaryDataArrayList"); writer.WriteAttributeString("count", "2"); string mzData = EncodePeaks(scan, false); writer.WriteStartElement("binaryDataArray"); writer.WriteAttributeString("encodedLength", mzData.Length.ToString()); WriteCVParam("MS:1000521", ""); // 32-bit float WriteCVParam("MS:1000576", ""); // no compression WriteCVParam("MS:1000514", "", "MS:1000040"); // m/z array writer.WriteStartElement("binary"); writer.WriteString(mzData); writer.WriteEndElement(); // binary writer.WriteEndElement(); // binaryDataArray string intensityData = EncodePeaks(scan, true); writer.WriteStartElement("binaryDataArray"); writer.WriteAttributeString("encodedLength", intensityData.Length.ToString()); WriteCVParam("MS:1000521", ""); // 32-bit float WriteCVParam("MS:1000576", ""); // no compression WriteCVParam("MS:1000515", "", "MS:1000131"); // intensity array writer.WriteStartElement("binary"); writer.WriteString(intensityData); writer.WriteEndElement(); // binary writer.WriteEndElement(); // binaryDataArray writer.WriteEndElement(); // binaryDataArrayList writer.WriteEndElement(); // spectrum }
public static void UpdateScan(Scan current, ScanStatus status, int?nodeId, string processErrors) { entityRepository.UpdateScan(current, status, nodeId, processErrors); }
//Next are the implementations of the MockApi, delete methods when the API exists. public void addScan(Scan scan) { MockAPI.MockAPI.addScan(scan); }
private static MzLite.Model.MassSpectrum GetSpectrum( Batch batch, MassSpectrometerSample sample, MSExperiment msExp, int sampleIndex, int experimentIndex, int scanIndex) { MassSpectrumInfo wiffSpectrum = msExp.GetMassSpectrumInfo(scanIndex); MzLite.Model.MassSpectrum mzLiteSpectrum = new Model.MassSpectrum(ToSpectrumID(sampleIndex, experimentIndex, scanIndex)); // spectrum IParamEdit paramEdit = mzLiteSpectrum.BeginParamEdit(); paramEdit.MS_MsLevel(wiffSpectrum.MSLevel); if (wiffSpectrum.CentroidMode) { paramEdit.MS_CentroidSpectrum(); } else { paramEdit.MS_ProfileSpectrum(); } // scan Scan scan = new Scan(); scan.BeginParamEdit() .MS_ScanStartTime(wiffSpectrum.StartRT) .UO_Minute(); mzLiteSpectrum.Scans.Add(scan); // precursor if (wiffSpectrum.IsProductSpectrum) { Precursor precursor = new Precursor(); double isoWidth; double targetMz; if (GetIsolationWindow(wiffSpectrum.Experiment, out isoWidth, out targetMz)) { precursor.IsolationWindow.BeginParamEdit() .MS_IsolationWindowTargetMz(targetMz) .MS_IsolationWindowUpperOffset(isoWidth) .MS_IsolationWindowLowerOffset(isoWidth); } SelectedIon selectedIon = new SelectedIon(); selectedIon.BeginParamEdit() .MS_SelectedIonMz(wiffSpectrum.ParentMZ) .MS_ChargeState(wiffSpectrum.ParentChargeState); precursor.SelectedIons.Add(selectedIon); precursor.Activation.BeginParamEdit() .MS_CollisionEnergy(wiffSpectrum.CollisionEnergy); mzLiteSpectrum.Precursors.Add(precursor); } return(mzLiteSpectrum); }
void AddScanedImages() { Scan scanner = new Scan() { ImageDirectory = Directory.GetCurrentDirectory(), }; scanner.ShowDialog(); List<IScannedImage> images = scanner.ScannedImages; if (images == null) return; AddImages(images.Select(X => Path.Combine(X.ImagePath, X.FileName)).ToList()); }
/// <summary> /// Writes a scan to the mzdb file. /// </summary> public void WriteScan(Scan scan) { double precursorMH = 0; double precursorMz = 0; int charge = 0; if (scan.Precursors.Count > 0) { precursorMH = scan.Precursors[0].Mh; precursorMz = scan.Precursors[0].Mz; charge = scan.Precursors[0].Charge; } scanInsert.Parameters.AddWithValue("$id", ++scanIndex); scanInsert.Parameters.AddWithValue("$scan", scan.ScanNumber); // No support for merged scans yet. scanInsert.Parameters.AddWithValue("$last_scan", scan.ScanNumber); // RT in min scanInsert.Parameters.AddWithValue("$time", scan.RetentionTime); scanInsert.Parameters.AddWithValue("$precursor_mh", precursorMH); scanInsert.Parameters.AddWithValue("$precursor_mz", precursorMz); scanInsert.Parameters.AddWithValue("$charge", charge); scanInsert.Parameters.AddWithValue("$total_intensity", scan.TotalIonCurrent); scanInsert.Parameters.AddWithValue("$polarity", scan.Polarity == Polarity.Negative ? "-" : "+"); scanInsert.Parameters.AddWithValue("$base_peak_mz", scan.BasePeakMz); scanInsert.Parameters.AddWithValue("$base_peak_intensity", scan.BasePeakIntensity); scanInsert.Parameters.AddWithValue("$start_mz", scan.StartMz); scanInsert.Parameters.AddWithValue("$end_mz", scan.EndMz); scanInsert.Parameters.AddWithValue("$low_mz", scan.LowestMz); scanInsert.Parameters.AddWithValue("$high_mz", scan.HighestMz); scanInsert.Parameters.AddWithValue("$parent_scan", scan.PrecursorMasterScanNumber); scanInsert.Parameters.AddWithValue("$filter_line", scan.FilterLine); scanInsert.Parameters.AddWithValue("$detector_type", scan.DetectorType); scanInsert.Parameters.AddWithValue("$activation_type", scan.PrecursorActivationMethod); scanInsert.Parameters.AddWithValue("$activation_energy", scan.CollisionEnergy); scanInsert.Parameters.AddWithValue("$ms_level", scan.MsOrder); scanInsert.Parameters.AddWithValue("$scan_type", scan.ScanType); scanInsert.Parameters.AddWithValue("$parent_type", ""); scanInsert.Parameters.AddWithValue("$master_index", scan.MasterIndex); scanInsert.Parameters.AddWithValue("$scan_event", scan.ScanEvent); scanInsert.Parameters.AddWithValue("$peak_count", scan.Centroids.Count); scanInsert.Parameters.AddWithValue("$ion_injection_time", scan.IonInjectionTime); scanInsert.Parameters.AddWithValue("$elapsed_scan_time", scan.ElapsedScanTime); scanInsert.Parameters.AddWithValue("$cv", scan.FaimsCV); scanInsert.ExecuteNonQuery(); peakInsert.Parameters.AddWithValue("$id", ++peakIndex); peakInsert.Parameters.AddWithValue("$scan", scan.ScanNumber); peakInsert.Parameters.AddWithValue("$peak_count", scan.Centroids.Count); peakInsert.Parameters.AddWithValue("$data_type", getPeakFlags(scan)); // skipping compression for now. peakInsert.Parameters.AddWithValue("$data", encodePeaks(scan)); peakInsert.ExecuteNonQuery(); foreach (Precursor precursor in scan.Precursors) { precursorInsert.Parameters.AddWithValue("$id", ++precursorIndex); precursorInsert.Parameters.AddWithValue("$scan", scan.ScanNumber); precursorInsert.Parameters.AddWithValue("$precursor_mz", precursor.Mz); precursorInsert.Parameters.AddWithValue("$precursor_mh", precursor.Mh); precursorInsert.Parameters.AddWithValue("$precursor_charge", precursor.Charge); precursorInsert.Parameters.AddWithValue("$original_mz", precursor.Mz); precursorInsert.Parameters.AddWithValue("$original_charge", precursor.Charge); precursorInsert.Parameters.AddWithValue("$isolation_mz", precursor.IsolationMz); precursorInsert.Parameters.AddWithValue("$isolation_width", precursor.IsolationWidth); precursorInsert.Parameters.AddWithValue("$isolation_specificity", precursor.IsolationSpecificity); precursorInsert.Parameters.AddWithValue("$precursor_intensity", precursor.Intensity); precursorInsert.ExecuteNonQuery(); } }
protected override void OnSetup() { cachedScan = Agent.GetAbility <Scan>(); }
/// <summary>Gera o cdigo dos relatrios de scan</summary> private void GenerateScanReport( StringWriter writer, Scan[] scans ) { Ruler ruler = getRuler(); writer.Write("<tr class='resourceTitle'>"); writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("turn_current")); if( ShowSourcePlanet ) { writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("section_planet")); } writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("scan_target")); writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("section_ruler")); writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("scan_success")); writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("scan_cloaked")); writer.Write("<td class='resourceTitle'>{0}</td>", info.getContent("scan_report")); writer.Write("</tr>"); foreach( Scan scan in scans ) { writer.Write("<tr onmouseover='overResource(this);' onmouseout='outResource(this);'>"); writer.Write("<td class='resourceCell'>{0}</td>", scan.Turn); if( ShowSourcePlanet ) { writer.Write("<td class='resourceCell'><a href='{0}default.aspx?id={2}'>{1}</a></td>", OrionGlobals.getSectionUrl("scan"), ruler.getPlanet(scan.SourcePlanetId).Name, scan.SourcePlanetId); } writer.Write("<td class='resourceCell'>{0}</td>", scan.Target.ToString()); if( scan.TargetPlanetOwner >= 0 ) { writer.Write("<td class='resourceCell'>{0}</td>", OrionGlobals.getLink( Universe.instance.getRuler(scan.TargetPlanetOwner))); } else { writer.Write("<td class='resourceCell'>{0}</td>", info.getContent("scan_inhabited")); } writer.Write("<td class='resourceCell'><img src='{0}' /></td>", OrionGlobals.YesNoImage(scan.Success)); writer.Write("<td class='resourceCell'><img src='{0}' /></td>", OrionGlobals.YesNoImage(!scan.Intercepted)); if( !scan.Success ) { writer.Write("<td class='resourceCell'> </td>"); } else { writer.Write("<td class='resourceCell'><a href='scanreport.aspx?id={0}&scan={2}'><img src='{1}' /></a></td>", scan.SourcePlanetId, OrionGlobals.getCommonImagePath("Filter.gif"), scan.Id ); } writer.Write("</tr>"); } }
public PictureProcessor() { r = cpuMemory.RegistersPPU; core = new PPUCore(r); scan = new Scan(); }
public async Task <StoreScanDto> GetStoresWithBarcode(string barcode, double longtitude, double latitude) { //Store Bilgisi var dbStores = await _unitOfWork.Products.GetStoresWithBarcode(barcode); var dbClosestStore = await _unitOfWork.Stores.GetClosestStoreAsync(dbStores, longtitude, latitude); if (dbClosestStore == null) { throw new CustomException("Mağaza bulunamadı"); } //Product Bilgisi var dbProduct = await _unitOfWork.Products.GetProductByBarcodeAsync(barcode); if (dbProduct == null) { throw new CustomException("Ürün bulunamadı"); } var scanDto = _mapper.Map <StoreScanDto>(await _unitOfWork.Stores.GetWithProductsByIdAsync(dbClosestStore.Id, dbProduct.ProductNo)); foreach (var product in scanDto.Products) { if (!scanDto.Sizes.Contains(product.Size)) { scanDto.Sizes.Add(product.Size); } if (!scanDto.Colors.Contains(product.Color)) { scanDto.Colors.Add(product.Color); } } if (_httpContextAccessor.HttpContext.User.Identity.Name != null) { var dbUser = await _userManager.FindByNameAsync(_httpContextAccessor.HttpContext.User?.Identity?.Name); if (dbUser == null) { throw new CustomException("Kullanıcı bulunamadı"); } Scan scan = new Scan() { StoreId = dbClosestStore.Id, ProductId = dbProduct.Id, UserId = dbUser.Id }; await _unitOfWork.Scans.AddAsync(scan); foreach (var item in scanDto.Products) { foreach (var i in item.Favorites) { if (i.UserId == dbUser.Id) { item.Liked = true; } } } } //User Bilgisi else { Scan scan = new Scan() { StoreId = dbClosestStore.Id, ProductId = dbProduct.Id }; await _unitOfWork.Scans.AddAsync(scan); } await _unitOfWork.CommitAsync(); return(scanDto); }
private void WorkerIntegrityScanner_DoWork(object sender, DoWorkEventArgs e) { if (RunScan != null && RunScan.GetScanStatus() != ScanStatus.Finish) { Scan s = RunScan; s.Status = (int)ScanStatus.Running; RepoFactory.Scan.Save(s); Refresh(); List <ScanFile> files = RepoFactory.ScanFile.GetWaiting(s.ScanID); int cnt = 0; foreach (ScanFile sf in files) { try { if (!File.Exists(sf.FullName)) { sf.Status = (int)ScanFileStatus.ErrorFileNotFound; } else { FileInfo f = new FileInfo(sf.FullName); if (sf.FileSize != f.Length) { sf.Status = (int)ScanFileStatus.ErrorInvalidSize; } else { Hashes hashes = FileHashHelper.GetHashInfo(sf.FullName, true, OnHashProgress, false, false, false); if (string.IsNullOrEmpty(hashes.ED2K)) { sf.Status = (int)ScanFileStatus.ErrorMissingHash; } else { sf.HashResult = hashes.ED2K; if (!sf.Hash.Equals(sf.HashResult, StringComparison.InvariantCultureIgnoreCase)) { sf.Status = (int)ScanFileStatus.ErrorInvalidHash; } else { sf.Status = (int)ScanFileStatus.ProcessedOK; } } } } } catch (Exception) { sf.Status = (int)ScanFileStatus.ErrorIOError; } cnt++; sf.CheckDate = DateTime.Now; RepoFactory.ScanFile.Save(sf); if (sf.Status > (int)ScanFileStatus.ProcessedOK) { Scanner.Instance.AddErrorScan(sf); } Refresh(); if (cancelIntegrityCheck) { break; } } if (files.Any(a => a.GetScanFileStatus() == ScanFileStatus.Waiting)) { s.Status = (int)ScanStatus.Standby; } else { s.Status = (int)ScanStatus.Finish; } RepoFactory.Scan.Save(s); Refresh(); RunScan = null; } }
/// <summary>Regista um scan</summary> public override void Register( Scan scan ) { MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, scan); byte[] data = stream.ToArray(); PostGre.PostGreParam [] parameters = new PostGreParam[2]; parameters[0] = new PostGreParam(scan.SourcePlanetId,NpgsqlDbType.Integer); parameters[1] = new PostGreParam(data,NpgsqlDbType.Bytea); PostGreServerUtility.executeNonQuery2("OrionsBelt_InsertScans",parameters); }
public void HandleDataPoint(DataEventArgs e) { Profile currentProfile = Controller.GetController().ProfileManager.CurrentProfile; // update the TOF graphs if (currentProfile.GUIConfig.average) { if (shotCounter % currentProfile.GUIConfig.updateTOFsEvery == 0) { if (avOnTof != null) { window.PlotOnTOF(avOnTof / onAverages); } avOnTof = (TOF)e.point.AverageOnShot.TOFs[0]; onAverages = 1; if ((bool)currentProfile.AcquisitorConfig.switchPlugin.Settings["switchActive"]) { if (avOffTof != null) { window.PlotOffTOF(avOffTof / offAverages); } avOffTof = (TOF)e.point.AverageOffShot.TOFs[0]; offAverages = 1; } } else // do the averaging { if (avOnTof != null) { avOnTof = avOnTof + ((TOF)e.point.AverageOnShot.TOFs[0]); onAverages++; } if ((bool)currentProfile.AcquisitorConfig.switchPlugin.Settings["switchActive"] && avOffTof != null) { avOffTof = avOffTof + ((TOF)e.point.AverageOffShot.TOFs[0]); offAverages++; } } } else // if not averaging { if (shotCounter % currentProfile.GUIConfig.updateTOFsEvery == 0) { window.PlotOnTOF((TOF)e.point.AverageOnShot.TOFs[0]); if ((bool)currentProfile.AcquisitorConfig.switchPlugin.Settings["switchActive"]) { window.PlotOffTOF((TOF)e.point.AverageOffShot.TOFs[0]); } } } // update the spectra pointsToPlot.Points.Add(e.point); if (shotCounter % currentProfile.GUIConfig.updateSpectraEvery == 0) { if (pointsToPlot.AnalogChannelCount >= 1) { window.AppendToAnalog1(pointsToPlot.ScanParameterArray, pointsToPlot.GetAnalogArray(0)); } if (pointsToPlot.AnalogChannelCount >= 2) { window.AppendToAnalog2(pointsToPlot.ScanParameterArray, pointsToPlot.GetAnalogArray(1)); } if (sdisplayMode == ScanDisplayMode.Integral) { window.AppendToPMTOn(pointsToPlot.ScanParameterArray, pointsToPlot.GetTOFOnIntegralArray(0, startTOFGate, endTOFGate)); } if (sdisplayMode == ScanDisplayMode.IofAbs) { window.AppendToPMTOn(pointsToPlot.ScanParameterArray, pointsToPlot.GetTOFOnAbsValIntegralArray(0, startTOFGate, endTOFGate)); } if ((bool)currentProfile.AcquisitorConfig.switchPlugin.Settings["switchActive"]) { if (sdisplayMode == ScanDisplayMode.Integral) { window.AppendToPMTOff(pointsToPlot.ScanParameterArray, pointsToPlot.GetTOFOffIntegralArray(0, startTOFGate, endTOFGate)); window.AppendToDifference(pointsToPlot.ScanParameterArray, pointsToPlot.GetDifferenceIntegralArray(0, startTOFGate, endTOFGate)); } if (sdisplayMode == ScanDisplayMode.IofAbs) { window.AppendToPMTOff(pointsToPlot.ScanParameterArray, pointsToPlot.GetTOFOffAbsValIntegralArray(0, startTOFGate, endTOFGate)); window.AppendToDifference(pointsToPlot.ScanParameterArray, pointsToPlot.GetDifferenceAbsValIntegralArray(0, startTOFGate, endTOFGate)); } } // update the spectrum fit if in shot mode. if (spectrumFitMode == FitMode.Shot) { Scan currentScan = Controller.GetController().DataStore.CurrentScan; if (currentScan.Points.Count > 10) { FitAndPlotSpectrum(currentScan); } } pointsToPlot.Points.Clear(); } shotCounter++; }
static void Main() { var sw = new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; var sc = new Scan(); int n = sc.Int; var a = new int[n][]; for (int i = 0; i < n; i++) { a[i] = sc.IntArr; } double l = -(1e5), r = 1e5, maxl = 0, maxr = 0; while (r - l > eps) { double ml = (l * 2 + r) / 3, mr = (l + r * 2) / 3; maxl = 0; maxr = 0; for (int i = 0; i < n; i++) { maxl = Math.Max(maxl, Math.Abs(a[i][0] - ml) * a[i][2]); maxr = Math.Max(maxr, Math.Abs(a[i][0] - mr) * a[i][2]); } if (maxl < maxr) { r = mr; } else { l = ml; } } l = -(1e5); r = 1e5; var t = maxr; while (r - l > eps) { double ml = (l * 2 + r) / 3, mr = (l + r * 2) / 3; maxl = 0; maxr = 0; for (int i = 0; i < n; i++) { maxl = Math.Max(maxl, Math.Abs(a[i][1] - ml) * a[i][2]); maxr = Math.Max(maxr, Math.Abs(a[i][1] - mr) * a[i][2]); } if (maxl < maxr) { r = mr; } else { l = ml; } } sw.WriteLine(Math.Max(maxr, t)); sw.Flush(); }
public void updateRow(SpectrumDataSet.SpectrumTableRow row, MassSpectrum spectrum) { spectrumList[spectrum.Index] = spectrum; Spectrum s = spectrum.Element; DataProcessing dp = spectrum.DataProcessing; Scan scan = null; InstrumentConfiguration ic = null; if (s.scanList.scans.Count > 0) { scan = s.scanList.scans[0]; ic = scan.instrumentConfiguration; } if (dp == null) { dp = s.dataProcessing; } CVParam param; param = s.cvParam(CVID.MS_ms_level); row.MsLevel = !param.empty() ? (int)param.value : 0; param = scan != null?scan.cvParam(CVID.MS_scan_start_time) : new CVParam(); row.ScanTime = !param.empty() ? (double)param.value : 0; param = s.cvParam(CVID.MS_base_peak_m_z); row.BasePeakMz = !param.empty() ? (double)param.value : 0; param = s.cvParam(CVID.MS_base_peak_intensity); row.BasePeakIntensity = !param.empty() ? (double)param.value : 0; param = s.cvParam(CVID.MS_total_ion_current); row.TotalIonCurrent = !param.empty() ? (double)param.value : 0; StringBuilder precursorInfo = new StringBuilder(); if (row.MsLevel == 1 || s.precursors.Count == 0) { precursorInfo.Append("n/a"); } else { foreach (Precursor p in s.precursors) { foreach (SelectedIon si in p.selectedIons) { if (precursorInfo.Length > 0) { precursorInfo.Append(","); } precursorInfo.Append((double)si.cvParam(CVID.MS_selected_ion_m_z).value); } } } if (precursorInfo.Length == 0) { precursorInfo.Append("unknown"); } row.PrecursorInfo = precursorInfo.ToString(); StringBuilder scanInfo = new StringBuilder(); foreach (Scan scan2 in s.scanList.scans) { if (scan2.scanWindows.Count > 0) { foreach (ScanWindow sw in scan2.scanWindows) { if (scanInfo.Length > 0) { scanInfo.Append(","); } scanInfo.AppendFormat("[{0}-{1}]", (double)sw.cvParam(CVID.MS_scan_window_lower_limit).value, (double)sw.cvParam(CVID.MS_scan_window_upper_limit).value); } } } if (scanInfo.Length == 0) { scanInfo.Append("unknown"); } row.ScanInfo = scanInfo.ToString(); row.SpotId = s.spotID; row.SpectrumType = s.cvParamChild(CVID.MS_spectrum_type).name; row.DataPoints = s.defaultArrayLength; row.IcId = (ic == null || ic.id.Length == 0 ? "unknown" : ic.id); row.DpId = (dp == null || dp.id.Length == 0 ? "unknown" : dp.id); }