Пример #1
0
 public Microfacet(Spectrum reflectance, IFresnel fresnel, IMicrofacetDistribution distribution)
     : base(BxDFType.BSDF_REFLECTION | BxDFType.BSDF_GLOSSY)
 {
     R = new Spectrum (reflectance.c[0], reflectance.c[1], reflectance.c[2]);
     Fresnel = fresnel;
     Distribution = distribution;
 }
Пример #2
0
 // DensityRegion Public Methods
 public DensityRegion(Spectrum sa, Spectrum ss, float gg, Spectrum emit, AABB b) {
     sig_a = sa;
     sig_s = ss;
     le = emit;
     g = gg;
     worldBound = b;
 }
Пример #3
0
 public DiffuseAreaLight(Transform lightToWorld, Spectrum Le, int ns, IShape shape)
     : base(lightToWorld, ns)
 {
     Lemit = Le;
     ShapeSet = new ShapeSet (shape);
     area = ShapeSet.Area;
 }
Пример #4
0
        public static Spectrum SpecularReflect(RayDifferential ray, BSDF bsdf, Intersection isect, IRenderer renderer, Scene scene, Sample sample)
        {
            Vector wo = -ray.Direction, wi = new Vector ();
            double pdf = 0.0;
            Point p = bsdf.dgShading.p;
            Normal n = bsdf.dgShading.n;

            Spectrum f = bsdf.SampleF (wo, ref wi, new BSDFSample (), ref pdf, BxDFType.BSDF_REFLECTION | BxDFType.BSDF_SPECULAR);
            Spectrum L = new Spectrum ();

            if (pdf > 0.0 && !f.IsBlack && Util.AbsDot (wi, n) != 0.0)
            {
                RayDifferential rd = new RayDifferential (p, wi, ray, isect.RayEpsilon);
                if (ray.HasDifferentials)
                {
                    rd.HasDifferentials = true;
                    rd.RxOrigin = p + isect.dg.dpdx;
                    rd.RyOrigin = p + isect.dg.dpdy;

                    Normal dndx = bsdf.dgShading.dndu * bsdf.dgShading.dudx + bsdf.dgShading.dndv * bsdf.dgShading.dvdx;
                    Normal dndy = bsdf.dgShading.dndu * bsdf.dgShading.dudy + bsdf.dgShading.dndv * bsdf.dgShading.dvdy;
                    Vector dwodx = -ray.RxDirection - wo, dwody = -ray.Direction - wo;
                    double dDNdx = (dwodx ^ n) + (wo ^ dndx);
                    double dDNdy = (dwody ^ n) + (wo ^ dndy);
                    rd.RxDirection = wi - dwodx + 2 * new Vector ((wo ^ n) * dndx + dDNdx * n);
                    rd.RyDirection = wi - dwody + 2 * new Vector ((wo ^ n) * dndy + dDNdy * n);
                }

                Spectrum Li = renderer.Li (scene, rd, sample);
                L = f * Li * Util.AbsDot (wi, n) / pdf;
            }

            return L;
        }
Пример #5
0
 public SpecularTransmission(Spectrum t, double ei, double et)
     : base(BxDFType.BSDF_TRANSMISSION | BxDFType.BSDF_SPECULAR)
 {
     T = t;
     EtaI = ei;
     EtaT = et;
     Fresnel = new FresnelDielectric (ei, et);
 }
Пример #6
0
 public OrenNayar(Spectrum reflectance, double sig)
     : base(BxDFType.BSDF_REFLECTION | BxDFType.BSDF_DIFFUSE)
 {
     double sigma = Util.Radians (sig);
     double sigma2 = sigma * sigma;
     A = 1.0 - (sigma2 / (2.0 * (sigma2 + 0.33)));
     B = 0.45 * sigma2 / (sigma2 + 0.09);
 }
Пример #7
0
 public static Spectrum FrCond(double cosi, Spectrum eta, Spectrum k)
 {
     Spectrum tmp = (eta * eta + k * k) * cosi * cosi;
     Spectrum Rparl2 = (tmp - (2.0 * eta * cosi) + new Spectrum (1.0)) / (tmp + (2.0 * eta * cosi) + new Spectrum (1.0));
     Spectrum tmp_f = eta * eta + k * k;
     Spectrum Rperp2 = (tmp_f - (2.0 * eta * cosi) + new Spectrum (cosi * cosi)) / (tmp_f + (2.0 * eta * cosi) + new Spectrum (cosi * cosi));
     return (Rparl2 + Rperp2) / 2.0;
 }
Пример #8
0
 public FresnelBlend(Spectrum rs, Spectrum rd, float e)
 {
     distribution = 
         //new Anisotropic(10,10);
         //new Anisotropic(e*rs.Average, e*rd.Average);
         new BlinnDistribution(e);
     Rd = rd;
     Rs = rs;
 }
Пример #9
0
 public Graph(CommonOptions commonOpts, params double[] coeffs)
 {
     Collectors = new Spectrum(commonOpts, coeffs);
     int length = coeffs.Length;
     _all = new int[length];
     for (int i = 0; i < length; ++i) {
         _all[i] = i + 1;
     }
 }
Пример #10
0
        public OrenNayar(Spectrum reflectance, float sig)
            : base(BxdfType.Reflection | BxdfType.Diffuse)
        {
            _reflectance = reflectance;

            float sigma = MathUtility.ToRadians(sig);
            float sigma2 = sigma * sigma;
            _a = 1.0f - (sigma2 / (2.0f * (sigma2 + 0.33f)));
            _b = 0.45f * sigma2 / (sigma2 + 0.09f);
        }
Пример #11
0
        public void Run()
        {
            ISampler sampler = MainSampler.GetSubSampler (TaskNumber, TaskCount);
            if (sampler == null)
            {
                return;
            }

            int maxSamples = sampler.MaximumSampleCount;
            Sample[] samples = OrigSample.Duplicate (maxSamples);
            RayDifferential[] rays = new RayDifferential[maxSamples];
            Spectrum[] Ls = new Spectrum[maxSamples];
            Spectrum[] Ts = new Spectrum[maxSamples];
            Intersection[] isects = new Intersection[maxSamples];

            for (int i = 0; i < maxSamples; ++i)
            {
                samples[i] = new Sample ();
                rays[i] = new RayDifferential ();
                Ls[i] = new Spectrum ();
                Ts[i] = new Spectrum ();
                isects[i] = new Intersection ();
            }

            int sampleCount;

            while ((sampleCount = sampler.GetMoreSamples (samples)) > 0)
            {
                for (int i = 0; i < sampleCount; ++i)
                {
                    double rayWeight = Camera.GenerateRayDifferential (samples[i], ref rays[i]);
                    rays[i].ScaleDifferentials (1.0 / Math.Sqrt (sampler.SamplesPerPixel));

                    if (rayWeight > 0.0)
                        Ls[i] = rayWeight * Renderer.Li (Scene, rays[i], samples[i], ref isects[i], ref Ts[i]);
                    else
                    {
                        Ls[i] = new Spectrum ();
                        Ts[i] = new Spectrum (1.0);
                    }

                    // WARNINGS
                }

                if (sampler.ReportResults (samples, rays, Ls, isects, sampleCount))
                {
                    for (int i = 0; i < sampleCount; ++i)
                        Camera.Film.AddSample (samples[i], Ls[i]);
                }
            }

            Camera.Film.UpdateDisplay (sampler.xPixelStart, sampler.yPixelStart, sampler.xPixelEnd + 1, sampler.yPixelEnd + 1);
            Reporter.Update ();
        }
Пример #12
0
        public PreprocessedCoefficients([NotNull] Element element, [NotNull] Func<double, double> getValue,
            Region region, int n)
        {
            if (element == null) throw new ArgumentNullException("element");
            if (getValue == null) throw new ArgumentNullException("getValue");
            if (region.Width.IsZero()) throw new ArgumentException("region");
            if (n <= 0) throw new ArgumentOutOfRangeException("n");

            values = Spectrum.ByFunc(getValue, region, n);
            Element = element;
        }
Пример #13
0
 public Spectrum F(Vector woW, Vector wiW, BxDFType flags)
 {
     Vector wi = WorldToLocal (wiW), wo = WorldToLocal (woW);
     if ((wiW ^ ng) * (woW ^ ng) > 0)
         flags &= ~BxDFType.BSDF_TRANSMISSION;
     else
         flags &= ~BxDFType.BSDF_REFLECTION;
     Spectrum f = new Spectrum ();
     for (int i = 0; i < nBxDFs; ++i)
         if (bxdfs[i].MatchesFlags (flags))
             f += bxdfs[i].F (wo, wi);
     return f;
 }
Пример #14
0
 public virtual Spectrum Rho(Vector wo, int nSamples, double[] samples)
 {
     Spectrum r = new Spectrum ();
     for (int i = 0; i < nSamples; ++i)
     {
         Vector wi = new Vector ();
         double pdf = 0.0;
         Spectrum f = SampleF (wo, ref wi, samples[2 * i], samples[2 * i + 1], ref pdf);
         if (pdf > 0.0)
             r += f * Util.AbsCosTheta (wi) / pdf;
     }
     return r / (double)nSamples;
 }
Пример #15
0
		/// <summary>
		/// データの特性を取得。
		/// </summary>
		/// <param name="spectrum">スペクトル</param>
		/// <param name="type">特性の種類</param>
		/// <returns>特性</returns>
		public static double[] GetData(Spectrum spectrum, Property type)
		{
			switch(type)
			{
				case Property.Amplitude:
				{
					double[] tmp = spectrum.GetPower();
					Spectrum.Smooth(tmp);
					return tmp;
				}
				case Property.Phase:
				{
					double[] tmp = spectrum.GetPhase();
					Spectrum.Unwrap(tmp);
					Spectrum.Smooth(tmp);
					return tmp;
				}
				case Property.MinimumPhase:
				{
					double[] tmp = spectrum.GetMinimumPhase();
					Spectrum.Smooth(tmp);
					return tmp;
				}
				case Property.AllPassPhase:
				{
					double[] tmp  = spectrum.GetPhase();
					double[] tmp2 = spectrum.GetMinimumPhase();
					for(int i=0; i<tmp.Length; ++i) tmp[i] += tmp2[i];
					Spectrum.Unwrap(tmp);
					Spectrum.Smooth(tmp);
					return tmp;
				}
				case Property.PhaseDelay:
				{
					double[] tmp = spectrum.GetPhase();
					Spectrum.Unwrap(tmp);
					Spectrum.Smooth(tmp);
					return Spectrum.GetPhaseDalay(tmp, 48000);
				}
				case Property.GroupDelay:
				{
					double[] tmp = spectrum.GetPhase();
					Spectrum.Unwrap(tmp);
					Spectrum.Smooth(tmp);
					return Spectrum.GetGroupDalay(tmp, 48000);
				}
				default:
					return spectrum.TimeSequence;
			}
		}//GetData
Пример #16
0
        public Texture<Spectrum> GetSpectrumTexture(string n, Spectrum defaultValue)
        {
            var name = _geomParams.FindTexture(n);
            if (string.IsNullOrEmpty(name))
                name = _materialParams.FindTexture(n);

            if (!string.IsNullOrEmpty(name))
            {
                if (_spectrumTextures.ContainsKey(name))
                    return _spectrumTextures[name];
                throw new InvalidOperationException(string.Format("Couldn't find spectrum texture named '{0}' for parameter '{1}'", name, n));
            }
            var value = _geomParams.FindSpectrum(n, _materialParams.FindSpectrum(n, defaultValue));
            return new ConstantTexture<Spectrum>(value);
        }
Пример #17
0
        public virtual Spectrum Rho(int nSamples, double[] samples1, double[] samples2)
        {
            Spectrum r = new Spectrum ();
            for (int i = 0; i < nSamples; ++i)
            {
                Vector wo, wi = new Vector ();
                wo = MonteCarlo.UniformSampleHemisphere (samples1[2 * i], samples1[2 * i + 1]);
                double pdf_o = Util.InvTwoPi, pdf_i = 0.0;
                Spectrum f = SampleF (wo, ref wi, samples2[2 * i], samples2[2 * i + 1], ref pdf_i);

                if (pdf_i > 0.0)
                    r += f * Util.AbsCosTheta (wi) * Util.AbsCosTheta (wo) / (pdf_o * pdf_i);
            }
            return r / (Util.Pi * nSamples);
        }
Пример #18
0
        public static Spectrum SpecularTransmit(RayDifferential ray, BSDF bsdf, Intersection isect, IRenderer renderer, Scene scene, Sample sample)
        {
            Vector wo = -ray.Direction, wi = new Vector ();
            double pdf = 0.0;
            Point p = bsdf.dgShading.p;
            Normal n = bsdf.dgShading.n;
            Spectrum f = bsdf.SampleF (wo, ref wi, new BSDFSample (), ref pdf, BxDFType.BSDF_TRANSMISSION | BxDFType.BSDF_SPECULAR);
            Spectrum L = new Spectrum ();

            if (pdf > 0.0 && !f.IsBlack && Util.AbsDot (wi, n) != 0.0)
            {
                RayDifferential rd = new RayDifferential (p, wi, ray, isect.RayEpsilon);
                if (ray.HasDifferentials)
                {
                    rd.HasDifferentials = true;
                    rd.RxOrigin = p + isect.dg.dpdx;
                    rd.RyOrigin = p + isect.dg.dpdy;

                    double eta = bsdf.Eta;
                    Vector w = -wo;

                    if ((wo ^ n) < 0.0)
                        eta = 1.0 / eta;

                    Normal dndx = bsdf.dgShading.dndu * bsdf.dgShading.dudx + bsdf.dgShading.dndv * bsdf.dgShading.dvdx;
                    Normal dndy = bsdf.dgShading.dndu * bsdf.dgShading.dudy + bsdf.dgShading.dndv * bsdf.dgShading.dvdy;

                    Vector dwodx = -ray.RxDirection - wo, dwody = -ray.RyDirection - wo;
                    double dDNdx = (dwodx ^ n) + (wo ^ dndx);
                    double dDNdy = (dwody ^ n) + (wo ^ dndy);
                    double mu = eta * (w ^ n) - (wi ^ n);
                    double dmudx = (eta - (eta * eta * (w ^ n)) / (wi ^ n)) * dDNdx;
                    double dmudy = (eta - (eta * eta * (w ^ n)) / (wi ^ n)) * dDNdy;

                    rd.RxDirection = wi + eta * dwodx - new Vector (mu * dndx + dmudx * n);
                    rd.RyDirection = wi + eta * dwody - new Vector (mu * dndy + dmudy * n);
                }

                Spectrum Li = renderer.Li (scene, rd, sample);
                L = f * Li * Util.AbsDot (wi, n) / pdf;
            }

            return L;
        }
Пример #19
0
        public static Spectrum[] ReadImage(string name, out int xSize, out int ySize)
        {
            Bitmap bitmap = new Bitmap (name);
            Spectrum[] pixels = new Spectrum[bitmap.Width * bitmap.Height];

            for (int y = 0; y < bitmap.Height; ++y)
            {
                for (int x = 0; x < bitmap.Width; ++x)
                {
                    Color pixel = bitmap.GetPixel (x, y);
                    double[] c = new double[3];
                    c[0] = pixel.R / 255.0;
                    c[1] = pixel.G / 255.0;
                    c[2] = pixel.B / 255.0;
                    pixels[y * bitmap.Width + x] = new Spectrum (c[0], c[1], c[2]);
                }
            }

            xSize = bitmap.Width;
            ySize = bitmap.Height;

            return pixels;
        }
Пример #20
0
        public AudioEngine()
        {

            Path = @"http://psv4.vk.me/c613621/u23628424/audios/45049760ad7c.mp3?extra=xy8j8Fwc0OnSqJcxvITYLiX-D4akkd_Rkl8cvuVgLlLvD9G133yv-_MAqCspCcmxxUdw9OMZGdrq702KUJ2PdO1oGDkTRvw&/Scratch%20Bandits%20Crew%20-%20Surround%20Me.mp3";
            //Path = @"D:\Documents and Settings\Admin\Рабочий стол\C#\Music Primer\6ddb8171688e23.mp3";
            // Path = @"http://www.sky.fm/mp3/the80s.pls";
            //Path = @"http://download.wavetlan.com/SVV/Media/HTTP/WMA/WMALossless/Coldplay_StrawberrySwing_WMALossless.wma";
            //Path = @"http://yp.shoutcast.com/sbin/tunein-station.pls?id=193174";
            //+Path = @"http://yp.shoutcast.com/sbin/tunein-station.pls?id=193174";
            //Path = @"http://radiocaroline259.nl/winamp_rc259_320.pls";
            //Path = @"http://yp.shoutcast.com/sbin/tunein-station.pls?id=94181";
            //Path = @"http://yp.shoutcast.com/sbin/tunein-station.pls?id=256410";
            //Path = @"http://flacradio.esy.es/playlist/AI-Radio.m3u";
            //Path = @"http://a.files.bbci.co.uk/media/live/manifesto/audio/simulcast/hls/uk/sbr_high/llnw/bbc_1xtra.m3u8";
            ListSongs = new List<string>(
                Directory.GetFiles(@"D:\Documents and Settings\Admin\Рабочий стол\C#\Music Primer"));
            /* ListSongs = new List<string>();
             ListSongs.Add(@"http://cs1-34v4.vk-cdn.net/p6/d1483bd42febd1.mp3?extra=vi0VwGa9y_QGmZqu8zXS2NNAuPHuBuHM-yChSaH3-vezjVEJMN7tvO6WDQq3CRsOk0SJw9apaTVSamib5nHTPROhCr8kCz3n&/CunninLynguists%20-%20Darkness%20(Dream%20On)%20(Instrumental).mp3");
             ListSongs.Add(@"http://psv4.vk.me/c613231/u23628424/audios/bca9f0bb9989.mp3?extra=c7lN4T5gQC3FOQPpHCgWnmtCTk2F89a-HjouOB5qAPoKePRg_0OSR7nbm8tsFqS1ypEXhrV5khECX449brMq9qzqtiYNOfq1&/Mr.%20Moods%20-%20Rainbow.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c613924/u64887148/audios/73b365664dbb.mp3?extra=qbIEMne5L7HEkwI8l57HvsJbjpHEap8WEapQ5BVETzm-bo_6lpu3UPJ4gDnGJyc-G4-7cWHb_gqO9fDT9Ly87XQPYfwcEcaO&/PhybaOptikz%20-%20Chronicles.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c521100/u4594424/audios/0277415e656d.mp3?extra=tUmU_lLbAdXrMsDon27ayCWW3l6soR7fHTiQ0-6Qj6xuim7tQLXcEBXS0lq9uJ1TxuFkG-4xyQyWR004b_BL7nkaLcKZqMbd&/Roger%20Molls%20-%20You.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c613126/u247179947/audios/5b4259f1d5c3.mp3?extra=Fo_qX0TC-RHoozxSTQQZBedY9vxIlLk1VcPyRMziMarqYxCBZqIhX7cCPCPfB4XvYy2Gbnz9Zdl34KXdNtXu0ovlSeG_B86E&/Keizan%20-%20Keizan%20-%20Damn%20feat%20Dj%20Meloman.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c611427/u221922242/audios/d196c39b7b28.mp3?extra=OgcU7H3jJrRB94KkUdGFxqXRlGwh7ttN3sIB0LGRqYUIxFpXfm48v6FQWyHWHge3DDI5U02KBoSRHOJTQX9Pdwj31aeoWBFw&/Billa%20Qause%20-%20Slow%20Down.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c611324/u1444216/audios/36a640799476.mp3?extra=sr0Y8gulc4N5Wr4wEPavdJ98vK3FRAFX6pQbCC6JeDypyPoT8RGLsR4618C8CpZE1YaLlUfGmFMAyJCsXsnjSo4sg-lH87qq&/GRiZ%20-%20Love%20Will%20Follow%20You%20(feat.%20Russ%20Liquid).mp3");
             ListSongs.Add(@"http://psv4.vk.me/c613327/u23628424/audios/fb86d3ceae8f.mp3?extra=q7-2v9Jh_Cq0V4QlhgEz7E4pvf3NxS9yPCE5MIdu_0NQsdQ13572JElzEgZt9Kj7VafbWfxb-vq2IP1BvLLqCE6MSD7MZRA6&/Kinack%20-%20Shine.mp3");
             ListSongs.Add(@"http://cs1-42v4.vk-cdn.net/p23/7ffb834f38273a.mp3?extra=-mJYId08Rdph4HddpqC6noOAFcs6jvCw0hauKmXWQkREoEUclM-MMSstShqEYPguWrAemIoc5zA57nx89XmbnkHGh-E_5WgD&/Frameworks%20-%20Music%20Box.mp3");
             ListSongs.Add(@"http://psv4.vk.me/c613121/u23628424/audios/659402091c6c.mp3?extra=ZfCP0UugdWy6oapnqKBTnvwtC2vXa_WQXZsE648_vkKMgn2e-3nP1E1fREEgJnUsSka0pMvOHvOlBwU6oyjird1po-WO0J8W&/Travelers%20Of%20Tyme%20-%20Raining%20Castanets%20(The%20Rains%20of%20Castamere).mp3");
 */

            WahWahEffect = new WahWahService();
            PitchShiftEffect = new PitchShiftService();
            PhaserEffect = new PhaserService();
            ChorusEffect = new ChorusService();
            DistortionEffect = new DistortionService();
            DynamicAmplificationEffect = new DynamicAmplificationService();
            ReverberationEffect = new ReverberationService();
            EchoEffect = new EchoService();
            CompressorEffect = new CompressorService();
            BiQuadFilterEffect = new BiQuadFilterService();
            DSPEffect = new DSP();
            WaveFormClass = new WaveFormService();
            Spectrum = new Spectrum();

            MemoryPlay = true;
            _timer = new BASSTimer();
            _timer.Tick += MusicTrackTick;
            _timer.Start();
            CurrentVolume = 1;
            Crossfade = new CrossfadeService(CurrentVolume);
            EqualizerEffect = new EqualizerService();
            CrossfadeActive = true;
            SoundOutProvider = new SoundOutProviderBASS();
            _myUserAgentPtr = Marshal.StringToHGlobalAnsi(_myUserAgent);
            _positionEventAggregator = new EventAggregator();
            _waveFormEventAggregator = new EventAggregator();
            DownloadMode = DownloadTypes.NoDownload;

            _syncProcPos = SyncMethodPos;
            

            Bass.BASS_SetConfigPtr(BASSConfig.BASS_CONFIG_NET_AGENT, _myUserAgentPtr);

            SoundOutProvider.SetConfig(BASSConfig.BASS_CONFIG_FLOATDSP, true);
            SoundOutProvider.SetConfig(BASSConfig.BASS_CONFIG_NET_TIMEOUT, 5000);
            SoundOutProvider.SetConfig(BASSConfig.BASS_CONFIG_WMA_PREBUF, 0);
            SoundOutProvider.SetConfig(BASSConfig.BASS_CONFIG_NET_PREBUF, 0);
            SoundOutProvider.SetConfig(BASSConfig.BASS_CONFIG_NET_PLAYLIST, 2);
        }
Пример #21
0
 public Spectrum GetDeconvolutedSpectrum(Spectrum spec, int minCharge, int maxCharge, Tolerance tolerance, double corrThreshold)
 {
     return(GetDeconvolutedSpectrum(spec, minCharge, maxCharge, tolerance, corrThreshold, IsotopeOffsetTolerance, FilteringWindowSize));
 }
Пример #22
0
 public SnaSerializer(Spectrum spec)
     : base(spec)
 {
 }
Пример #23
0
        public void updateRow(SpectrumDataSet.SpectrumTableRow row, MassSpectrum spectrum)
        {
            spectrumList[spectrum.Index] = spectrum;

            Spectrum                s    = spectrum.Element; //GetElement(false);
            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() ? param.timeInSeconds() : 0;
            if (Properties.Settings.Default.TimeInMinutes)
            {
                row.ScanTime /= 60;
            }

            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;

            var precursorInfo    = new StringBuilder();
            var isolationWindows = new StringBuilder();

            if (row.MsLevel == 1 || s.precursors.Count == 0)
            {
                precursorInfo.Append("n/a");
                isolationWindows.Append("n/a");
            }
            else
            {
                foreach (Precursor p in s.precursors)
                {
                    foreach (SelectedIon si in p.selectedIons)
                    {
                        if (precursorInfo.Length > 0)
                        {
                            precursorInfo.Append(",");
                        }
                        precursorInfo.AppendFormat("{0:G8}", (double)si.cvParam(CVID.MS_selected_ion_m_z).value);
                    }

                    var     iw = p.isolationWindow;
                    CVParam isolationTarget = iw.cvParam(CVID.MS_isolation_window_target_m_z);
                    if (!isolationTarget.empty())
                    {
                        double iwMz = (double)isolationTarget.value;

                        if (isolationWindows.Length > 0)
                        {
                            isolationWindows.Append(",");
                        }

                        CVParam lowerOffset = iw.cvParam(CVID.MS_isolation_window_lower_offset);
                        CVParam upperOffset = iw.cvParam(CVID.MS_isolation_window_upper_offset);
                        if (lowerOffset.empty() || upperOffset.empty())
                        {
                            isolationWindows.AppendFormat("{0:G8}", iwMz);
                        }
                        else
                        {
                            isolationWindows.AppendFormat("[{0:G8}-{1:G8}]", iwMz - (double)lowerOffset.value, iwMz + (double)upperOffset.value);
                        }
                    }
                }
            }

            if (precursorInfo.Length == 0)
            {
                precursorInfo.Append("unknown");
            }
            row.PrecursorInfo = precursorInfo.ToString();

            if (isolationWindows.Length == 0)
            {
                isolationWindows.Append("unknown");
            }
            row.IsolationWindows = isolationWindows.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:G8}-{1:G8}]",
                                              (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.IonMobility = scan != null ? (double)scan.cvParam(CVID.MS_ion_mobility_drift_time).value : 0;
            if (row.IonMobility == 0 && scan != null)
            {
                row.IonMobility = (double)scan.cvParam(CVID.MS_inverse_reduced_ion_mobility).value;
                if (row.IonMobility == 0)
                {
                    // Early version of drift time info, before official CV params
                    var userparam = scan.userParam("drift time");
                    if (!userparam.empty())
                    {
                        row.IonMobility = userparam.timeInSeconds() * 1000.0;
                    }
                }
            }
            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);
        }
Пример #24
0
 public LambertianReflection(Spectrum r)
     : base(BxDFType.Reflection | BxDFType.Diffuse)
 {
     this.r = r;
 }
Пример #25
0
        static void _Main(string[] args)
        {
            const int N = 1024;

            double[] x = new double[N];

            IFilter filter = new ShelvingEqualizer(Common.Normalize(1000), 1);

            // インパルス応答取得
            filter.Clear();

            /*
             * filter.GetValue(1);
             * for(int i=0; i<16; ++i)
             *      filter.GetValue(0);
             */
            filter.GetValue(1);
            for (int i = 1; i < N; ++i)
            {
                x[i] = filter.GetValue(0);
            }

#if TIME_SEQUENCE
            int      n = N;
            double[] t = new double[n];
            for (int i = 0; i < n; ++i)
            {
                t[i] = i;
            }

            Graph.GraphForm gf = new Graph.GraphForm();
            gf.Graph.AddEntry(t, x, new Pen(Color.Crimson));
            gf.Graph.SetXAxis(0, n, 5, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Graph.SetYAxis(0, 2, 5, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Size = new Size(640, 480);
            gf.ShowDialog();
#elif PHASE
            Spectrum spec = Spectrum.FromTimeSequence(x, 1);

            int      n = spec.Count;
            double[] t = new double[n];
            for (int i = 0; i < n; ++i)
            {
                t[i] = i;
            }

            double[] y = spec.GetPhase();
            Spectrum.Unwrap(y);

            Graph.GraphForm gf = new Graph.GraphForm();
            gf.Graph.AddEntry(t, y, new Pen(Color.Crimson));
            gf.Graph.SetXAxis(0, n, 4, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Graph.SetYAxis(-50, 0, 4, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Size = new Size(640, 480);
            gf.ShowDialog();
#elif GAIN
            Spectrum spec = Spectrum.FromTimeSequence(x, 1);

            int      n = spec.Count;
            double[] t = new double[n];
            for (int i = 0; i < n; ++i)
            {
                t[i] = i;
            }

            double[] y = spec.GetAmplitude();

            Graph.GraphForm gf = new Graph.GraphForm();
            gf.Graph.AddEntry(t, y, new Pen(Color.Crimson));
            gf.Graph.SetXAxis(0, n, 4, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Graph.SetYAxis(0, 4, 4, new Font(FontFamily.GenericSerif, 12), new SolidBrush(Color.Black));
            gf.Size = new Size(640, 480);
            gf.ShowDialog();
#endif

#if false
            const int N  = 512;
            double[]  x  = new double[N];
            double[]  x0 = new double[N];
            double[]  y0 = new double[N];

/*
 *                      Random rnd = new Random();
 *                      x0[0] = 1;
 *                      x0[1] = 1;
 *                      y0[0] = 0;
 *                      y0[1] = 0;
 *                      for(int i=1; i<N/2; ++i)
 *                      {
 *                              x0[2*i]   = rnd.NextDouble();
 *                              x0[2*i+1] = rnd.NextDouble();
 *                              y0[2*i]   = -x0[2*i+1];
 *                              y0[2*i+1] = x0[2*i];
 *                      }
 *                      Fft fft = new Fft(N);
 *                      fft.Invert(x0);
 *                      fft.Invert(y0);
 *                      for(int i=0; i<N; ++i)
 *                              x[i] = x0[i];
 * //*/
//*
            for (int i = 0; i < N; ++i)
            {
                x[i] = 100;
                for (int k = 1; k < 200; ++k)
                {
                    x[i] += short.MaxValue / 4 / k * Math.Cos(Math.PI / 512 * 32 * i * k);
                }
                x0[i] = x[i];
                y0[i] = 0;
                for (int k = 1; k < 200; ++k)
                {
                    y0[i] += short.MaxValue / 4 / k * Math.Sin(Math.PI / 512 * 32 * i * k);
                }
            }
//*/

            double[] y = Spectrum.HilbertTransform(x);

            using (StreamWriter writer = new StreamWriter("z.csv", false, Encoding.Default))
            {
/*
 *                              for(int i=0; i<x.Length; ++i)
 *                                      writer.Write("{0},{1},{2},{3},{4}\n", i, x0[i], x[i], y0[i], y[i]);
 * //*/
//*
                Spectrum a0 = Spectrum.FromTimeSequence(x0);
                Spectrum a  = Spectrum.FromTimeSequence(x);
                Spectrum b0 = Spectrum.FromTimeSequence(y0);
                Spectrum b  = Spectrum.FromTimeSequence(y);

                for (int i = 0; i < a.Count; ++i)
                {
                    writer.Write("{0},{1},{2},{3},{4}\n", i, a0[i].Abs, a[i].Abs, b0[i].Abs, b[i].Abs);
//					writer.Write("{0},{1},{2},{3},{4}\n", i, a0[i].Arg, a[i].Arg, b0[i].Arg, b[i].Arg);
                }
//*/
            }
#elif false
            const int N = 1024;

            double[] lp  = new double[N];
            IFilter  lpf = new LowPassFir(16, Common.Normalize(2000));
            lp[0] = lpf.GetValue(1);
            for (int i = 1; i < N; ++i)
            {
                lp[i] = lpf.GetValue(0);
            }

            double[] bp  = new double[N];
            IFilter  bpf = new BandPassFir(16, Common.Normalize(2000), Common.Normalize(8000));
            lp[0] = bpf.GetValue(1);
            for (int i = 1; i < N; ++i)
            {
                bp[i] = bpf.GetValue(0);
            }

            double[] hp  = new double[N];
            IFilter  hpf = new HighPassFir(16, Common.Normalize(8000));
            lp[0] = hpf.GetValue(1);
            for (int i = 1; i < N; ++i)
            {
                hp[i] = hpf.GetValue(0);
            }

            Fft fft = new Fft(N);
            fft.Transform(1, lp);
            fft.Transform(1, bp);
            fft.Transform(1, hp);

            using (StreamWriter writer = new StreamWriter("z.csv", false, Encoding.Default))
            {
                double la = Common.Amp(lp[0]);
                double ba = Common.Amp(bp[0]);
                double ha = Common.Amp(hp[0]);
                writer.Write("{0},{1},{2},{3}\n", 0, la, ba, ha);

                for (int i = 1; i < N / 2; ++i)
                {
                    la = Common.Amp(lp[2 * i] * lp[2 * i] + lp[2 * i + 1] * lp[2 * i + 1]);
                    ba = Common.Amp(bp[2 * i] * bp[2 * i] + bp[2 * i + 1] * bp[2 * i + 1]);
                    ha = Common.Amp(hp[2 * i] * hp[2 * i] + hp[2 * i + 1] * hp[2 * i + 1]);

                    writer.Write("{0},{1},{2},{3}\n", i, la, ba, ha);
                }

                la = Common.Amp(lp[1]);
                ba = Common.Amp(bp[1]);
                ha = Common.Amp(hp[1]);
                writer.Write("{0},{1},{2},{3}\n", N / 2, la, ba, ha);
            }
#elif false
            uint         length;
            double[]     l;
            double[]     r;
            FormatHeader header;

            using (WaveReader reader = new WaveReader(@"TD100V00H030.wav"))
            {
                header = reader.Header;
                length = reader.Length;
                int tmp = reader.Read(length, out l, out r);
            }

            IFilter lpf = new LowPassFir(16, Common.Normalize(4500));
            IFilter bpf = new BandPassFir(16, Common.Normalize(4500), Common.Normalize(10000));
            IFilter hpf = new HighPassFir(16, Common.Normalize(10000));

            for (int i = 0; i < l.Length; ++i)
            {
                double lp = lpf.GetValue(l[i]);
                double bp = bpf.GetValue(l[i]);
                double hp = hpf.GetValue(l[i]);
                l[i] = lp + bp + hp;
            }
            if (r != null)
            {
                for (int i = 0; i < l.Length; ++i)
                {
                    double lp = lpf.GetValue(r[i]);
                    double bp = bpf.GetValue(r[i]);
                    double hp = hpf.GetValue(r[i]);
                    r[i] = lp + bp + hp;
                }
            }

            using (WaveWriter writer = new WaveWriter("z.wav", header))
            {
                writer.Write(l, r);
            }
#elif false
            using (StreamWriter writer = new StreamWriter("z.csv", false, Encoding.Default))
            {
                for (int i = 0; i < l.Length; ++i)
                {
                    writer.Write("{0},{1},{2}\n", i, l[i], r[i]);
                }
            }
#endif
        }
Пример #26
0
 public StraightLine(Spectrum spec)
 {
     _spectrum = new Spectrum(spec.SpectrumData);
 }
Пример #27
0
 public ScaledBxDF(BxDF b, Spectrum sc)
     : base(b.Type)
 {
     bxdf = b;
     s = sc;
 }
Пример #28
0
        public DialogResult ShowData(IntegrateResultItem item, List <IntegrateResultItem> results, Spectrum spec = null, int idMaxNum = 5)
        {
            if (item == null || results == null)
            {
                return(System.Windows.Forms.DialogResult.Cancel);
            }
            this._item        = item;
            this.lblName.Text = item.ToString();

            //找出使用相同识别库和相同拟合库的性质
            var lst = results.Where(d => d.GroupFitID == item.GroupFitID && d.GroupIDID == item.GroupIDID && ((double.IsNaN(d.IdWeight) && double.IsNaN(item.IdWeight)) || d.IdWeight == item.IdWeight) && ((double.IsNaN(d.FitWeight) && double.IsNaN(item.FitWeight)) || d.FitWeight == item.FitWeight)).ToList();


            //识别
            this.panelId.Title = "识别、拟合结果";


            //添加第一行,显示最终预测结果
            this.gridId.Rows.Add("");
            this.gridId.Rows[0].Frozen = true;
            if (spec != null)
            {
                this.gridId[0, 0].Value = spec.Name;
                this.gridId[1, 0].Value = spec.UUID;
            }
            foreach (var idc in lst)
            {
                //添加性质列
                this.gridId.Columns.Add(new DataGridViewTextBoxColumn()
                {
                    Width      = 80,
                    HeaderText = idc.Comp.Name,
                    SortMode   = DataGridViewColumnSortMode.NotSortable
                });
                this.gridId[this.gridId.Columns.Count - 1, 0].Value = idc.Comp.PredictedValue.ToString(idc.Comp.EpsFormatString);
            }

            int k = 1;

            if (item.IdResult != null)
            {
                //添加识别行
                this.gridId.Rows.Add(
                    "识别结果",
                    "",
                    item.IDTQ.ToString("F4"),
                    item.IDSQ.ToString("F4"),
                    "",
                    item.ConfidenceId.ToString("F2"),
                    string.Format("{0}%/{1}%", item.PrimalWID, double.IsNaN(item.IdWeight) ? 0 : item.IdWeight));
                for (int i = 0; i < lst.Count; i++)
                {
                    this.gridId[7 + i, this.gridId.Rows.Count - 1].Value = lst[i].IdValue.ToString(lst[i].Comp.EpsFormatString);
                }
                this.gridId.Rows[this.gridId.Rows.Count - 1].DefaultCellStyle.BackColor = Color.FromArgb(221, 217, 195);

                int idcounter = 0;
                foreach (var r in item.IdResult)
                {
                    if (idcounter >= idMaxNum)
                    {
                        break;
                    }
                    idcounter++;
                    var cell = new DataGridViewRowHeaderCell()
                    {
                        Value = k.ToString()
                    };
                    var row = new nodeIdRow(r)
                    {
                        HeaderCell = cell
                    };
                    var cells = new List <string>();
                    cells.AddRange(new string[] {
                        r.Spec.Name,
                        r.Spec.UUID,
                        r.TQ.ToString("F4"),
                        r.SQ.ToString("F4"),
                        r.Result.ToString(),
                        "",
                        ""
                    });
                    foreach (var iditem in lst)
                    {
                        var c = r.Spec.Components.Contains(iditem.Comp) ? r.Spec.Components[iditem.Comp.Name] : null;
                        cells.Add(c != null ? c.ActualValue.ToString(c.EpsFormatString) : "");
                    }

                    row.CreateCells(this.gridId, cells.ToArray());
                    row.DefaultCellStyle.BackColor = Color.FromArgb(221, 217, 195);

                    this.gridId.Rows.Add(row);
                    k++;
                }
            }

            //拟合


            if (item.FitResult != null && item.FitResult.Specs != null)
            {
                var fitrow = new nodeFitRow(item.FitResult);
                fitrow.CreateCells(this.gridId, "拟合结果",
                                   "",
                                   item.FitTQ.ToString("F4"),
                                   item.FitSQ.ToString("F4"),
                                   item.FitResult.Result.ToString(),
                                   item.ConfidenceFit.ToString("F2"),
                                   string.Format("{0}%/{1}%", item.PrimalWFit, double.IsNaN(item.FitWeight) ? 0 : item.FitWeight));
                this.gridId.Rows.Add(fitrow);
                for (int i = 0; i < lst.Count; i++)
                {
                    this.gridId[7 + i, this.gridId.Rows.Count - 1].Value = lst[i].FitValue.ToString(lst[i].Comp.EpsFormatString);
                }
                this.gridId.Rows[this.gridId.Rows.Count - 1].DefaultCellStyle.BackColor = Color.FromArgb(217, 151, 149);

                k = 1;
                foreach (var d in item.FitResult.Specs)
                {
                    var cell = new DataGridViewRowHeaderCell()
                    {
                        Value = k.ToString()
                    };
                    var row = new DataGridViewRow()
                    {
                        HeaderCell = cell
                    };
                    var cells = new List <string>();

                    if (k == 1)
                    {
                        cells.AddRange(new string[] {
                            d.Spec.Name,
                            d.Spec.UUID,
                            item.FitResult.TQ.ToString("F4"),
                            item.FitResult.SQ.ToString("F4"),
                            d.Rate.ToString("F4"),
                            "",
                            ""
                        });
                    }
                    else
                    {
                        cells.AddRange(new string[] {
                            d.Spec.Name,
                            d.Spec.UUID,
                            "",
                            "",
                            d.Rate.ToString("F4"),
                            "",
                            ""
                        });
                    }
                    //添加性质
                    foreach (var fititem in lst)
                    {
                        var c = d.Spec.Components.Contains(fititem.Comp) ? d.Spec.Components[fititem.Comp.Name] : null;
                        cells.Add(c != null ? c.ActualValue.ToString(c.EpsFormatString) : "");
                    }
                    row.CreateCells(this.gridId, cells.ToArray());
                    row.DefaultCellStyle.BackColor = Color.FromArgb(217, 151, 149);
                    this.gridId.Rows.Add(row);
                    k++;
                }
            }

            //PLS
            if (lst.Select(d => d.Pls1Result != null || d.AnnResult != null).Count() > 0)
            {
                //洗添加PLS-ANN的行
                var plsrowP = new DataGridViewRow();
                plsrowP.CreateCells(this.gridId, "PLS1预测结果");
                plsrowP.DefaultCellStyle.BackColor = Color.FromArgb(117, 146, 60);
                this.gridId.Rows.Add(plsrowP);
                var plsrowW = new DataGridViewRow();
                plsrowW.CreateCells(this.gridId, "PLS1比例");
                plsrowW.DefaultCellStyle.BackColor = Color.FromArgb(117, 146, 60);
                this.gridId.Rows.Add(plsrowW);
                var plsrowMash = new DataGridViewRow();
                plsrowMash.CreateCells(this.gridId, "马氏距离");
                plsrowMash.DefaultCellStyle.BackColor = Color.FromArgb(117, 146, 60);
                this.gridId.Rows.Add(plsrowMash);
                var plsrowSec = new DataGridViewRow();
                plsrowSec.CreateCells(this.gridId, "光谱残差");
                plsrowSec.DefaultCellStyle.BackColor = Color.FromArgb(117, 146, 60);
                this.gridId.Rows.Add(plsrowSec);
                var plsrowND = new DataGridViewRow();
                plsrowND.CreateCells(this.gridId, "最邻近距离");
                plsrowND.DefaultCellStyle.BackColor = Color.FromArgb(117, 146, 60);
                this.gridId.Rows.Add(plsrowND);

                var annrowP = new DataGridViewRow();
                annrowP.CreateCells(this.gridId, "ANN预测结果");
                annrowP.DefaultCellStyle.BackColor = Color.FromArgb(83, 142, 213);
                this.gridId.Rows.Add(annrowP);
                var annrowW = new DataGridViewRow();
                annrowW.CreateCells(this.gridId, "ANN比例");
                annrowW.DefaultCellStyle.BackColor = Color.FromArgb(83, 142, 213);
                this.gridId.Rows.Add(annrowW);
                var annrowMash = new DataGridViewRow();
                annrowMash.CreateCells(this.gridId, "马氏距离");
                annrowMash.DefaultCellStyle.BackColor = Color.FromArgb(83, 142, 213);
                this.gridId.Rows.Add(annrowMash);
                var annrowSec = new DataGridViewRow();
                annrowSec.CreateCells(this.gridId, "光谱残差");
                annrowSec.DefaultCellStyle.BackColor = Color.FromArgb(83, 142, 213);
                this.gridId.Rows.Add(annrowSec);
                var annrowND = new DataGridViewRow();
                annrowND.CreateCells(this.gridId, "最邻近距离");
                annrowND.DefaultCellStyle.BackColor = Color.FromArgb(83, 142, 213);
                this.gridId.Rows.Add(annrowND);

                foreach (var r in lst)
                {
                    if (r.Pls1Result != null)
                    {
                        var idx = this.findColumnIndex(r.Pls1Result.Comp.Name);
                        if (idx >= 0)
                        {
                            var factor = r.Pls1Result.Factor - 1;
                            plsrowP.Cells[idx].Value    = r.Pls1Result.Comp.PredictedValue.ToString(r.Pls1Result.Comp.EpsFormatString);
                            plsrowP.Cells[idx].Style    = r.Pls1Result.Comp.Style;
                            plsrowW.Cells[idx].Value    = string.Format("{0}%/{1}%", this.doubleToString(r.PrimalWPLS1, 1), this.doubleToString(r.Pls1Weight, 1));
                            plsrowMash.Cells[idx].Value = string.Format("{0}/{1}", this.doubleToString(r.Pls1Result.MDMin), this.doubleToString(r.Pls1Result.MahDist[factor]));
                            plsrowSec.Cells[idx].Value  = string.Format("{0}/{1}", this.doubleToString(r.Pls1Result.SRMin), this.doubleToString(r.Pls1Result.SR[factor]));
                            plsrowND.Cells[idx].Value   = string.Format("{0}/{1}", this.doubleToString(r.Pls1Result.NDMin), this.doubleToString(r.Pls1Result.ND[factor]));
                        }
                    }

                    if (r.AnnResult != null)
                    {
                        var idx = this.findColumnIndex(r.AnnResult.Comp.Name);
                        if (idx >= 0)
                        {
                            var factor = r.AnnResult.Factor - 1;
                            annrowP.Cells[idx].Value    = r.AnnResult.Comp.PredictedValue.ToString(r.AnnResult.Comp.EpsFormatString);
                            annrowP.Cells[idx].Style    = r.AnnResult.Comp.Style;
                            annrowW.Cells[idx].Value    = string.Format("{0}/{1}", this.doubleToString(r.PrimalWPLS1), this.doubleToString(r.Pls1Weight));
                            annrowMash.Cells[idx].Value = string.Format("{0}/{1}", this.doubleToString(r.AnnResult.MDMin), this.doubleToString(r.AnnResult.MahDist[factor]));
                            annrowSec.Cells[idx].Value  = string.Format("{0}/{1}", this.doubleToString(r.AnnResult.SRMin), this.doubleToString(r.AnnResult.SR[factor]));
                            annrowND.Cells[idx].Value   = string.Format("{0}/{1}", this.doubleToString(r.AnnResult.NDMin), this.doubleToString(r.AnnResult.ND[factor]));
                        }
                    }
                }
            }



            return(this.ShowDialog());
        }
Пример #29
0
        public IAnalysisResult Analyze(Spectrum data, IMeasurementSettings settings)
        {
            var imdSettings = settings as IImdSettings;

            if (imdSettings == null)
            {
                throw new InvalidOperationException();
            }

            var result = new ImdAnalysisResult();

            result.Data = data;

            var maxFrequency = imdSettings.LimitMaxFrequency ? imdSettings.MaxFrequency : data.MaxFrequency;
            var f1           = imdSettings.F1Frequency;
            var f2           = imdSettings.F2Frequency;
            var f1i          = data.GetFrequencyIndices(f1, imdSettings.WindowHalfSize);
            var f2i          = data.GetFrequencyIndices(f2, imdSettings.WindowHalfSize);
            var f1rss        = data.ValueAtFrequency(f1, x => x.Mean, imdSettings.WindowHalfSize);
            var f2rss        = data.ValueAtFrequency(f2, x => x.Mean, imdSettings.WindowHalfSize);

            /* Total IMD+Noise is full bandwidth except F1 and F2 frequencies */
            double totalImd = 0.0;
            double total    = 0.0;
            var    right    = data.GetFrequencyIndices(maxFrequency, 0).First();

            for (var f = 0; f < right; f++)
            {
                total += Math.Pow(data.Statistics[f].Mean, 2.0);

                if (!f1i.Contains(f) && !f2i.Contains(f))
                {
                    totalImd += Math.Pow(data.Statistics[f].Mean, 2.0);
                }
            }
            totalImd = Math.Sqrt(totalImd) / Math.Sqrt(total);

            result.TotalImdPlusNoisePercentage = 100.0 * totalImd;
            result.TotalImdPlusNoiseDb         = -totalImd.ToDbTp();

            var orders = new Dictionary <int, double>();
            var order  = imdSettings.MaxOrder;

            for (var n = -order + 1; n < order; n++)
            {
                for (var m = -order + 1; m < order; m++)
                {
                    if (n == 0 || m == 0)
                    {
                        continue;
                    }

                    var o = Math.Max(Math.Abs(n), Math.Abs(m)) + 1;
                    var f = n * f1 + m * f2;
                    if (f > 0 && f < maxFrequency)
                    {
                        var imd = data.ValueAtFrequency(f, x => x.Mean, imdSettings.WindowHalfSize);
                        if (!orders.ContainsKey(o))
                        {
                            orders.Add(o, imd);
                        }
                        else
                        {
                            orders[o] += imd;
                        }
                    }
                }
            }

            result.F1Db        = -f1rss.ToDbTp();
            result.F2Db        = -f2rss.ToDbTp();
            result.F1Frequency = f1;
            result.F2Frequency = f2;

            result.MaxOrder  = imdSettings.MaxOrder;
            result.Bandwidth = maxFrequency;

            var sumOfOrders = 0.0;

            for (var i = 2; i <= order; i++)
            {
                sumOfOrders += Math.Pow(orders[i], 2.0);
                orders[i]    = -orders[i].ToDbTp();
            }
            sumOfOrders       = Math.Sqrt(sumOfOrders);
            result.OrderedImd = orders.OrderBy(o => o.Key).ToDictionary(k => k.Key, v => v.Value);

            result.ImdF2ForGivenOrderPercentage = (sumOfOrders / f1rss) * 100.0;
            result.ImdF2ForGivenOrderDb         = -(sumOfOrders / f1rss).ToDbTp();

            result.ImdF1F2ForGivenOrderPercentage = (sumOfOrders / (f1rss + f2rss)) * 100.0;
            result.ImdF1F2ForGivenOrderDb         = -(sumOfOrders / (f1rss + f2rss)).ToDbTp();

            return(result);
        }
Пример #30
0
        public Spectrum SampleF(Vector woW, out Vector wiW, BsdfSample bsdfSample,
                                out float pdf, out BxdfType sampledType, BxdfType flags = BxdfType.All)
        {
            // Choose which _BxDF_ to sample
            int matchingComps = NumComponents(flags);

            if (matchingComps == 0)
            {
                wiW         = Vector.Zero;
                pdf         = 0.0f;
                sampledType = 0;
                return(Spectrum.CreateBlack());
            }
            int which = Math.Min(
                MathUtility.Floor(bsdfSample.UComponent * matchingComps),
                matchingComps - 1);
            Bxdf bxdf  = null;
            int  count = which;

            foreach (var eachBxdf in _bxdfs)
            {
                if (eachBxdf.MatchesFlags(flags) && count-- == 0)
                {
                    bxdf = eachBxdf;
                    break;
                }
            }
            Debug.Assert(bxdf != null);

            // Sample chosen _BxDF_
            Vector wo = WorldToLocal(woW);
            Vector wi;

            pdf = 0.0f;
            Spectrum f = bxdf.SampleF(wo, out wi, bsdfSample.UDir0, bsdfSample.UDir1, out pdf);

            if (pdf == 0.0f)
            {
                wiW         = Vector.Zero;
                sampledType = 0;
                return(Spectrum.CreateBlack());
            }
            sampledType = bxdf.Type;
            wiW         = LocalToWorld(wi);

            // Compute overall PDF with all matching _BxDF_s
            if (!bxdf.Type.HasFlag(BxdfType.Specular) && matchingComps > 1)
            {
                foreach (var eachBxdf in _bxdfs)
                {
                    if (eachBxdf != bxdf && eachBxdf.MatchesFlags(flags))
                    {
                        pdf += bxdf.Pdf(wo, wi);
                    }
                }
            }
            if (matchingComps > 1)
            {
                pdf /= matchingComps;
            }

            // Compute value of BSDF for sampled direction
            if (!bxdf.Type.HasFlag(BxdfType.Specular))
            {
                f = Spectrum.CreateBlack();
                if (Vector.Dot(wiW, _ng) * Vector.Dot(woW, _ng) > 0) // ignore BTDFs
                {
                    flags &= ~BxdfType.Transmission;
                }
                else // ignore BRDFs
                {
                    flags &= ~BxdfType.Reflection;
                }
                foreach (var eachBxdf in _bxdfs)
                {
                    if (eachBxdf.MatchesFlags(flags))
                    {
                        f += eachBxdf.F(wo, wi);
                    }
                }
            }
            return(f);
        }
Пример #31
0
 public Z80Serializer(Spectrum spec)
     : base(spec)
 {
 }
Пример #32
0
 public SpecularReflection(Spectrum r, Fresnel fresnel)
     : base(BxDFType.Reflection | BxDFType.Specular)
 {
     this.reflectance = r;
     this.fresnel     = fresnel;
 }
Пример #33
0
 public FresnelConductor(Spectrum e, Spectrum k)
 {
     Eta = e;
     K = k;
 }
Пример #34
0
        private static IScene Build()
        {
            var white =
                new MatteMaterial(
                    new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.6f, 0f, 0.9f }, SpectrumType.Illuminant)),
                    new ConstantTexture <float>(0), null);

            var sss = new DisneyMaterial(
                new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.9f, 0.9f, 0.9f }, SpectrumType.Reflectance)),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1.5f),
                new ConstantTexture <float>(0.5f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0.5f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <Spectrum>(new Spectrum(40f)),
                false,
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0.5f),
                null);

            var red =
                new DisneyMaterial(
                    new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.9f, 0f, 0f }, SpectrumType.Reflectance)),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(1.5f),
                    new ConstantTexture <float>(0.8f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0.9f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <Spectrum>(Spectrum.Zero),
                    false,
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0.5f),
                    null);

            var yellow =
                new DisneyMaterial(
                    new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 1f, 1f, 0f }, SpectrumType.Reflectance)),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(1.5f),
                    new ConstantTexture <float>(1f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0.9f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <Spectrum>(Spectrum.Zero),
                    false,
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0.5f),
                    null);

            var cyan =
                new DisneyMaterial(
                    new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0f, 1f, 1f }, SpectrumType.Reflectance)),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(1.8f),
                    new ConstantTexture <float>(0.1f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(1f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(1f),
                    new ConstantTexture <float>(0.9f),
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <Spectrum>(Spectrum.Zero),
                    false,
                    new ConstantTexture <float>(0f),
                    new ConstantTexture <float>(0.5f),
                    null);

            var metal = new DisneyMaterial(
                new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.5f, 0.5f, 0.5f }, SpectrumType.Reflectance)),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(1.5f),
                new ConstantTexture <float>(0.4f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <Spectrum>(Spectrum.Zero),
                false,
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0.5f),
                null);

            var mirror = new DisneyMaterial(
                new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.7f, 0.7f, 0.8f }, SpectrumType.Reflectance)),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(1.5f),
                new ConstantTexture <float>(0.1f),
                new ConstantTexture <float>(0.5f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <Spectrum>(Spectrum.Zero),
                false,
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0.5f),
                null);

            var trans = new DisneyMaterial(
                new ConstantTexture <Spectrum>(Spectrum.FromRGB(new[] { 0.0f, 0.8f, 0.0f }, SpectrumType.Illuminant)),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(2.5f),
                new ConstantTexture <float>(0.01f),
                new ConstantTexture <float>(0.5f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(1f),
                new ConstantTexture <float>(0f),
                new ConstantTexture <Spectrum>(new Spectrum(0f)),
                false,
                new ConstantTexture <float>(0f),
                new ConstantTexture <float>(0f),
                null);

            var px   = 3000;
            var pz   = 3000;
            var tr   = Transform.Translate(-500, 178, -600);
            var tris = TriangleMesh.CreateTriangleMesh(
                tr,
                Transform.Invert(tr),
                false,
                2,
                new[] { 0, 1, 2, 3, 2, 1 },
                4,
                new[]
            {
                new Point(0, 0, 0),
                new Point(0, 0, pz),
                new Point(px, 0, 0),
                new Point(px, 0, pz)
            },
                null,
                null, null, null, null, null);

            var prims = new List <IPrimitive>();

            foreach (var tri in tris)
            {
                prims.Add(new GeometricPrimitive(tri, red, null));
            }

            var s1t = Transform.Translate(278, 278, 100);
            var s1  = new Sphere(s1t, Transform.Invert(s1t), false, 100f, -100, 100, 360);
            var s1g = new GeometricPrimitive(s1, sss, null);

            prims.Add(s1g);

            var s2t = Transform.Translate(390, 228, 30);
            var s2  = new Sphere(s2t, Transform.Invert(s2t), false, 50f, -50, 50, 360);
            var s2g = new GeometricPrimitive(s2, cyan, null);

            prims.Add(s2g);

            var s3t = Transform.Translate(50, 328, 200);
            var s3  = new Sphere(s3t, Transform.Invert(s3t), false, 150f, -150, 150, 360);
            var s3g = new GeometricPrimitive(s3, yellow, null);

            prims.Add(s3g);

            var s4t = Transform.Translate(480, 238, -50);
            var s4  = new Sphere(s4t, Transform.Invert(s4t), false, 60f, -60, 60, 360);
            var s4g = new GeometricPrimitive(s4, metal, null);

            prims.Add(s4g);

            var s5t = Transform.Translate(490, 255, 250);
            var s5  = new Sphere(s5t, Transform.Invert(s5t), false, 80f, -80, 80, 360);
            var s5g = new GeometricPrimitive(s5, white, null);

            prims.Add(s5g);

            var s7t = Transform.Translate(150, 248, -120);
            var s7  = new Sphere(s7t, Transform.Invert(s7t), false, 70f, -70, 70, 360);
            var s7g = new GeometricPrimitive(s7, trans, null);

            prims.Add(s7g);

            //var temp = 5000f;
            //var lightMatte =
            //    new MatteMaterial(
            //        new ConstantTexture<Spectrum>(Spectrum.FromBlackbodyT(temp)),
            //        new ConstantTexture<float>(0), null);
            //var s6t = Transform.Translate(400, 188, -230);
            //var s6 = new Sphere(s6t, Transform.Invert(s6t), false, 10f, -10, 10, 360);
            //var dl = new DiffuseAreaLight(s6t, null, Spectrum.FromBlackbodyT(temp) * 60f, 12, s6);
            //var s6g = new GeometricPrimitive(s6, lightMatte, dl);
            //prims.Add(s6g);

            var bvh = new BVH(prims.ToArray(), SplitMethod.HLBVH);

            var lt   = Transform.RotateX(MathF.Rad(75)).Translate(278, 600, -120);
            var s    = Spectrum.FromBlackbodyT(4500) * 400000f;
            var spot = new SpotLight(lt, null, s, 120, 20);

            lt = Transform.RotateX(MathF.Rad(75)).Translate(278, 300, -300);
            s  = Spectrum.FromBlackbodyT(6500) * 55000f;
            var point = new PointLight(lt, null, s);

            return(new Scene(bvh, new ILight[] { spot, point }));
        }
Пример #35
0
        public override void AddSample(CameraSample sample, Spectrum l)
        {
            // Compute sample's raster extent
            float dimageX = sample.ImageX - 0.5f;
            float dimageY = sample.ImageY - 0.5f;
            int x0 = MathUtility.Ceiling(dimageX - _filter.XWidth);
            int x1 = MathUtility.Floor(dimageX + _filter.XWidth);
            int y0 = MathUtility.Ceiling(dimageY - _filter.YWidth);
            int y1 = MathUtility.Floor(dimageY + _filter.YWidth);
            x0 = Math.Max(x0, _xPixelStart);
            x1 = Math.Min(x1, _xPixelStart + _xPixelCount - 1);
            y0 = Math.Max(y0, _yPixelStart);
            y1 = Math.Min(y1, _yPixelStart + _yPixelCount - 1);
            if ((x1 - x0) < 0 || (y1 - y0) < 0)
                return;

            // Loop over filter support and add sample to pixel arrays
            var xyz = l.ToXyz();

            // Precompute $x$ and $y$ filter table offsets
            var ifx = new int[x1 - x0 + 1];
            for (int x = x0; x <= x1; ++x)
            {
                float fx = Math.Abs((x - dimageX) * _filter.InverseXWidth * FilterTableSize);
                ifx[x - x0] = Math.Min(MathUtility.Floor(fx), FilterTableSize - 1);
            }
            var ify = new int[y1 - y0 + 1];
            for (int y = y0; y <= y1; ++y)
            {
                float fy = Math.Abs((y - dimageY) * _filter.InverseYWidth * FilterTableSize);
                ify[y - y0] = Math.Min(MathUtility.Floor(fy), FilterTableSize - 1);
            }
            bool syncNeeded = (_filter.XWidth > 0.5f || _filter.YWidth > 0.5f);
            for (int y = y0; y <= y1; ++y)
            {
                for (int x = x0; x <= x1; ++x)
                {
                    // Evaluate filter value at $(x,y)$ pixel
                    int offset = ify[y - y0] * FilterTableSize + ifx[x - x0];
                    float filterWt = _filterTable[offset];

                    // Update pixel values with filtered sample contribution
                    var pixel = _pixels[x - _xPixelStart, y - _yPixelStart];
                    if (!syncNeeded)
                    {
                        pixel.Lxyz[0] += filterWt * xyz[0];
                        pixel.Lxyz[1] += filterWt * xyz[1];
                        pixel.Lxyz[2] += filterWt * xyz[2];
                        pixel.WeightSum += filterWt;
                    }
                    else
                    {
                        // Safely update _Lxyz_ and _weightSum_ even with concurrency
                        AtomicAdd(ref pixel.Lxyz[0], filterWt * xyz[0]);
                        AtomicAdd(ref pixel.Lxyz[1], filterWt * xyz[1]);
                        AtomicAdd(ref pixel.Lxyz[2], filterWt * xyz[2]);
                        AtomicAdd(ref pixel.WeightSum, filterWt);
                    }
                }
            }
        }
Пример #36
0
        private void HandleSpectrum(
            ref SpectrumTrackingInfo trackingInfo,
            Dictionary <int, List <int> > isolationMzBinToScanNums,
            Spectrum spec)
        {
            trackingInfo.SpecRead += 1;

            //Console.WriteLine("Reading Scan {0}; {1} peaks", spec.ScanNum, spec.Peaks.Length);
            ScanNumToMsLevel[spec.ScanNum]      = spec.MsLevel;
            ScanNumElutionTimeMap[spec.ScanNum] = spec.ElutionTime;
            if (spec.MsLevel == 1)
            {
                if (trackingInfo.PrecursorSignalToNoiseRatioThreshold > 0.0)
                {
                    spec.FilterNoise(trackingInfo.PrecursorSignalToNoiseRatioThreshold);
                }

                //foreach (var peak in spec.Peaks)
                //{
                //    _ms1PeakList.Add(new LcMsPeak(peak.Mz, peak.Intensity, spec.ScanNum));
                //}
                _ms1PeakList.AddRange(spec.Peaks.Select(peak => new LcMsPeak(peak.Mz, peak.Intensity, spec.ScanNum)));
                _scanNumSpecMap.Add(spec.ScanNum, spec);
            }
            else if (spec.MsLevel == 2)
            {
                var productSpec = spec as ProductSpectrum;

                if (productSpec != null)
                {
                    if (trackingInfo.ProductSignalToNoiseRatioThreshold > 0.0)
                    {
                        productSpec.FilterNoise(trackingInfo.ProductSignalToNoiseRatioThreshold);
                    }

                    var isolationWindow = productSpec.IsolationWindow;
                    var minBinNum       = (int)Math.Round(isolationWindow.MinMz * IsolationWindowBinningFactor);
                    var maxBinNum       = (int)Math.Round(isolationWindow.MaxMz * IsolationWindowBinningFactor);
                    for (var binNum = minBinNum; binNum <= maxBinNum; binNum++)
                    {
                        if (!isolationMzBinToScanNums.TryGetValue(binNum, out var scanNumList))
                        {
                            scanNumList = new List <int>();
                            isolationMzBinToScanNums[binNum] = scanNumList;
                        }
                        scanNumList.Add(productSpec.ScanNum);
                    }
                    _scanNumSpecMap.Add(spec.ScanNum, productSpec);
                }
            }

            if (spec.ScanNum < trackingInfo.MinScanNum)
            {
                trackingInfo.MinScanNum = spec.ScanNum;
            }
            if (spec.ScanNum > trackingInfo.MaxScanNum)
            {
                trackingInfo.MaxScanNum = spec.ScanNum;
            }

            if (spec.MsLevel < trackingInfo.MinMsLevel)
            {
                trackingInfo.MinMsLevel = spec.MsLevel;
            }
            if (spec.MsLevel > trackingInfo.MaxMsLevel)
            {
                trackingInfo.MaxMsLevel = spec.MsLevel;
            }
        }
Пример #37
0
 public static Spectrum FrDiel(double cosi, double cost, Spectrum etai, Spectrum etat)
 {
     Spectrum Rparl = ((etat * cosi) - (etai * cost)) / ((etat * cosi) + (etai * cost));
     Spectrum Rperp = ((etai * cosi) - (etat * cost)) / ((etai * cosi) + (etat * cost));
     return (Rparl * Rparl + Rperp * Rperp) / 2.0;
 }
Пример #38
0
 public DiffuseAreaLight(Transform lightToWorld, Spectrum lemit, int numSamples, Shape shape) 
     : base(lightToWorld, numSamples)
 {
 }
 public RectangleLightFakeForSobolev(Point3D position, float length, float width, Spectrum illuminance, IMaterial material, int samples = 32)
     : base(position, length, width, illuminance, material, samples)
 {
 }
Пример #40
0
 public RankedPeaks(Spectrum spectrum)
     : base(spectrum.Peaks, spectrum.ScanNum)
 {
     _spectrum = spectrum;
     Array.Sort(Peaks, new IntensityComparer());
 }
Пример #41
0
        private void btnPredict_Click(object sender, EventArgs e)
        {
            if (this._model == null)
            {
                return;
            }

            OpenFileDialog myOpenFileDialog = new OpenFileDialog();

            myOpenFileDialog.InitialDirectory = Busi.Common.Configuration.FolderSpectrum;
            myOpenFileDialog.Multiselect      = true;
            myOpenFileDialog.Filter           = Spectrum.GetDialogFilterString();
            if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.progressBar1.Visible = true;
                this.toolStrip1.Enabled   = false;

                var    flst = myOpenFileDialog.FileNames.ToList();
                Action a    = () =>
                {
                    foreach (var f in flst)
                    {
                        var sp = new Spectrum(f);
                        var pr = this._model.Predict(sp);
                        if (this.dataGridView1.InvokeRequired)
                        {
                            ThreadStart s = () =>
                            {
                                if (!this._inited)
                                {
                                    this.init(this._model);
                                }
                                this.addRow(pr, sp);
                            };
                            this.dataGridView1.Invoke(s);
                        }
                        else
                        {
                            if (!this._inited)
                            {
                                this.init(this._model);
                            }
                            this.addRow(pr, sp);
                        }
                    }



                    if (this.toolStrip1.InvokeRequired)
                    {
                        ThreadStart s = () =>
                        {
                            this.progressBar1.Visible = false;
                            this.toolStrip1.Enabled   = true;
                        };
                        this.toolStrip1.Invoke(s);
                    }
                    else
                    {
                        this.progressBar1.Visible = false;
                        this.toolStrip1.Enabled   = true;
                    }
                };
                a.BeginInvoke(null, null);
            }
        }
Пример #42
0
        private void gridView_ShowCellToolTip(DataGridViewCell cell)
        {
            MassSpectrum spectrum = cell.OwningRow.Tag as MassSpectrum;
            Spectrum     s        = spectrum.Element;

            TreeViewForm treeViewForm = new TreeViewForm(spectrum);
            TreeView     tv           = treeViewForm.TreeView;

            if (gridView.Columns[cell.ColumnIndex].Name == "PrecursorInfo")
            {
                treeViewForm.Text = "Precursor Details";
                if (s.precursors.Count == 0)
                {
                    tv.Nodes.Add("No precursor information available.");
                }
                else
                {
                    foreach (Precursor p in s.precursors)
                    {
                        string pNodeText = "Precursor scan";
                        if (p.sourceFile != null && p.externalSpectrumID.Length > 0)
                        {
                            pNodeText += String.Format(": {0}:{1}", p.sourceFile.name, p.externalSpectrumID);
                        }
                        else if (p.spectrumID.Length > 0)
                        {
                            pNodeText += String.Format(": {0}", p.spectrumID);
                        }

                        TreeNode pNode = tv.Nodes.Add(pNodeText);
                        addParamsToTreeNode(p as ParamContainer, pNode);

                        if (p.selectedIons.Count == 0)
                        {
                            pNode.Nodes.Add("No selected ion list available.");
                        }
                        else
                        {
                            foreach (SelectedIon si in p.selectedIons)
                            {
                                TreeNode siNode = pNode.Nodes.Add("Selected ion");
                                //siNode.ToolTipText = new CVTermInfo(CVID.MS_selected_ion); // not yet in CV
                                addParamsToTreeNode(si as ParamContainer, siNode);
                            }
                        }

                        if (p.activation.empty())
                        {
                            pNode.Nodes.Add("No activation details available.");
                        }
                        else
                        {
                            TreeNode actNode = pNode.Nodes.Add("Activation");
                            addParamsToTreeNode(p.activation as ParamContainer, actNode);
                        }

                        if (p.isolationWindow.empty())
                        {
                            pNode.Nodes.Add("No isolation window details available.");
                        }
                        else
                        {
                            TreeNode iwNode = pNode.Nodes.Add("Isolation Window");
                            addParamsToTreeNode(p.isolationWindow as ParamContainer, iwNode);
                        }
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "ScanInfo")
            {
                treeViewForm.Text = "Scan Configuration Details";
                if (s.scanList.empty())
                {
                    tv.Nodes.Add("No scan details available.");
                }
                else
                {
                    TreeNode slNode = tv.Nodes.Add("Scan List");
                    addParamsToTreeNode(s.scanList as ParamContainer, slNode);

                    foreach (Scan scan in s.scanList.scans)
                    {
                        TreeNode scanNode = slNode.Nodes.Add("Acquisition");
                        addParamsToTreeNode(scan as ParamContainer, scanNode);

                        foreach (ScanWindow sw in scan.scanWindows)
                        {
                            TreeNode swNode = scanNode.Nodes.Add("Scan Window");
                            addParamsToTreeNode(sw as ParamContainer, swNode);
                        }
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "InstrumentConfigurationID")
            {
                treeViewForm.Text = "Instrument Configuration Details";
                InstrumentConfiguration ic = s.scanList.scans[0].instrumentConfiguration;
                if (ic == null || ic.empty())
                {
                    tv.Nodes.Add("No instrument configuration details available.");
                }
                else
                {
                    TreeNode icNode = tv.Nodes.Add(String.Format("Instrument Configuration ({0})", ic.id));
                    addParamsToTreeNode(ic as ParamContainer, icNode);

                    if (ic.componentList.Count == 0)
                    {
                        icNode.Nodes.Add("No component list available.");
                    }
                    else
                    {
                        TreeNode clNode = icNode.Nodes.Add("Component List");
                        foreach (pwiz.CLI.msdata.Component c in ic.componentList)
                        {
                            string cNodeText;
                            switch (c.type)
                            {
                            case ComponentType.ComponentType_Source:
                                cNodeText = "Source";
                                break;

                            case ComponentType.ComponentType_Analyzer:
                                cNodeText = "Analyzer";
                                break;

                            default:
                            case ComponentType.ComponentType_Detector:
                                cNodeText = "Detector";
                                break;
                            }
                            TreeNode cNode = clNode.Nodes.Add(cNodeText);
                            addParamsToTreeNode(c as ParamContainer, cNode);
                        }
                    }

                    Software sw = ic.software;
                    if (sw == null || sw.empty())
                    {
                        icNode.Nodes.Add("No software details available.");
                    }
                    else
                    {
                        TreeNode swNode        = icNode.Nodes.Add(String.Format("Software ({0})", sw.id));
                        CVParam  softwareParam = sw.cvParamChild(CVID.MS_software);
                        TreeNode swNameNode    = swNode.Nodes.Add("Name: " + softwareParam.name);
                        swNameNode.ToolTipText = new CVTermInfo(softwareParam.cvid).def;
                        swNode.Nodes.Add("Version: " + sw.version);
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "DataProcessing")
            {
                treeViewForm.Text = "Data Processing Details";
                DataProcessing dp = s.dataProcessing;
                if (dp == null || dp.empty())
                {
                    tv.Nodes.Add("No data processing details available.");
                }
                else
                {
                    TreeNode dpNode = tv.Nodes.Add(String.Format("Data Processing ({0})", dp.id));

                    if (dp.processingMethods.Count == 0)
                    {
                        dpNode.Nodes.Add("No component list available.");
                    }
                    else
                    {
                        TreeNode pmNode = dpNode.Nodes.Add("Processing Methods");
                        foreach (ProcessingMethod pm in dp.processingMethods)
                        {
                            addParamsToTreeNode(pm as ParamContainer, pmNode);
                        }
                    }
                }
            }
            else
            {
                return;
            }

            tv.ExpandAll();
            treeViewForm.StartPosition = FormStartPosition.CenterParent;
            treeViewForm.AutoSize      = true;
            //treeViewForm.DoAutoSize();
            treeViewForm.Show(this.DockPanel);
            //leaveTimer.Start();
            this.Focus();
        }
Пример #43
0
 public Spectrum Li(Scene scene, RayDifferential ray, Sample sample, ref Intersection isect)
 {
     Spectrum T = new Spectrum ();
     return Li (scene, ray, sample, ref isect, ref T);
 }
Пример #44
0
 public PeptideIsoform(Peptide peptide, Spectrum spectrum, int charge)
     : base(peptide)
 {
     Spectrum = spectrum;
     Charge   = charge;
 }
Пример #45
0
 public virtual bool ReportResults(Sample[] samples, RayDifferential[] rays,
     Spectrum[] ls, Intersection[] intersections, int count)
 {
     return true;
 }
Пример #46
0
 public ZxSerializer(Spectrum spec)
 {
     this._spec = spec;
 }
Пример #47
0
 public PlasticMaterial(Spectrum d, Spectrum s, float r)
 {
     diffuse   = d;
     specular  = s;
     roughness = r;
 }
Пример #48
0
 public dbgWD1793(Spectrum spectrum)
 {
     this._betaDiskDevice = (spectrum as IBetaDiskDevice);
     this.InitializeComponent();
 }
Пример #49
0
 /// <summary>
 /// Called on first instantiation (and subsequent core reboots)
 /// </summary>
 /// <param name="files"></param>
 protected void InitializeMedia(List <byte[]> files)
 {
     mediaImages = files;
     LoadAllMedia();
     Spectrum.OSD_TapeInit();
 }
Пример #50
0
        /// <summary>
        /// Write the supplied spectrum to the current position in <paramref name="writer"/>
        /// </summary>
        /// <param name="specIn"></param>
        /// <param name="writer"></param>
        protected internal override void WriteSpectrum(Spectrum specIn, BinaryWriter writer)
        {
            // All changes made here must be duplicated to ReadSpectrum() and GetPeakMetadataForSpectrum()
            if (!(specIn is DeconvolutedSpectrum spec))
            {
                throw new ArgumentException("Input spectrum must be DeconvolutedSpectrum!", nameof(specIn));
            }

            // scan number: 4
            writer.Write(spec.ScanNum);

            // NativeID: 50
            // pad or truncate to keep in limit (may have to change in future...)
            writer.Write(spec.NativeId.PadRight(NativeIdLength).ToCharArray(0, NativeIdLength), 0, NativeIdLength);

            // ms level: 1
            writer.Write(Convert.ToByte(spec.MsLevel));

            // elution time: 4
            writer.Write(spec.ElutionTime);

            // Total Ion Current: 4
            writer.Write(Convert.ToSingle(spec.TotalIonCurrent));

            var isolationWindow = spec.IsolationWindow;

            // precursor mass: 8
            writer.Write(isolationWindow.MonoisotopicMz ?? 0.0);
            // precursor charge: 4
            writer.Write(isolationWindow.Charge ?? 0);
            // Activation method: 1
            writer.Write((byte)spec.ActivationMethod);
            // Isolation window target m/z: 8
            writer.Write(isolationWindow.IsolationWindowTargetMz);
            // Isolation window lower offset: 8
            writer.Write(isolationWindow.IsolationWindowLowerOffset);
            // Isolation window upper offset: 8
            writer.Write(isolationWindow.IsolationWindowUpperOffset);

            // Guarantee sorted peaks.
            //var peaks = spec.Peaks.ToList();
            Array.Sort(spec.Peaks);
            //peaks.Sort();
            // Number of peaks: 4
            writer.Write(spec.Peaks.Length);
            //writer.Write(peaks.Count);
            foreach (var peakIn in spec.Peaks)
            //foreach (var peak in peaks)
            {
                var peak = peakIn as DeconvolutedPeak;
                if (peak == null)
                {
                    throw new ArgumentException("Input spectrum peaks array must contain only DeconvolutedPeaks!");
                }
                // m/z: 8
                writer.Write(peak.Mz);
                // intensity: 4
                writer.Write(Convert.ToSingle(peak.Intensity));
                // charge: 4
                writer.Write(peak.Charge);
                // correlation: 4
                writer.Write(Convert.ToSingle(peak.Corr));
                // distance: 4
                writer.Write(Convert.ToSingle(peak.Dist));

                // Output indices of isotope peaks where index (in PbfLcMsRun) is < 65535
                var isotopePeaksInRange = peak.ObservedPeakIndices.Where(x => x >= ushort.MinValue && x <= ushort.MaxValue).ToList();
                if (isotopePeaksInRange.Count != peak.ObservedPeakIndices.Count)
                {
                    WarnOnce(WriteWarnings.PeakIndexCannotBeStored, "Cannot output all observed peaks for some peaks - more than 65535 peaks in observed spectrum");
                }
                // Count of isotope peaks, as byte: 1
                writer.Write((byte)isotopePeaksInRange.Count);
                // Output indices, as unsigned shorts
                foreach (var index in isotopePeaksInRange)
                {
                    writer.Write((ushort)index);
                }
            }
        }
Пример #51
0
 public override void Splat(CameraSample sample, Spectrum l)
 {
     var xyz = l.ToXyz();
     int x = MathUtility.Floor(sample.ImageX), y = MathUtility.Floor(sample.ImageY);
     if (x < _xPixelStart || x - _xPixelStart >= _xPixelCount ||
         y < _yPixelStart || y - _yPixelStart >= _yPixelCount) return;
     var pixel = _pixels[x - _xPixelStart, y - _yPixelStart];
     AtomicAdd(ref pixel.SplatXyz[0], xyz[0]);
     AtomicAdd(ref pixel.SplatXyz[1], xyz[1]);
     AtomicAdd(ref pixel.SplatXyz[2], xyz[2]);
 }
Пример #52
0
        private FilesStatus upload(Stream inputStream, string fileName, HttpContext context)
        {
            var statu = new FilesStatus();

            var filename     = RIPP.Web.Chem.Tools.Common.GetRnd(10, true, true, false) + Path.GetExtension(fileName);
            var tempfullName = Path.Combine(StorageRoot, filename);

            statu.progress = "1.0";
            statu.size     = (int)inputStream.Length;
            statu.name     = fileName;
            try
            {
                //先保存在服务器一个临时文件
                using (var fs = new FileStream(tempfullName, FileMode.Append, FileAccess.Write))
                {
                    var buffer = new byte[1024];
                    var l      = inputStream.Read(buffer, 0, 1024);
                    while (l > 0)
                    {
                        fs.Write(buffer, 0, l);
                        l = inputStream.Read(buffer, 0, 1024);
                    }
                    fs.Flush();
                    fs.Close();
                }
            }
            catch
            {
                statu.error = "服务器错误,上传文件失败!";
                return(statu);
            }

            //根据文件后缀尝试打开文件
            var   ftype   = BindModel.CheckType(tempfullName);
            model dbmodel = new model();
            spec  sp      = new spec();

            try
            {
                statu.type   = ftype.GetDescription();
                dbmodel.path = Path.Combine(RIPP.Web.Chem.Tools.Common.GetUploadPath(), filename);
                sp.path      = dbmodel.path;
                switch (ftype)
                {
                case FileExtensionEnum.Allmethods:
                    var mBind = BindModel.ReadModel <BindModel>(tempfullName);
                    statu.description  = mBind.ToString();
                    dbmodel.createtime = mBind.CreateTime;
                    dbmodel.name       = mBind.Name;
                    // ;
                    // dbmodel.type = (int)ftype;
                    //  dbmodel.
                    break;

                case FileExtensionEnum.PLSBind:
                    var mPLS = BindModel.ReadModel <PLSModel>(tempfullName);
                    statu.description  = mPLS.ToString();
                    dbmodel.createtime = mPLS.CreateTime;
                    dbmodel.name       = mPLS.Name;
                    break;

                case FileExtensionEnum.IdLib:
                    var mId = BindModel.ReadModel <IdentifyModel>(tempfullName);
                    statu.description  = mId.ToString();
                    dbmodel.createtime = mId.CreateTime;
                    dbmodel.name       = mId.Name;
                    break;

                case FileExtensionEnum.FitLib:
                    var mFitting = BindModel.ReadModel <FittingModel>(tempfullName);
                    statu.description  = mFitting.ToString();
                    dbmodel.createtime = mFitting.CreateTime;
                    dbmodel.name       = mFitting.Name;
                    break;

                case FileExtensionEnum.PLS1:
                case FileExtensionEnum.PLSANN:
                    var mPLS1 = BindModel.ReadModel <PLSSubModel>(tempfullName);
                    statu.description  = mPLS1.ToString();
                    dbmodel.createtime = mPLS1.CreateTime;
                    dbmodel.name       = mPLS1.Name;
                    break;

                case FileExtensionEnum.ItgBind:
                    var itgSub = BindModel.ReadModel <IntegrateModel>(tempfullName);
                    statu.description  = itgSub.ToString();
                    dbmodel.createtime = itgSub.CreateTime;
                    dbmodel.name       = itgSub.Name;
                    break;

                case FileExtensionEnum.Spec:
                default:
                    var s = new Spectrum(tempfullName);
                    ftype             = FileExtensionEnum.Spec;
                    sp.Spec           = s;
                    sp.name           = Path.GetFileName(fileName);
                    statu.description = "光谱文件";
                    break;
                }
            }
            catch (Exception ex)//读取文件失败
            {
                statu.error = "上传的文件类型有误,服务器无法识别,上传文件失败!";

                if (File.Exists(tempfullName))
                {
                    File.Delete(tempfullName);
                }
                return(statu);
            }


            //根据文件类型保存数据库
            using (var db = new RIPPWebEntities())
            {
                if (ftype != FileExtensionEnum.Unkown)
                {
                    var user = RIPP.Web.Chem.Tools.Common.Get_User;
                    if (user == null)
                    {
                        var uid = Convert.ToInt32(context.Request["uid"]);
                        user = db.S_User.Where(d => d.ID == uid).FirstOrDefault();
                    }

                    if (ftype == FileExtensionEnum.Spec)//光谱
                    {
                        if (RIPP.Web.Chem.Tools.Common.UserCanPredict(user))
                        {
                            sp.addtime = DateTime.Now;
                            sp.ext     = Path.GetExtension(fileName).Substring(1);
                            sp.uid     = user.ID;
                            sp.gid     = user.GroupID;
                            db.spec.Add(sp);
                            db.SaveChanges();
                            statu.deleteType = "DELETE";
                            statu.deleteUrl  = "/upload/UploadHandler.ashx?t=s&id=" + sp.id;
                            statu.url        = "/admin/spec/detail/" + sp.id;
                            statu.id         = sp.id;

                            File.Move(tempfullName, Path.Combine(HttpContext.Current.Server.MapPath("~/"), sp.path));//移动刚才上传的临时文件
                        }
                        else
                        {
                            statu.error = "您无权上传光谱文件,请与管理员联系。";
                            if (File.Exists(tempfullName))
                            {
                                File.Delete(tempfullName);
                            }
                        }
                    }
                    else//模型
                    {
                        if (user.HasRole(RoleEnum.Administrator) || user.HasRole(RoleEnum.Engineer))
                        {
                            dbmodel.addtime = DateTime.Now;
                            dbmodel.type    = (int)ftype;
                            dbmodel.uid     = user.ID;
                            dbmodel.gid     = user.GroupID;
                            db.model.Add(dbmodel);
                            db.SaveChanges();
                            statu.deleteType = "DELETE";
                            statu.deleteUrl  = "/upload/UploadHandler.ashx?t=m&id=" + dbmodel.id;
                            statu.url        = "/admin/model/detail/" + dbmodel.id;
                            statu.id         = dbmodel.id;
                            File.Move(tempfullName, Path.Combine(HttpContext.Current.Server.MapPath("~/"), dbmodel.path));//移动刚才上传的临时文件
                        }
                        else
                        {
                            statu.error = "您无权上传模型文件,请与管理员联系。";
                            if (File.Exists(tempfullName))
                            {
                                File.Delete(tempfullName);
                            }
                        }
                    }
                }
            }

            return(statu);
        }
Пример #53
0
 //The DisplayColor method displays the name of a color.
 private void DisplayColor(Spectrum color)
 {
     colorLabel.Text = color.ToString();
 }
Пример #54
0
        /// <summary>
        /// Cycles through all the input callbacks
        /// This should be done once per frame
        /// </summary>
        public void PollInput()
        {
            Spectrum.InputCallbacks.Call();

            lock (this)
            {
                // parse single keyboard matrix keys
                for (var i = 0; i < KeyboardDevice.KeyboardMatrix.Length; i++)
                {
                    string key       = KeyboardDevice.KeyboardMatrix[i];
                    bool   prevState = KeyboardDevice.GetKeyStatus(key);
                    bool   currState = Spectrum._controller.IsPressed(key);

                    if (currState != prevState)
                    {
                        KeyboardDevice.SetKeyStatus(key, currState);
                    }
                }

                // non matrix keys
                foreach (string k in KeyboardDevice.NonMatrixKeys)
                {
                    if (!k.StartsWith("Key"))
                    {
                        continue;
                    }

                    bool currState = Spectrum._controller.IsPressed(k);

                    KeyboardDevice.SetKeyStatus(k, currState);
                }

                // J1
                foreach (string j in JoystickCollection[0].ButtonCollection)
                {
                    bool prevState = JoystickCollection[0].GetJoyInput(j);
                    bool currState = Spectrum._controller.IsPressed(j);

                    if (currState != prevState)
                    {
                        JoystickCollection[0].SetJoyInput(j, currState);
                    }
                }

                // J2
                foreach (string j in JoystickCollection[1].ButtonCollection)
                {
                    bool prevState = JoystickCollection[1].GetJoyInput(j);
                    bool currState = Spectrum._controller.IsPressed(j);

                    if (currState != prevState)
                    {
                        JoystickCollection[1].SetJoyInput(j, currState);
                    }
                }

                // J3
                foreach (string j in JoystickCollection[2].ButtonCollection)
                {
                    bool prevState = JoystickCollection[2].GetJoyInput(j);
                    bool currState = Spectrum._controller.IsPressed(j);

                    if (currState != prevState)
                    {
                        JoystickCollection[2].SetJoyInput(j, currState);
                    }
                }
            }

            // Tape control
            if (Spectrum._controller.IsPressed(Play))
            {
                if (!pressed_Play)
                {
                    Spectrum.OSD_FireInputMessage(Play);
                    TapeDevice.Play();
                    pressed_Play = true;
                }
            }
            else
            {
                pressed_Play = false;
            }

            if (Spectrum._controller.IsPressed(Stop))
            {
                if (!pressed_Stop)
                {
                    Spectrum.OSD_FireInputMessage(Stop);
                    TapeDevice.Stop();
                    pressed_Stop = true;
                }
            }
            else
            {
                pressed_Stop = false;
            }

            if (Spectrum._controller.IsPressed(RTZ))
            {
                if (!pressed_RTZ)
                {
                    Spectrum.OSD_FireInputMessage(RTZ);
                    TapeDevice.RTZ();
                    pressed_RTZ = true;
                }
            }
            else
            {
                pressed_RTZ = false;
            }

            if (Spectrum._controller.IsPressed(Record))
            {
            }
            if (Spectrum._controller.IsPressed(NextTape))
            {
                if (!pressed_NextTape)
                {
                    Spectrum.OSD_FireInputMessage(NextTape);
                    TapeMediaIndex++;
                    pressed_NextTape = true;
                }
            }
            else
            {
                pressed_NextTape = false;
            }

            if (Spectrum._controller.IsPressed(PrevTape))
            {
                if (!pressed_PrevTape)
                {
                    Spectrum.OSD_FireInputMessage(PrevTape);
                    TapeMediaIndex--;
                    pressed_PrevTape = true;
                }
            }
            else
            {
                pressed_PrevTape = false;
            }

            if (Spectrum._controller.IsPressed(NextBlock))
            {
                if (!pressed_NextBlock)
                {
                    Spectrum.OSD_FireInputMessage(NextBlock);
                    TapeDevice.SkipBlock(true);
                    pressed_NextBlock = true;
                }
            }
            else
            {
                pressed_NextBlock = false;
            }

            if (Spectrum._controller.IsPressed(PrevBlock))
            {
                if (!pressed_PrevBlock)
                {
                    Spectrum.OSD_FireInputMessage(PrevBlock);
                    TapeDevice.SkipBlock(false);
                    pressed_PrevBlock = true;
                }
            }
            else
            {
                pressed_PrevBlock = false;
            }

            if (Spectrum._controller.IsPressed(TapeStatus))
            {
                if (!pressed_TapeStatus)
                {
                    Spectrum.OSD_ShowTapeStatus();
                    pressed_TapeStatus = true;
                }
            }
            else
            {
                pressed_TapeStatus = false;
            }

            if (Spectrum._controller.IsPressed(HardResetStr))
            {
                if (!pressed_HardReset)
                {
                    HardReset();
                    pressed_HardReset = true;
                }
            }
            else
            {
                pressed_HardReset = false;
            }

            if (Spectrum._controller.IsPressed(SoftResetStr))
            {
                if (!pressed_SoftReset)
                {
                    SoftReset();
                    pressed_SoftReset = true;
                }
            }
            else
            {
                pressed_SoftReset = false;
            }

            // disk control
            if (Spectrum._controller.IsPressed(NextDisk))
            {
                if (!pressed_NextDisk)
                {
                    Spectrum.OSD_FireInputMessage(NextDisk);
                    DiskMediaIndex++;
                    pressed_NextDisk = true;
                }
            }
            else
            {
                pressed_NextDisk = false;
            }

            if (Spectrum._controller.IsPressed(PrevDisk))
            {
                if (!pressed_PrevDisk)
                {
                    Spectrum.OSD_FireInputMessage(PrevDisk);
                    DiskMediaIndex--;
                    pressed_PrevDisk = true;
                }
            }
            else
            {
                pressed_PrevDisk = false;
            }

            if (Spectrum._controller.IsPressed(EjectDisk))
            {
                if (!pressed_EjectDisk)
                {
                    Spectrum.OSD_FireInputMessage(EjectDisk);
                    if (UPDDiskDevice != null)
                    {
                        UPDDiskDevice.FDD_EjectDisk();
                    }
                }
            }
            else
            {
                pressed_EjectDisk = false;
            }

            if (Spectrum._controller.IsPressed(DiskStatus))
            {
                if (!pressed_DiskStatus)
                {
                    Spectrum.OSD_ShowDiskStatus();
                    pressed_DiskStatus = true;
                }
            }
            else
            {
                pressed_DiskStatus = false;
            }
        }
Пример #55
0
 public CompositeScorer(Spectrum ms2Spec, Tolerance tol, double relativeIsotopeIntensityThreshold = 0.1)
     : base(ms2Spec, tol, 1, 20, relativeIsotopeIntensityThreshold)
 {
 }
Пример #56
0
 private bool lessThan(Spectrum lhs, Spectrum rhs)
 {
     return((double)lhs.cvParam(CVID.MS_TIC).value < (double)rhs.cvParam(CVID.MS_TIC).value);
 }
Пример #57
0
 protected virtual bool IsCorrectionApplicable(Spectrum data, int index)
 {
     return(true);
 }
Пример #58
0
 // The DisplayColor method displays the
 // name of a color.
 private void DisplayColor(Spectrum color)
 {
     colorLabel.Text = color.ToString();
 }
Пример #59
0
 public abstract Spectrum Li(Scene scene, Renderer renderer, RayDifferential ray,
     Sample sample, Random rng, out Spectrum transmittance);
Пример #60
0
        public void updateRow(SpectrumDataSet.SpectrumTableRow row, MassSpectrum spectrum)
        {
            spectrumList[spectrum.Index] = spectrum;

            Spectrum                s    = spectrum.Element; //GetElement(false);
            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);
        }