public void ShouldConvertNegativeValues()
        {
            var sample = new Measurement(-0.75, "units");

            var expected = new Measurement(-75, "units");
            Assert.That(CalibratedDevice.ConvertOutput(sample, LUT.Keys.ToList(), LUT.Values.ToList()), Is.EqualTo(expected));
        }
        public void ShouldConvertKeyDirectlyToValue()
        {
            var sample = new Measurement(10, "units");

            var expected = new Measurement(200, "units");
            Assert.That(CalibratedDevice.ConvertOutput(sample, LUT.Keys.ToList(), LUT.Values.ToList()), Is.EqualTo(expected));
        }
Exemple #3
0
    void FixedUpdate()
    {
        m_pose = null;

		switch(ubitrackEvent)
		{
		case UbitrackEventType.Pull:{				
				ulong lastTimestamp =  UbiMeasurementUtils.getUbitrackTimeStamp();
				if(m_posePull.getPose(m_simplePose, lastTimestamp))
				{					
                    m_pose = UbiMeasurementUtils.ubitrackToUnity(m_simplePose);    
				}	
				break;
			}
		case UbitrackEventType.Push:{
            m_pose = m_poseReceiver.getData();
				break;
			}
		default:
		break;
		}

        if (m_pose != null)
        {
            UbiUnityUtils.setGameObjectPose(relative, gameObject, m_pose.data(), applyData);
        }
        lastPose = m_pose;
    }   
        public async Task Write_WithValidMeasurementFields_IsSuccessful()
        {
            //  Arrange
            InfluxManager mgr = new InfluxManager(_influxEndpoint, _influxDatabase);
            Measurement m = new Measurement()
            {
                Name = "unittest",
                IntegerFields = new List<IntegerField>()
                {
                    new IntegerField() { Name="count", Value=44 }
                },
                Timestamp = DateTime.Parse("10/26/2015 13:48")
            };

            //  Act
            Task<HttpResponseMessage> asyncretval = mgr.Write(m);
            Debug.WriteLine(DateTime.Now); // Log the time right after the call:

            HttpResponseMessage retval = await asyncretval; // Await the return
            Debug.WriteLine(DateTime.Now); // Log the time right after the return:

            //  Assert
            Assert.IsNotNull(retval);
            Assert.AreEqual(204, (int)retval.StatusCode);
        }
Exemple #5
0
 //--- Class Methods ---
 protected static Measurement[] Measure(string testname, Func<int> callback)
 {
     var result = new Measurement[_iterations.Length];
     for(var j = 0; j < 100; ++j) {
         callback();
     }
     for(int i = 0; i < _iterations.Length; ++i) {
         var count = _iterations [i];
         var sw = new Stopwatch();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         var memory = GC.GetTotalMemory(true);
         sw.Start();
         for(var j = 0; j < count; ++j) {
             callback();
         }
         sw.Stop();
         memory = GC.GetTotalMemory(false) - memory;
         result[i] = new Measurement(memory, sw.Elapsed);
     }
     Console.WriteLine();
     Console.WriteLine("        --- {0} ---", testname);
     for(var i = 0; i < result.Length; ++i) {
         Console.WriteLine("        #{0}: {1:#,##0} bytes, {2:#,##0.000} ms", i + 1, result[i].MemoryUsage, result[i].Duration.TotalMilliseconds);
     }
     return result;
 }
        public void UnitNames()
        {
            var meter = new Unit("meter")
                .IsAlsoCalled("metre")
                .CanBeAbbreviated("m", "mtr")
                .UsePluralFormat("{0}s");

            var feet = new Unit("foot")
                .PluralizeAs("feet")
                .CanBeAbbreviated("ft");

            var system = new ConversionGraph()
                .RoundToDecimalPlaces(5);

            system.AddConversion(Conversions.One(meter).In(feet).Is(3.28084M));

            var meterMeasurement = new Measurement(meter, 1);
            var feetMeasurement = new Measurement(feet, 2);

            var x = system.Convert(meterMeasurement, feet);

            Assert.That(system.Convert(meterMeasurement, feet) == 3.28084M);
            Assert.That(system.Convert(meterMeasurement, "ft") == 3.28084M);
            Assert.That(system.Convert(feetMeasurement, "metre") == 0.6096M);
            Assert.That(system.Convert(feetMeasurement, "mtr") == 0.6096M);
            Assert.That(system.Convert(feetMeasurement, "m") == 0.6096M);

            Assert.That(meterMeasurement.ToAbbreviatedString() == "1 m");
            Assert.That(meterMeasurement.ToString() == "1 meter");

            Assert.That(feetMeasurement.ToAbbreviatedString() == "2 ft");
            Assert.That(feetMeasurement.ToString() == "2 feet");
        }
        public void ChannelInfoShouldGiveCompleteITCChannelInfo(
            [Values((ushort)0, (ushort)1, (ushort)8)] 
            ushort channelNumber,
    [Values(StreamType.AO, StreamType.DO_PORT, StreamType.XO)] 
            StreamType streamType
            )
        {
            var controller = new HekaDAQController();
            const string name = "UNUSED_NAME";
            var s = new HekaDAQOutputStream(name,
                streamType,
                channelNumber,
                controller);

            const decimal sampleRate = 9000;
            var srate = new Measurement(sampleRate, "Hz");
            controller.SampleRate = srate;

            ITCMM.ITCChannelInfo info = s.ChannelInfo;

            Assert.AreEqual(channelNumber, info.ChannelNumber);
            Assert.AreEqual((int)streamType, info.ChannelType);
            Assert.AreEqual(s.SampleRate.QuantityInBaseUnits, info.SamplingRate);
            Assert.AreEqual(ITCMM.USE_FREQUENCY, info.SamplingIntervalFlag);
            Assert.AreEqual(0, info.Gain);
            Assert.AreEqual(IntPtr.Zero, info.FIFOPointer);
        }
 public override void receiveMatrix4x4(SimpleMatrix4x4 newMatrix)
 {
     lock (thisLock)
     {
         m_matrix = UbiMeasurementUtils.ubitrackToUnity(newMatrix);
     }
 }
Exemple #9
0
    void FixedUpdate()
    {
        m_position = null;
	
		switch(ubitrackEvent)
		{
		case UbitrackEventType.Pull:{				
				ulong lastTimestamp =  UbiMeasurementUtils.getUbitrackTimeStamp();
				if(m_positionPull.getPosition3D(m_simplePosition, lastTimestamp))
				{					
                    m_position = UbiMeasurementUtils.ubitrackToUnity(m_simplePosition);    
				}	
				break;
			}
		case UbitrackEventType.Push:{
            m_position = m_positionReceiver.getData();
				break;
			}
		default:
		break;
		}

        if (m_position != null)
        {
            UbiUnityUtils.setGameObjectPosition(relative, gameObject, m_position.data());
        }
        	
    }
 public override void receivePositionList3D(SimplePositionList3D position3dList)
 {
     lock (thisLock)
     {
         m_data = UbiMeasurementUtils.ubitrackToUnity(position3dList);
     }
 }
 public override void receivePosition3D(SimplePosition3D newPosition)
 {
     lock (thisLock)
     {			
         m_position = UbiMeasurementUtils.ubitrackToUnity(newPosition);            
     }
 }
        public void DelegatesBlocks()
        {
            var parameters = new Dictionary<string, object>();
            parameters["sampleRate"] = new Measurement(1000, "Hz");

            var s = new DelegatedStimulus("DelegatedStimulus", "units",
                                          parameters,
                                          (p, b) => new OutputData(Enumerable.Range(0, (int)(b.TotalSeconds * (double)((IMeasurement)p["sampleRate"]).QuantityInBaseUnit))
                                                                       .Select(i => new Measurement(i, "units")).ToList(),
                                                                   (IMeasurement)p["sampleRate"],
                                                                   false),
                                          (p) => Option<TimeSpan>.None());

            var block = TimeSpan.FromMilliseconds(100);
            IEnumerator<IOutputData> iter = s.DataBlocks(block).GetEnumerator();
            int n = 0;
            while (iter.MoveNext() && n < 100)
            {
                var expected =
                    new OutputData(
                        Enumerable.Range(0, (int)(block.TotalSeconds * (double)((IMeasurement)parameters["sampleRate"]).QuantityInBaseUnit))
                            .Select(i => new Measurement(i, "units")).ToList(),
                        (IMeasurement)parameters["sampleRate"],
                        false);

                Assert.That(iter.Current.Duration, Is.EqualTo(expected.Duration));
                Assert.That(iter.Current.Data, Is.EqualTo(expected.Data));
                n++;
            }
        }
        public static Animation CreateCounterExample2(Lifetime life)
        {
            var animation = new Animation();

            var state = Ani.Anon(step => {
                var t = (step.TotalSeconds * 8).SmoothCycle(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);

                var t1 = TimeSpan.Zero;
                var t2 = t.Seconds();

                var ra = new EndPoint("Robot A", skew: 0.Seconds() + t1);
                var rb = new EndPoint("Robot B", skew: 0.Seconds() + t2);

                var graph = new EndPointGraph(
                    new[] { ra, rb },
                    new Dictionary<Tuple<EndPoint, EndPoint>, TimeSpan> {
                        {Tuple.Create(ra, rb), 2.Seconds() + t2 - t1},
                        {Tuple.Create(rb, ra), 2.Seconds() + t1 - t2},
                    });

                var m1 = new Message("I think it's t=0s.", graph, ra, rb, ra.Skew + 0.Seconds());
                var m2 = new Message("Received at t=2s", graph, rb, ra, m1.ArrivalTime);

                var s1 = new Measurement("Apparent Time Mistake = 2s+2s", ra, ra, m2.ArrivalTime, m2.ArrivalTime + 4.Seconds(), 60);
                var s2 = new Measurement("Time mistake = RTT - 4s", ra, ra, m2.ArrivalTime + 4.Seconds(), m2.ArrivalTime + 4.Seconds(), 140);

                return new GraphMessages(graph, new[] { m1, m2}, new[] { s1, s2});
            });

            return CreateNetworkAnimation(animation, state, life);
        }
Exemple #14
0
        /// <summary>
        /// Prende da file i dati quando la rete non funziona
        /// </summary>
        /// <param name="percorso">Percorso e nome del file del log dei dati</param>
        public void PrendiDaFile(string percorso)
        {
            //TODO: il programma deve fare:
            // XXXX
            try
            {
                // vedere se questo codice si può riutilizzare
                using (StreamReader sr = new StreamReader(percorso))
                {
                    char[] buffer = new char[endRead];
                    sr.Read(buffer,startRead,endRead);
                    string lettura="";

                    for(int i= 0; i < buffer.Length -1; i++)
                    {
                        lettura = lettura + buffer[i];
                    }

                    string[] slitlettura = lettura.Split(' ');
                    Measurement sensore = new Measurement();

                    //DA FINIRE
                }
            }
            catch
            {
                throw new Exception();
            }
        }
        // Add a measurement to the database and collections.
        public void AddMeasurement(Measurement newMeasurement)
        {
            // Add a measurement to the data context.
            measurementDB.Measurements.InsertOnSubmit(newMeasurement);

            // Save changes to the database.
            measurementDB.SubmitChanges();

            // Add a measurement to the "all" observable collection.
            App.MainPageViewModel.AllMeasurements.Add(newMeasurement);

            // Add a measurement to the appropriate filtered collection.
            switch (newMeasurement.Type.Name)
            {
                case "Weight":
                    App.MainPageViewModel.WeightMeasurements.Add(newMeasurement);
                    break;
                case "Pulse":
                    App.MainPageViewModel.PulseMeasurements.Add(newMeasurement);
                    break;
                case "Pressure":
                    App.MainPageViewModel.PressureMeasurements.Add(newMeasurement);
                    break;
                default:
                    break;
            }
            // Save changes to the database.
            measurementDB.SubmitChanges();
        }
 public PacketMeasurement(Measurement measurement, string physicianName, string sessionType, string username)
 {
     this.measurement = measurement;
     this.physicianName = physicianName;
     this.sessionType = sessionType;
     this.username = username;
 }
        public void OneUnitDefaultName()
        {
            var meter = new Unit("meter");
            var oneMeter = new Measurement(meter, 1M);

            oneMeter.ToString().Should().Be("1 meter");
        }
        public void FrameworkPlugins_SingleContextGet()
        {
            // engine data objects (not plugin-able business logic)
            Model model = CreateModel();
            var measurement = new Measurement();
            // plugin definition (unique and parameters)
            const string commandUnique = "pluginB_single_get";
            const string commandParameters = "parameter1=P1; parameter2=P2; material1=M1; material2=M2; threshold=0.4";

            var containerFramework = new ContainerFramework();
            var dataFramework = new DataFramework(containerFramework);
            dataFramework.Add<IModelDataEntity>(new ModelDataEntity(model));
            dataFramework.Add<IMeasurementDataEntity>(new MeasurementDataEntity(measurement));

            var commandFramework = new CommandFramework(containerFramework, dataFramework);
            commandFramework.AddPluginsFolder(new DataFolder(@"..\..\..\@PluginsBinaries"));
            commandFramework.AddPluginsBinary(new DataFile(@".\EngineAPI.dll"));
            commandFramework.Init();
//            var service1 = commandFramework.FindPlugin("model_get_measurement_properties").Value as IMeasurementPropertiesService;   //TODO should be implemented automatically
//            commandFramework.RegisterService<IMeasurementPropertiesService>(service1);
//            var service2 = commandFramework.FindPlugin("get_material_properties").Value as IMaterialPropertiesService;   //TODO should be implemented automatically
//            commandFramework.RegisterService<IMaterialPropertiesService>(service2);

            IDataEntity commandResult = commandFramework.RunCommand(commandUnique, commandParameters);
            Assert.IsInstanceOf<ModelParametersDataEntity>(commandResult);
        }
Exemple #19
0
        public void GenerateReports(Measurement m)
        {
            RawAnalysisReport rep = new AnalysisDefs.RawAnalysisReport(ctrllog);
            rep.GenerateReport(m);
            ResultsReport = rep.replines;
            MethodResultsReport mrep = new AnalysisDefs.MethodResultsReport(ctrllog);
            mrep.GenerateReport(m);
            foreach (List<string> r in mrep.INCCResultsReports)
            {
                INCCResultsReports.Add(r);
            }
            if (NC.App.AppContext.CreateINCC5TestDataFile)
            { 
                TestDataFile mdat = new AnalysisDefs.TestDataFile(ctrllog);
                mdat.GenerateReport(m);
                foreach (List<string> r in mdat.INCCTestDataFiles)
                {
                    TestDataFiles.Add(r);
                }
            }

            if (NC.App.AppContext.OpenResults)
            {
                string notepadPath = System.IO.Path.Combine(Environment.SystemDirectory, "notepad.exe");
                if (System.IO.File.Exists(notepadPath))
                {
                    foreach (string fname in m.INCCResultsFileNames)
                        System.Diagnostics.Process.Start(notepadPath, fname);
                }
                // todo:optional enablement
                // Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                //Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(m.ResultsFileName);
                //excel.Visible = true;
            }
        }
 public override void receivePose(SimplePose newPose)
 {
     lock (thisLock)
     {			
         m_pose = UbiMeasurementUtils.ubitrackToUnity(newPose);            
     }
 }
        public void ShouldConstructFromInteger()
        {
            const int expected = 1;
            var m = new Measurement(expected, "V");

            Assert.That((int)m.Quantity, Is.EqualTo(expected));
        }
        public void OneUnitExplicitDisplayName()
        {
            var meter = new Unit("meter")
                .DisplayWithName("metre");
            var oneMeter = new Measurement(meter, 1M);

            oneMeter.ToString().Should().Be("1 metre");
        }
        public void ThirtyTwoDegreesFahrenheitInCelcius()
        {
            var degrees = new Measurement("Fahrenheit", 32M);

            var result = _graph.Convert(degrees, "Celcius");

            result.Should().Be(0M);
        }
 public PerformanceResult(string testCase, string serializerName, int measurementCount)
 {
     SerializeTime = new Measurement(measurementCount);
     DeserializeTime = new Measurement(measurementCount);
     TestCase = testCase;
     SerializerName = serializerName;
     MeasurementCount = measurementCount;
 }
Exemple #25
0
        public void ConvertOneMeterToMeters()
        {
            var oneMeter = new Measurement(SI.Length.Meter, 1M);

            decimal feet = _length.Convert(oneMeter, SI.Length.Meter);

            feet.Should().Be(1M);
        }
        public void ZeroDegreesCelciusInFahrenheit()
        {
            var degrees = new Measurement(new Unit("Celcius"), 0M);

            var result = _graph.Convert(degrees, "Fahrenheit");

            result.Should().Be(32M);
        }
 public void SamplesShouldRoundUp()
 {
     TimeSpan t = TimeSpan.FromMilliseconds(99.3);
     var sampleRate = new Measurement(1000, "Hz");
     Assert.That(t.Samples(sampleRate), Is.EqualTo(
         (ulong)Math.Ceiling(t.TotalSeconds * (double)sampleRate.QuantityInBaseUnit))
         );
 }
Exemple #28
0
        public void ConvertOneFootToMeters()
        {
            var oneFoot = new Measurement(US.Length.Foot, 1M);

            decimal meters = _length.Convert(oneFoot, SI.Length.Meter);

            meters.Should().Be(0.3048M);
        }
Exemple #29
0
        public void ConvertOneMeterToFeet()
        {
            var oneMeter = new Measurement(SI.Length.Meter, 1M);

            decimal feet = _length.Convert(oneMeter, US.Length.Foot);

            feet.Should().Be(3.2808M);
        }
        public void ConvertsZeroSamples()
        {
            IMeasurement m = new Measurement(723, "Hz");

            TimeSpan expected = new TimeSpan(0);

            Assert.AreEqual(expected, TimeSpanExtensions.FromSamples(0, m));
        }
Exemple #31
0
 public MeasureScope(Measurement parent, long timestamp)
 {
     this.parent    = parent;
     this.timestamp = timestamp;
 }
Exemple #32
0
 public Flow()
 {
     CalibrationSettings = new Dictionary <string, object>(GetDefaultCalibrationSettings());
     lastMeasurement     = new Measurement(0.0f, Measurement.UnitsOfMeasure.Ounces);
 }
        //Note: nipple cannot be null, but breast can. make sure to check for null on breast whenever using it.
        //note: if plural is set to true, with article is ignored. the alternate format for plural is identical to the regular format.
        private static string LongFullDesc(INipple nipple, IBreast breast, bool withArticle, bool allAvailableNipples, bool preciseMeasurements, bool full)
        {
            StringBuilder sb = new StringBuilder();

            if (full && breast?.piercings.wearingJewelry == true)
            {
                sb.Append("pierced");
            }

            if (nipple.blackNipples)
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }

                sb.Append("black");
            }

            if (nipple.lactationStatus > LactationStatus.NOT_LACTATING)
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                //creature is not null or islactating would be false.
                var lactationState = nipple.lactationStatus;
                //Light lactation
                if (lactationState < LactationStatus.MODERATE)
                {
                    sb.Append(Utils.RandomChoice("milk moistened", "slightly lactating", "milk-dampened"));
                }
                //Moderate lactation
                else if (lactationState < LactationStatus.STRONG)
                {
                    sb.Append(Utils.RandomChoice("lactating", "milky", "milk-seeping"));
                }
                //Heavy lactation
                else
                {
                    sb.Append(Utils.RandomChoice("dripping", "dribbling", "milk-leaking", "drooling"));
                }
            }
            if (nipple.status.IsInverted())
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                //else... shit. different articles.
                if (nipple.status == NippleStatus.SLIGHTLY_INVERTED)
                {
                    sb.Append("slightly-");
                }
                sb.Append("inverted");
            }

            //check if we've added any adjectives. if we have, the length is > 0. if not, try using lust. if that doesn't work, we don't have any adjectives :(.
            if (sb.Length == 0 && nipple.relativeLust > 50)
            {
                if (nipple.relativeLust >= 75)
                {
                    sb.Append(Utils.RandomChoice("throbbing", "trembling", "needy ", "throbbing "));
                }
                else
                {
                    sb.Append(Utils.RandomChoice("erect ", "perky ", "erect ", "firm ", "tender "));
                }
            }


            if (nipple.status == NippleStatus.DICK_NIPPLE)
            {
                if (nipple.quadNipples)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append("quad-tipped");
                }

                if (sb.Length > 0)
                {
                    sb.Append(" ");
                }
                sb.Append(Utils.PluralizeIf("dick-nipple", allAvailableNipples));
            }
            else if (nipple.status == NippleStatus.FUCKABLE)
            {
                if (nipple.quadNipples)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(Utils.PluralizeIf("quad-fuckable nipple", allAvailableNipples));
                }
                else
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(" ");
                    }
                    sb.Append(Utils.PluralizeIf("nipple-c**t", allAvailableNipples));
                }
            }
            else
            {
                if (sb.Length > 0)
                {
                    sb.Append(" ");
                }
                if (nipple.quadNipples)
                {
                    sb.Append("quad-");
                }
                sb.Append(Utils.PluralizeIf("nipple", allAvailableNipples));
            }

            bool needsArticle = !allAvailableNipples && withArticle;

            if (preciseMeasurements)
            {
                //...shit. eight uses an. well, i guess add article if handles that now. not a huge fan but i guess it works.
                return(Utils.AddArticleIf(Measurement.ToNearestQuarterInchOrMillimeter(nipple.length, false, false), needsArticle) + sb.ToString());
            }
            else
            {
                return(NippleSizeAdjective(nipple.length, needsArticle) + sb.ToString());
            }
        }
Exemple #34
0
 public void AddNewOrUpdateMeasurement(Measurement measurement)
 {
     DataContext.Table <Measurement>().AddNewOrUpdateRecord(measurement);
 }
        public async Task <T> ExecuteAsync <T>(Func <Task <T> > action)
        {
            var m = new Measurement();

            return(await DoExecuteAsync(GetName(action.Method.Name), m, async() => await action()));
        }
Exemple #36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="frame"></param>
        /// <param name="index"></param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            try
            {
                m_totalTimeStopwatch.Start();

                // ------------------- Refreshing the Network Model ------------------- //
                m_stopwatch.Reset();
                m_stopwatch.Start();

                // Refresh the Network Model
                m_network.Model.InputKeyValuePairs.Clear();
                m_network.Model.ClearValues();

                m_stopwatch.Stop();
                m_refreshExecutionTime = m_stopwatch.ElapsedTicks;

                // ------------------- Frame Parsing ------------------- //

                m_stopwatch.Restart();

                // Extract the raw measurements from the frame
                foreach (IMeasurement measurement in frame.Measurements.Values)
                {
                    m_network.Model.InputKeyValuePairs.Add(measurement.Key.ToString(), measurement.Value);
                }

                m_stopwatch.Stop();
                m_parsingExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // ------------------- Measurement Mapping ------------------- //

                m_stopwatch.Start();

                // Alert the Network Model that new measurements have arrived.
                m_network.Model.OnNewMeasurements();

                m_stopwatch.Stop();
                m_measurementMappingExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // ------------------- Active Current Phasor Determination ------------------- //

                m_stopwatch.Start();
                m_network.RunNetworkReconstructionCheck();
                // Locate the current phasors measurements that are active
                if (m_network.HasChangedSincePreviousFrame)
                {
                    m_network.Model.DetermineActiveCurrentFlows();
                    m_network.Model.DetermineActiveCurrentInjections();
                }


                m_stopwatch.Stop();
                m_activeCurrentPhasorDetermintationExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // ------------------- Observability Analysis ------------------- //

                m_stopwatch.Start();

                // Perform observability checks and resolve network nodes to coherent observations.

                if (m_network.HasChangedSincePreviousFrame)
                {
                    m_network.Model.ResolveToObservedBuses();
                    m_network.Model.ResolveToSingleFlowBranches();
                }

                m_stopwatch.Stop();
                m_observabilityAnalysisExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();


                // ------------------- State Computation ------------------- //

                m_stopwatch.Start();

                // Compute the current state of the system
                m_network.ComputeSystemState();

                m_stopwatch.Stop();
                m_stateComputationExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // Compute the estimated current flows from the newly computed system state
                m_network.Model.ComputeEstimatedCurrentFlows();

                // Compute the sequence values for the measured and estimated phase quantities
                if (m_network.Model.PhaseConfiguration == PhaseSelection.ThreePhase)
                {
                    m_network.Model.ComputeSequenceValues();
                }

                // ------------------- Solution Retrieval ------------------- //

                m_stopwatch.Start();

                // Get the node voltages and currents from the network
                Dictionary <string, double> rawEstimateKeyValuePairs = m_network.Model.OutputKeyValuePairs;

                m_stopwatch.Stop();
                m_solutionRetrievalExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // ------------------- Output Measurement Preparation ------------------- //

                m_stopwatch.Start();

                // Prepare to clone the output measurements
                IMeasurement[] outputMeasurements = OutputMeasurements;

                // Create a list of IMeasurement objects for the output;
                List <IMeasurement> output = new List <IMeasurement>();

                // Clone the measurements for output
                foreach (IMeasurement measurement in outputMeasurements)
                {
                    double value = 0;
                    if (rawEstimateKeyValuePairs.TryGetValue(measurement.Key.ToString(), out value))
                    {
                        output.Add(Measurement.Clone(measurement, value, frame.Timestamp));
                    }
                    else
                    {
                        output.Add(Measurement.Clone(measurement, 0, frame.Timestamp));
                    }
                }

                m_stopwatch.Stop();
                m_outputPreparationExecutionTime = m_stopwatch.ElapsedTicks;
                m_stopwatch.Reset();

                // ------------------- Publish Output Measurements ------------------- //

                // Output the newest set of state variables
                OnNewMeasurements(output);

                m_totalTimeStopwatch.Stop();
                m_totalExecutionTimeInTicks        = m_totalTimeStopwatch.ElapsedTicks;
                m_totalExecutionTimeInMilliseconds = m_totalTimeStopwatch.ElapsedMilliseconds;
                m_totalTimeStopwatch.Reset();
            }
            catch (Exception exception)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine(exception.ToString());
                if (exception.InnerException != null)
                {
                    stringBuilder.AppendLine(exception.InnerException.ToString());
                }
                else if (exception.InnerException.InnerException != null)
                {
                    stringBuilder.AppendLine(exception.InnerException.InnerException.ToString());
                }
                using (StreamWriter outfile = new StreamWriter(m_snapshotPathName + @"\Error Log " + String.Format("{0:yyyy-MM-dd  hh-mm-ss}", DateTime.UtcNow) + ".txt"))
                {
                    outfile.Write(stringBuilder.ToString());
                }
            }
        }
Exemple #37
0
        public override void OnRender(IDrawingContext drawingContext, Measurement measurement)
        {
            var image = new Image(imageData, Image);

            drawingContext.DrawImage(image, new Rectangle(measurement.Position, measurement.Size));
        }
Exemple #38
0
        private void initFunc()
        {
            Func <object> par = func;

            function = new Measurement(Singleton, par, "Function");
        }
Exemple #39
0
        private void ProcessMeasurements()
        {
            List <IMeasurement> measurements = new List <IMeasurement>((int)(Ticks.ToSeconds(GapThreshold) * m_sampleRate * m_channels * 1.1D));

            LittleBinaryValue[] sample;

            while (Enabled)
            {
                try
                {
                    SpinWait spinner = new SpinWait();

                    // Determine what time it is now
                    long now = DateTime.UtcNow.Ticks;

                    // Assign a timestamp to the next sample based on its location
                    // in the file relative to the other samples in the file
                    long timestamp = m_startTime + (m_dataIndex * Ticks.PerSecond / m_sampleRate);

                    if (now - timestamp > GapThreshold)
                    {
                        // Reset the start time and delay next transmission in an attempt to catch up
                        m_startTime = now - (m_dataIndex * Ticks.PerSecond / m_sampleRate) + Ticks.FromSeconds(RecoveryDelay);
                        timestamp   = now;
                        OnStatusMessage(MessageLevel.Info, "Start time reset.");
                    }

                    // Keep generating measurements until
                    // we catch up to the current time.
                    while (timestamp < now)
                    {
                        sample = m_dataReader.GetNextSample();

                        // If the sample is null, we've reached the end of the file - close and reopen,
                        // resetting the data index and start time
                        if (sample == null)
                        {
                            m_dataReader.Close();
                            m_dataReader.Dispose();

                            m_dataReader = OpenWaveDataReader();
                            m_dataIndex  = 0;

                            m_startTime = timestamp;
                            sample      = m_dataReader.GetNextSample();
                        }

                        // Create new measurements, one for each channel, and add them to the measurements list
                        for (int i = 0; i < m_channels; i++)
                        {
                            measurements.Add(Measurement.Clone(OutputMeasurements[i], sample[i].ConvertToType(TypeCode.Double), timestamp));
                        }

                        // Update the data index and recalculate the assigned timestamp for the next sample
                        m_dataIndex++;
                        timestamp = m_startTime + (m_dataIndex * Ticks.PerSecond / m_sampleRate);
                    }

                    OnNewMeasurements(measurements);
                    measurements.Clear();

                    while (DateTime.UtcNow.Ticks - timestamp <= GapThreshold / 100)
                    {
                        // Ahead of schedule -- pause for a moment
                        spinner.SpinOnce();
                    }
                }
                catch (Exception ex)
                {
                    OnProcessException(MessageLevel.Warning, ex);
                }
            }
        }
Exemple #40
0
 public Ammunition(Measurement <WeightUnit> weight, BallisticCoefficient ballisticCoefficient, Measurement <VelocityUnit> muzzleVelocity,
                   Measurement <DistanceUnit>?bulletDiameter = null, Measurement <DistanceUnit>?bulletLength = null)
 {
     Weight = weight;
     BallisticCoefficient = ballisticCoefficient;
     MuzzleVelocity       = muzzleVelocity;
     BulletDiameter       = bulletDiameter;
     BulletLength         = bulletLength;
 }
Exemple #41
0
 public MeasurementCalculator(Measurement measurements)
 {
     this._measurement = measurements;
     this.InitializeBoundaries();
     this._integrator = new TrapezoidalIntegratingModule();
 }
Exemple #42
0
        static void Main(string[] args)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(2)
                                 .WithDefaultEndpointPort(1883)
                                 .WithClientId("SystemMonitor");


            mqttServer = new MqttFactory().CreateMqttServer();
            mqttServer.StartAsync(optionsBuilder.Build());

            Running = true;

            publisher  = new Publisher(mqttServer);
            subscriber = new Subscriber(mqttServer);

            //var list = DeviceList.Local;
            //list.Changed += List_Changed;
            //list.RaiseChanged();

            SystemTraverser systemTraverser = new SystemTraverser();

            publisher.Register(systemTraverser);
            subscriber.Register(systemTraverser);

            Measurement cpuTemp    = systemTraverser.AllMeasurements.Where(m => m.Path.Equals("amdcpu/0/temperature/6")).FirstOrDefault();
            Measurement gpuTemp    = systemTraverser.AllMeasurements.Where(m => m.Path.Equals("gpu/0/temperature/0")).FirstOrDefault();
            Measurement liquidTemp = systemTraverser.AllMeasurements.Where(m => m.Path.Equals("nzxt/krakenx3/1A/temperature/0")).FirstOrDefault();

            Setting radiatorFans = systemTraverser.AllSettings.Where(s => s.Path.Equals("lpc/it8688e/control/0/control")).FirstOrDefault();
            Setting caseFans     = systemTraverser.AllSettings.Where(s => s.Path.Equals("lpc/it8688e/control/2/control")).FirstOrDefault();
            Setting pumpControl  = systemTraverser.AllSettings.Where(s => s.Path.Equals("nzxt/krakenx3/1A/control/0/control")).FirstOrDefault();

            Measurement[] loadStats = systemTraverser.AllMeasurements.Where(m => m.Path.StartsWith("amdcpu/0/load")).ToArray();

            var radiatorFanController = new LinearAdjuster(liquidTemp, radiatorFans)
            {
                LowerValue  = 35,
                UpperValue  = 50,
                LowerTarget = 0,
                UpperTarget = 100
            };
            var pumpController = new LinearAdjuster(cpuTemp, pumpControl)
            {
                LowerValue  = 50,
                UpperValue  = 70,
                LowerTarget = 30,
                UpperTarget = 100
            };
            var caseFanController = new LinearAdjuster(gpuTemp, caseFans)
            {
                LowerValue  = 60,
                UpperValue  = 80,
                LowerTarget = 0,
                UpperTarget = 50
            };

            // caseFans.UpdateValue(pumpController, 100.0f);
            while (Running)
            {
                /*
                 *  ColorSpace[] values = new ColorSpace[16];
                 *
                 *  int sleeptime = (int)(loadStats.Select(m => (float)m.MeasurementValue).Average() * 2);
                 *
                 *  Thread.Sleep(205 - sleeptime);
                 *
                 *  for (int i = 0; i < 8; i++)
                 *  {
                 *      //  hue = (hue + 1) % 360;
                 *
                 *      var lead_color = new Hsl { H = hue, S = 1, L = 0.7 };
                 *      var mid_color = new Hsl { H = hue, S = 1, L = 0.5 };
                 *      var trail_color = new Hsl { H = hue, S = 1, L = 0.25 };
                 *
                 *      values[(j - 1) % 8] = trail_color;
                 *      values[j] = mid_color;
                 *      values[(j + 1) % 8] = lead_color;
                 *  }
                 * // nzxtKrakenX3.RgbControl.UpdateValue(nzxtKrakenX3, values);
                 *
                 *  j = ++j % 8;
                 */
                Thread.Yield();
                //caseFans.UpdateValue(pumpController, 100.0f);
                Thread.Sleep(1000);
                // caseFans.UpdateValue(pumpController, 1.0f);
                //Thread.Sleep(1000);
            }
        }
 public static void AddNewOrUpdateMeasurement(this TableOperations <Measurement> measurementTable, Measurement measurement) =>
 measurementTable.AddNewOrUpdateRecord(measurement);
Exemple #44
0
        private static List <ExecuteResult> Execute(ILogger logger, Benchmark benchmark, IToolchain toolchain, BuildResult buildResult, IConfig config)
        {
            var executeResults = new List <ExecuteResult>();

            logger.WriteLineInfo("// *** Execute ***");
            var launchCount = Math.Max(1, benchmark.Job.LaunchCount.IsAuto ? 2 : benchmark.Job.LaunchCount.Value);

            for (int processNumber = 0; processNumber < launchCount; processNumber++)
            {
                var printedProcessNumber = (benchmark.Job.LaunchCount.IsAuto && processNumber < 2) ? "" : " / " + launchCount.ToString();
                logger.WriteLineInfo($"// Launch: {processNumber + 1}{printedProcessNumber}");

                var executeResult = toolchain.Executor.Execute(buildResult, benchmark, logger);

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError("Executable not found");
                }
                executeResults.Add(executeResult);

                var measurements = executeResults
                                   .SelectMany(r => r.Data)
                                   .Select(line => Measurement.Parse(logger, line, 0))
                                   .Where(r => r.IterationMode != IterationMode.Unknown).
                                   ToArray();

                if (!measurements.Any())
                {
                    // Something went wrong during the benchmark, don't bother doing more runs
                    logger.WriteLineError($"No more Benchmark runs will be launched as NO measurements were obtained from the previous run!");
                    break;
                }

                if (benchmark.Job.LaunchCount.IsAuto && processNumber == 1)
                {
                    var idleApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.IdleTarget).Select(m => m.Nanoseconds)).Median;
                    var mainApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.MainTarget).Select(m => m.Nanoseconds)).Median;
                    var percent    = idleApprox / mainApprox * 100;
                    launchCount = (int)Math.Round(Math.Max(2, 2 + (percent - 1) / 3)); // an empirical formula
                }
            }
            logger.WriteLine();

            // Do a "Diagnostic" run, but DISCARD the results, so that the overhead of Diagnostics doesn't skew the overall results
            if (config.GetDiagnosers().Count() > 0)
            {
                logger.WriteLineInfo($"// Run, Diagnostic");
                config.GetCompositeDiagnoser().Start(benchmark);
                var executeResult = toolchain.Executor.Execute(buildResult, benchmark, logger, config.GetCompositeDiagnoser());
                var allRuns       = executeResult.Data.Select(line => Measurement.Parse(logger, line, 0)).Where(r => r.IterationMode != IterationMode.Unknown).ToList();
                var report        = new BenchmarkReport(benchmark, null, null, new[] { executeResult }, allRuns);
                config.GetCompositeDiagnoser().Stop(benchmark, report);

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError("Executable not found");
                }
                logger.WriteLine();
            }

            return(executeResults);
        }
Exemple #45
0
        /// <summary>
        /// Calculates the average frequency for all frequencies that have reported in the specified lag time.
        /// </summary>
        /// <param name="frame">Single frame of measurement data within a one second sample.</param>
        /// <param name="index">Index of frame within the one second sample.</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            if (frame.Measurements.Count > 0)
            {
                const double hzResolution = 1000.0; // three decimal places

                double frequency;
                double frequencyTotal;
                double maximumFrequency = LoFrequency;
                double minimumFrequency = HiFrequency;
                int    adjustedFrequency;
                int    lastValue;
                int    total;

                frequencyTotal = 0.0D;
                total          = 0;

                foreach (IMeasurement measurement in frame.Measurements.Values)
                {
                    frequency         = measurement.AdjustedValue;
                    adjustedFrequency = (int)(frequency * hzResolution);

                    // Do some simple flat line avoidance...
                    if (m_lastValues.TryGetValue(measurement.ID, out lastValue))
                    {
                        if (lastValue == adjustedFrequency)
                        {
                            frequency = 0.0D;
                        }
                        else
                        {
                            m_lastValues[measurement.ID] = adjustedFrequency;
                        }
                    }
                    else
                    {
                        m_lastValues[measurement.ID] = adjustedFrequency;
                    }

                    // Validate frequency
                    if (frequency > LoFrequency && frequency < HiFrequency)
                    {
                        frequencyTotal += frequency;

                        if (frequency > maximumFrequency)
                        {
                            maximumFrequency = frequency;
                        }

                        if (frequency < minimumFrequency)
                        {
                            minimumFrequency = frequency;
                        }

                        total++;
                    }
                }

                if (total > 0)
                {
                    m_averageFrequency = (frequencyTotal / total);
                    m_maximumFrequency = maximumFrequency;
                    m_minimumFrequency = minimumFrequency;
                }

                // Provide calculated measurements for external consumption
                IMeasurement[] outputMeasurements = OutputMeasurements;

                OnNewMeasurements(new IMeasurement[] {
                    Measurement.Clone(outputMeasurements[(int)Output.Average], m_averageFrequency, frame.Timestamp),
                    Measurement.Clone(outputMeasurements[(int)Output.Maximum], m_maximumFrequency, frame.Timestamp),
                    Measurement.Clone(outputMeasurements[(int)Output.Minimum], m_minimumFrequency, frame.Timestamp)
                });
            }
            else
            {
                m_averageFrequency = 0.0D;
                m_maximumFrequency = 0.0D;
                m_minimumFrequency = 0.0D;
            }
        }
Exemple #46
0
        /// <summary>
        /// Calculates the trajectory for the specified parameters.
        /// </summary>
        /// <param name="ammunition"></param>
        /// <param name="rifle"></param>
        /// <param name="atmosphere"></param>
        /// <param name="shot"></param>
        /// <param name="wind"></param>
        /// <param name="dragTable">Custom drag table</param>
        /// <returns></returns>
        public TrajectoryPoint[] Calculate(Ammunition ammunition, Rifle rifle, Atmosphere atmosphere, ShotParameters shot, Wind[] wind = null, DragTable dragTable = null)
        {
            Measurement <DistanceUnit> rangeTo         = shot.MaximumDistance;
            Measurement <DistanceUnit> step            = shot.Step;
            Measurement <DistanceUnit> calculationStep = GetCalculationStep(step);

            atmosphere ??= new Atmosphere();

            dragTable = ValidateDragTable(ammunition, dragTable);

            Measurement <DistanceUnit> alt0 = atmosphere.Altitude;
            Measurement <DistanceUnit> altDelta = new Measurement <DistanceUnit>(1, DistanceUnit.Meter);
            double densityFactor = 0, drag;
            Measurement <VelocityUnit> mach = new Measurement <VelocityUnit>(0, VelocityUnit.MetersPerSecond);

            double stabilityCoefficient = 1;
            bool   calculateDrift;

            if (rifle.Rifling != null && ammunition.BulletDiameter != null && ammunition.BulletLength != null)
            {
                stabilityCoefficient = CalculateStabilityCoefficient(ammunition, rifle, atmosphere);
                calculateDrift       = true;
            }
            else
            {
                calculateDrift = false;
            }

            TrajectoryPoint[] trajectoryPoints = new TrajectoryPoint[(int)(Math.Floor(rangeTo / step)) + 1];

            var barrelAzimuth   = shot.BarrelAzymuth ?? new Measurement <AngularUnit>(0.0, AngularUnit.Radian);
            var barrelElevation = shot.SightAngle;

            if (shot.ShotAngle != null)
            {
                barrelElevation += shot.ShotAngle.Value;
            }

            Measurement <VelocityUnit> velocity = ammunition.MuzzleVelocity;
            TimeSpan time = new TimeSpan(0);

            int currentWind = 0;
            Measurement <DistanceUnit> nextWindRange = new Measurement <DistanceUnit>(1e7, DistanceUnit.Meter);
            Vector <VelocityUnit>      windVector;

            if (wind == null || wind.Length < 1)
            {
                windVector = new Vector <VelocityUnit>();
            }
            else
            {
                if (wind.Length > 1 && wind[0].MaximumRange != null)
                {
                    nextWindRange = wind[0].MaximumRange.Value;
                }
                windVector = WindVector(shot, wind[0], velocity.Unit);
            }

            //x - distance towards target,
            //y - drop and
            //z - windage
            var rangeVector = new Vector <DistanceUnit>(new Measurement <DistanceUnit>(0, DistanceUnit.Meter),
                                                        -rifle.Sight.SightHeight,
                                                        new Measurement <DistanceUnit>(0, DistanceUnit.Meter));

            var velocityVector = new Vector <VelocityUnit>(velocity * barrelElevation.Cos() * barrelAzimuth.Cos(),
                                                           velocity * barrelElevation.Sin(),
                                                           velocity * barrelElevation.Cos() * barrelAzimuth.Sin());

            int currentItem = 0;
            Measurement <DistanceUnit> maximumRange      = rangeTo + calculationStep;
            Measurement <DistanceUnit> nextRangeDistance = new Measurement <DistanceUnit>(0, DistanceUnit.Meter);

            Measurement <DistanceUnit> lastAtAltitude = new Measurement <DistanceUnit>(-1000000, DistanceUnit.Meter);
            DragTableNode dragTableNode = null;

            double adjustBallisticFactorForVelocityUnits = Measurement <VelocityUnit> .Convert(1, velocity.Unit, VelocityUnit.FeetPerSecond);

            double ballisicFactor    = 1 / ammunition.GetBallisticCoefficient();
            var    accumulatedFactor = PIR * adjustBallisticFactorForVelocityUnits * ballisicFactor;

            var earthGravity = (new Measurement <VelocityUnit>(Measurement <AccelerationUnit> .Convert(1, AccelerationUnit.EarthGravity, AccelerationUnit.MeterPerSecondSquare),
                                                               VelocityUnit.MetersPerSecond)).To(velocity.Unit);



            //run all the way down the range
            while (rangeVector.X <= maximumRange)
            {
                Measurement <DistanceUnit> alt = alt0 + rangeVector.Y;

                //update density and Mach velocity each 10 feet of altitude
                if (MeasurementMath.Abs(lastAtAltitude - alt) > altDelta)
                {
                    atmosphere.AtAltitude(alt, out densityFactor, out mach);
                    lastAtAltitude = alt;
                }

                if (velocity < MinimumVelocity || rangeVector.Y < -MaximumDrop)
                {
                    break;
                }

                if (rangeVector.X >= nextWindRange)
                {
                    currentWind++;
                    windVector = WindVector(shot, wind[currentWind], velocity.Unit);

                    if (currentWind == wind.Length - 1 || wind[currentWind].MaximumRange == null)
                    {
                        nextWindRange = new Measurement <DistanceUnit>(1e7, DistanceUnit.Meter);
                    }
                    else
                    {
                        nextWindRange = wind[currentWind].MaximumRange.Value;
                    }
                }

                if (rangeVector.X >= nextRangeDistance)
                {
                    var windage = rangeVector.Z;
                    if (calculateDrift)
                    {
                        windage += new Measurement <DistanceUnit>(1.25 * (stabilityCoefficient + 1.2) * Math.Pow(time.TotalSeconds, 1.83) * (rifle.Rifling.Direction == TwistDirection.Right ? 1 : -1), DistanceUnit.Inch);
                    }

                    trajectoryPoints[currentItem] = new TrajectoryPoint(
                        time: time,
                        weight: ammunition.Weight,
                        distance: rangeVector.X,
                        velocity: velocity,
                        mach: velocity / mach,
                        drop: rangeVector.Y,
                        windage: windage);
                    nextRangeDistance += step;
                    currentItem++;
                    if (currentItem == trajectoryPoints.Length)
                    {
                        break;
                    }
                }

                TimeSpan deltaTime = BallisticMath.TravelTime(calculationStep, velocityVector.X);

                var velocityAdjusted = velocityVector - windVector;
                velocity = velocityAdjusted.Magnitude;
                double currentMach = velocity / mach;

                //find Mach node for the first time
                dragTableNode ??= dragTable.Find(currentMach);

                //walk towards the beginning the table as velocity drops
                while (dragTableNode.Mach > currentMach)
                {
                    dragTableNode = dragTableNode.Previous;
                }

                drag = accumulatedFactor * densityFactor * dragTableNode.CalculateDrag(currentMach) * velocity.Value;

                velocityVector = new Vector <VelocityUnit>(
                    velocityVector.X - deltaTime.TotalSeconds * drag * velocityAdjusted.X,
                    velocityVector.Y - deltaTime.TotalSeconds * drag * velocityAdjusted.Y
                    - earthGravity * deltaTime.TotalSeconds,
                    velocityVector.Z - deltaTime.TotalSeconds * drag * velocityAdjusted.Z);

                var deltaRangeVector = new Vector <DistanceUnit>(calculationStep,
                                                                 new Measurement <DistanceUnit>(velocityVector.Y.In(VelocityUnit.MetersPerSecond) * deltaTime.TotalSeconds, DistanceUnit.Meter),
                                                                 new Measurement <DistanceUnit>(velocityVector.Z.In(VelocityUnit.MetersPerSecond) * deltaTime.TotalSeconds, DistanceUnit.Meter));

                rangeVector += deltaRangeVector;
                velocity     = velocityVector.Magnitude;
                time         = time.Add(BallisticMath.TravelTime(deltaRangeVector.Magnitude, velocity));
            }

            return(trajectoryPoints);
        }
Exemple #47
0
        /// <summary>
        /// Performs a single cycle assay operation.
        /// </summary>
        /// <param name="measurement">The measurement parameters needed for the op.</param>
        /// <param name="cancellationToken">The cancellation token to observe.</param>
        /// <exception cref="MCADeviceLostConnectionException">An error occurred communicating with the device.</exception>
        /// <exception cref="MCADeviceBadDataException">An error occurred with the raw data stream state.</exception>
        /// <exception cref="Exception">Empty or corrupt runtime data structure.</exception>
        protected void PerformAssay(Measurement measurement, MeasTrackParams mparams, CancellationToken cancellationToken)
        {
            MCA527ProcessingState ps = (MCA527ProcessingState)(RDT.State);

            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

            try
            {
                if (ps == null)
                {
                    throw new Exception("Big L bogus state");                      // caught cleanly below
                }
                if (ps.writingFile && (ps.file == null || ps.file.writer == null))
                {
                    m_logger.TraceEvent(LogLevels.Verbose, 9, "null");
                }
                ushort seq = mparams.seq;
                m_logger.TraceEvent(LogLevels.Info, 0, "MCA527[{0}]: Started assay {1}", DeviceName, seq);
                m_logger.Flush();

                cancellationToken.ThrowIfCancellationRequested();

                if (m_setvoltage)
                {
                    SetVoltage(m_voltage, MaxSetVoltageTime, cancellationToken);
                }

                cancellationToken.ThrowIfCancellationRequested();

                if (seq == 1)                  // init var on first cycle
                {
                    ps.device = m_device;
                }

                bool x = InitSettings(seq, (uint)mparams.interval);                  // truncate for discrete integer result

                Stopwatch stopwatch = new Stopwatch();
                TimeSpan  duration  = TimeSpan.FromSeconds((uint)mparams.interval);
                byte[]    buffer    = new byte[1024 * 1024];

                // a5 5a 42 00 01 00 ae d5 44 56 b9 9b
                // flags: 0x0001 => spectrum is cleared and a new start time is set
                // start time: 0x5644d5ae => seconds since Dec 31, 1969, 16:00:00 GMT
                uint        secondsSinceEpoch = (uint)(Math.Abs(Math.Round((DateTime.UtcNow - MCADevice.MCA527EpochTime).TotalSeconds)));
                MCAResponse response          = m_device.Client.Send(MCACommand.Start(StartFlag.SpectrumClearedNewStartTime,
                                                                                      false, false, false, secondsSinceEpoch));
                if (response == null)
                {
                    throw new MCADeviceLostConnectionException();
                }

                const uint CommonMemoryBlockSize = 1440;
                // what's the most that could be left over from a previous attempt to decode? => 3 bytes
                byte[]  rawBuffer        = new byte[CommonMemoryBlockSize + 3];
                ulong[] timestampsBuffer = new ulong[CommonMemoryBlockSize + 1];

                uint commonMemoryReadIndex = 0;
                uint rawBufferOffset       = 0;

                m_logger.TraceEvent(LogLevels.Verbose, 11901, "{0} start time for {1}", DateTime.Now.ToString(), seq);

                ulong    accumulatedTime = 0, totalEvents = 0;
                int      maxindex = 0;
                TimeSpan elapsed  = new TimeSpan(0);
                stopwatch.Start();
                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    QueryState527ExResponse qs527er = (QueryState527ExResponse)m_device.Client.Send(MCACommand.QueryState527Ex());
                    if (qs527er == null)
                    {
                        throw new MCADeviceLostConnectionException();
                    }

                    MCAState state = qs527er.MCAState;

                    // pull off some data while we are waiting...
                    uint commonMemoryFillLevel = qs527er.CommonMemoryFillLevel;
                    uint bytesAvailable        = commonMemoryFillLevel - commonMemoryReadIndex;

                    elapsed = stopwatch.Elapsed;                      // snapshot

                    if (state != MCAState.Run && bytesAvailable == 0) // requested time is complete
                    {
                        break;
                    }
                    if ((elapsed = stopwatch.Elapsed) > duration)                       // elapsed time is complete
                    {
                        break;
                    }
                    if (bytesAvailable >= CommonMemoryBlockSize)                       // a full data block
                    {
                        QueryCommonMemoryResponse qcmr = (QueryCommonMemoryResponse)m_device.Client.Send(MCACommand.QueryCommonMemory(commonMemoryReadIndex / 2));
                        if (qcmr == null)
                        {
                            throw new MCADeviceLostConnectionException();
                        }
                        // bytesToCopy needs to always be even, so that commonMemoryReadIndex always stays even...
                        uint bytesToCopy = Math.Min(bytesAvailable / 2, CommonMemoryBlockSize / 2) * 2;
                        qcmr.CopyData(0, rawBuffer, (int)rawBufferOffset, (int)bytesToCopy);

                        if (ps.writingFile && ps.file != null && ps.file.writer != null)                         // write the block
                        {
                            ps.file.WriteTimestampsRawDataChunk(rawBuffer, 0, (int)bytesToCopy);
                        }

                        rawBufferOffset       += bytesToCopy;
                        commonMemoryReadIndex += bytesToCopy;
                        uint timestampsCount = m_device.TransformRawData(rawBuffer, ref rawBufferOffset, timestampsBuffer);

                        // make sure rawBufferOffset is never greater than 3 after transforming data
                        // => means something has gone wrong
                        if (rawBufferOffset > 3)
                        {
                            throw new MCADeviceBadDataException();
                        }

                        // copy the data out...
                        if (timestampsCount > 0)
                        {
                            if (maxindex < RDT.State.maxValuesInBuffer)                             // accumulate
                            {
                                if (RDT.State.timeArray.Count < maxindex + timestampsCount)
                                {
                                    RDT.State.timeArray.AddRange(new ulong[timestampsCount]);
                                }
                                for (int i = 0; i < timestampsCount; i++)
                                {
                                    accumulatedTime += timestampsBuffer[i];
                                    RDT.State.timeArray[maxindex] = accumulatedTime;
                                    maxindex++;                                      // always 1 more than the last index
                                }
                                RDT.State.NumValuesParsed     += timestampsCount;
                                RDT.State.hitsPerChn[0]       += timestampsCount;
                                RDT.State.NumTotalsEncountered = RDT.State.NumValuesParsed; // only one channel
                            }
                            else                                                            // process
                            {
                                long _max = RDT.State.NumValuesParsed;
                                if (_max < RDT.State.neutronEventArray.Count)                                  // equalize the length of the empty neutron channel event list
                                {
                                    RDT.State.neutronEventArray.RemoveRange((int)_max, RDT.State.neutronEventArray.Count - (int)_max);
                                }
                                else if (_max > RDT.State.neutronEventArray.Count)
                                {
                                    RDT.State.neutronEventArray.AddRange(new uint[_max - RDT.State.neutronEventArray.Count]);
                                }
                                if (_max < RDT.State.timeArray.Count)
                                {
                                    RDT.State.timeArray.RemoveRange((int)_max, RDT.State.timeArray.Count - (int)_max);
                                }
                                else if (_max > RDT.State.timeArray.Count)
                                {
                                    RDT.State.timeArray.AddRange(new ulong[_max - RDT.State.timeArray.Count]);
                                }
                                m_logger.TraceEvent(LogLevels.Verbose, 88, "{0} {1} handling {2} timestampsCount {3} num", elapsed, duration, timestampsCount, RDT.State.NumValuesParsed);
                                RDT.PassBufferToTheCounters((int)_max);
                                maxindex = 0; totalEvents += RDT.State.NumTotalsEncountered;
                                RDT.StartNewBuffer();
                            }
                        }
                    }
                    else if (bytesAvailable > 0 && state != MCAState.Run)
                    {
                        // special case for when there's not a whole block left to read
                        // we can only read up to the address: CommonMemorySize - 1440
                        uint commonMemorySize = qs527er.CommonMemorySize;

                        uint readAddress = commonMemoryReadIndex;
                        uint readOffset  = 0;
                        if (readAddress > commonMemorySize - 1440)
                        {
                            readOffset   = readAddress - (commonMemorySize - 1440);
                            readAddress -= readOffset;
                        }

                        QueryCommonMemoryResponse qcmr = (QueryCommonMemoryResponse)m_device.Client.Send(MCACommand.QueryCommonMemory(readAddress / 2));
                        if (qcmr == null)
                        {
                            throw new MCADeviceLostConnectionException();
                        }
                        uint bytesToCopy = bytesAvailable;
                        qcmr.CopyData((int)readOffset, rawBuffer, (int)rawBufferOffset, (int)bytesToCopy);

                        if (ps.writingFile && ps.file != null && ps.file.writer != null)                         // write the block
                        {
                            ps.file.WriteTimestampsRawDataChunk(rawBuffer, (int)readOffset, (int)bytesToCopy);
                        }

                        rawBufferOffset       += bytesToCopy;
                        commonMemoryReadIndex += bytesToCopy;
                        uint timestampsCount = m_device.TransformRawData(rawBuffer, ref rawBufferOffset, timestampsBuffer);

                        //if (rawBufferOffset > 0) {
                        // apparently this can happen. Perhaps when the device gets cut off (because of a timer event), right in the middle of writing?
                        //throw new MCADeviceBadDataException();
                        // an Engineer from GBS said we are running on a very old firmware version,
                        // perhaps that has something to do with it...
                        //}
                        if (timestampsCount > 0)
                        {
                            // copy the timestampsBuffer value into the RDT.State.timeArray, Q: wait to fill a much large internal buffer before calling the transform?
                            if (maxindex < RDT.State.maxValuesInBuffer)                             // accumulate
                            {
                                if (RDT.State.timeArray.Count < maxindex + timestampsCount)
                                {
                                    RDT.State.timeArray.AddRange(new ulong[timestampsCount]);
                                }
                                for (int i = 0; i < timestampsCount; i++)
                                {
                                    accumulatedTime += timestampsBuffer[i];
                                    RDT.State.timeArray[maxindex] = accumulatedTime;
                                    maxindex++;                                      // always 1 more than the last index
                                }
                                RDT.State.NumValuesParsed     += timestampsCount;
                                RDT.State.hitsPerChn[0]       += timestampsCount;
                                RDT.State.NumTotalsEncountered = RDT.State.NumValuesParsed; // only one channel
                            }
                            else                                                            // process
                            {
                                long _max = RDT.State.NumValuesParsed;
                                if (_max < RDT.State.neutronEventArray.Count)                                  // equalize the length of the empty neutron channel event list
                                {
                                    RDT.State.neutronEventArray.RemoveRange((int)_max, RDT.State.neutronEventArray.Count - (int)_max);
                                }
                                else if (_max > RDT.State.neutronEventArray.Count)
                                {
                                    RDT.State.neutronEventArray.AddRange(new uint[_max - RDT.State.neutronEventArray.Count]);
                                }
                                if (_max < RDT.State.timeArray.Count)
                                {
                                    RDT.State.timeArray.RemoveRange((int)_max, RDT.State.timeArray.Count - (int)_max);
                                }
                                else if (_max > RDT.State.timeArray.Count)
                                {
                                    RDT.State.timeArray.AddRange(new ulong[_max - RDT.State.timeArray.Count]);
                                }
                                m_logger.TraceEvent(LogLevels.Verbose, 89, "{0} {1} handling {2} timestampsCount {3} num", elapsed, duration, timestampsCount, RDT.State.NumValuesParsed);
                                RDT.PassBufferToTheCounters((int)_max);
                                maxindex = 0; totalEvents += RDT.State.NumTotalsEncountered;
                                RDT.StartNewBuffer();
                            }
                        }
                    }
                    else
                    {
                        // give the device a break, not needed now because PassBufferToTheCounters processing takes time
                        //Thread.Sleep(40); // 100? ms
                        //m_logger.TraceEvent(LogLevels.Verbose, 99899, "{0} {1} handling {2} timestampsCount {3} num", elapsed, duration, 0, RDT.State.NumValuesParsed);
                    }
                    elapsed = stopwatch.Elapsed;          // snapshot the time after the processing and before the next query

                    if (maxindex > 0)                     // accumulated data was not completely processed above, so it happens here
                    {
                        long _max = RDT.State.NumValuesParsed;
                        if (_max < RDT.State.neutronEventArray.Count)                          // equalize the length of the empty neutron channel event list
                        {
                            RDT.State.neutronEventArray.RemoveRange((int)_max, RDT.State.neutronEventArray.Count - (int)_max);
                        }
                        else if (_max > RDT.State.neutronEventArray.Count)
                        {
                            RDT.State.neutronEventArray.AddRange(new uint[_max - RDT.State.neutronEventArray.Count]);
                        }
                        if (_max < RDT.State.timeArray.Count)
                        {
                            RDT.State.timeArray.RemoveRange((int)_max, RDT.State.timeArray.Count - (int)_max);
                        }
                        else if (_max > RDT.State.timeArray.Count)
                        {
                            RDT.State.timeArray.AddRange(new ulong[_max - RDT.State.timeArray.Count]);
                        }
                        m_logger.TraceEvent(LogLevels.Verbose, 90, "{0} {1} handling {2} num", elapsed, duration, RDT.State.NumValuesParsed);
                        RDT.PassBufferToTheCounters((int)_max);
                        maxindex = 0; totalEvents += RDT.State.NumTotalsEncountered;
                        RDT.StartNewBuffer();
                    }
                }                  // while time elapsed is less than requested time

                stopwatch.Stop();
                m_logger.TraceEvent(LogLevels.Verbose, 11901, "{0} stop time for {1}", DateTime.Now.ToString(), seq);
                m_logger.TraceEvent(LogLevels.Info, 0, "MCA527[{0}]: Finished assay; read {1} events in {2}s for {3}", DeviceName, totalEvents, stopwatch.Elapsed.TotalSeconds, seq);
                m_logger.Flush();
                RDT.Cycle.HighVoltage = m_device.GetHighVoltage();

                if (ps.writingFile)
                {
                    m_device.CreateWriteHeaderAndClose(ps.file);
                    m_logger.TraceEvent(LogLevels.Verbose, 11921, "WriteHeader for {0}", seq);
                    m_logger.Flush();
                }

                lock (m_monitor)
                {
                    m_cancellationTokenSource.Dispose();
                    m_cancellationTokenSource = null;
                }

                if (totalEvents == 0)                  // nothing to handle if no events, close up and continue
                {
                    DAQControl.HandleEndOfCycleProcessing(this, new StreamStatusBlock(@"MCA527 Done"));
                    m_logger.TraceEvent(LogLevels.Verbose, 11911, "HandleEndOfCycle for {0}", seq);
                    m_logger.Flush();
                }
            }
            catch (OperationCanceledException)
            {
                m_logger.TraceEvent(LogLevels.Warning, 767, "MCA527[{0}]: Stopping assay", DeviceName);
                m_logger.Flush();
                DAQControl.StopActiveAssayImmediately();
                throw;
            }
            catch (Exception ex)
            {
                m_logger.TraceEvent(LogLevels.Error, 0, "MCA527[{0}]: Error during assay: {1}", DeviceName, ex.Message);
                m_logger.TraceException(ex, true);
                m_logger.Flush();
                DAQControl.HandleFatalGeneralError(this, ex);
                throw;
            }
            finally
            {
            }
        }
        private string ReductoNipples(NippleStatus oldState)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("You rub the paste evenly over your " + GenericShortDescription() + ", being sure to cover them completely." + GlobalStrings.NewParagraph());
            //Shrink
            if (length < 0.3)
            {
                sb.Append("Your nipples continue to shrink down until they stop at " + Measurement.ToNearestQuarterInchOrHalfCentimeter(length, true) + " long.");
            }
            else
            {
                sb.Append("Your " + GenericShortDescription() + " get smaller and smaller, stopping when they are roughly half their previous size.");
            }

            if (oldState != nippleStatus)
            {
                if (nippleStatus == NippleStatus.NORMAL)
                {
                    sb.Append("Your " + this.source.AllBreastsLongDescription() + " tingle with warmth that slowly migrates to your nipples, " +
                              "filling them with warmth, though they don't seem to be as hard as they usually are when they get this kind of sensation. " +
                              "You begin to caress them, waiting for your mutated nipples to cum so you can be on your way. Strangely, nothing happens. " +
                              "It almost feels like your nipples are back to normal... Oh. Further prodding confirms"
                              + SafelyFormattedString.FormattedText("you've lost your dick-nipples!", StringFormats.BOLD));
                }
                else if (nippleStatus == NippleStatus.SLIGHTLY_INVERTED)
                {
                    sb.Append("Your nipples tingle, strangely stuck partway into your breasts. They crave attention, so you bring a finger to your eager nipple-holes, " +
                              "ready to finger-f**k them until they're satisfied. Strangely, your finger meets resistiance, and your prodding only forces your nipple further in." +
                              " After a few more attempts confirm this wasn't a fluke, you come to the realization " + SafelyFormattedString.FormattedText(
                                  "Your nipples are too small to be fuckable!", StringFormats.BOLD) + " Stranger still, they seem to remain stuck partially within your breasts " +
                              "when not stimulated - it seems " + SafelyFormattedString.FormattedText("your nipples are slightly inverted now instead!", StringFormats.BOLD));
                }
                else if (nippleStatus == NippleStatus.FULLY_INVERTED)
                {
                    sb.Append("Your nipples tingle, sucking further into your breasts. They tingle intensely, so you absent-mindedly run your hands across your breasts"
                              + "to rub across your senstive nubs. That's curious - you can't seem to find them - it seems as though your breasts are competely smooth. ");

                    if (this.lactationStatus > LactationStatus.NOT_LACTATING)
                    {
                        sb.Append("A trickle of milk guides you to your seemingly missing nipples, obscured by the tit-flesh surrounding them. ");
                    }
                    else
                    {
                        sb.Append(" Now that your breasts have your full attention, you quickly discover the truth - your nipples aren't gone, " +
                                  "it's just they've been surrounded by tit-flesh. ");
                    }
                    sb.Append(SafelyFormattedString.FormattedText("You're nipples are now fully inverted!", StringFormats.BOLD) + "Fortunately, you can still reach " +
                              "your nipples, and they begin to work their way out after sustained stimulation. Still, this might take some getting used to.");
                }
            }

            return(sb.ToString());
        }
Exemple #49
0
        /// <summary>
        /// Calculates the sight angle for the specified zero distance
        /// </summary>
        /// <param name="ammunition"></param>
        /// <param name="rifle"></param>
        /// <param name="atmosphere"></param>
        /// <param name="dragTable">Custom dragTable</param>
        /// <returns></returns>
        public Measurement <AngularUnit> SightAngle(Ammunition ammunition, Rifle rifle, Atmosphere atmosphere, DragTable dragTable = null)
        {
            Measurement <DistanceUnit> rangeTo         = rifle.Zero.Distance * 2;
            Measurement <DistanceUnit> step            = rifle.Zero.Distance / 100;
            Measurement <DistanceUnit> calculationStep = GetCalculationStep(step);

            dragTable = ValidateDragTable(ammunition, dragTable);

            if (rifle.Zero.Atmosphere != null)
            {
                atmosphere = rifle.Zero.Atmosphere;
            }

            atmosphere ??= new Atmosphere();

            if (rifle.Zero.Ammunition != null)
            {
                ammunition = rifle.Zero.Ammunition;
            }

            Measurement <DistanceUnit> alt0 = atmosphere.Altitude;
            Measurement <DistanceUnit> altDelta = new Measurement <DistanceUnit>(1, DistanceUnit.Meter);
            double densityFactor = 0, drag;
            Measurement <VelocityUnit> mach = new Measurement <VelocityUnit>(0, VelocityUnit.MetersPerSecond);

            var sightAngle    = new Measurement <AngularUnit>(150, AngularUnit.MOA);
            var barrelAzimuth = new Measurement <AngularUnit>(0, AngularUnit.Radian);

            for (int approximation = 0; approximation < 100; approximation++)
            {
                var barrelElevation = sightAngle;

                Measurement <VelocityUnit> velocity = ammunition.MuzzleVelocity;
                TimeSpan time = new TimeSpan(0);

                //x - distance towards target,
                //y - drop and
                //z - windage
                var rangeVector = new Vector <DistanceUnit>(new Measurement <DistanceUnit>(0, DistanceUnit.Meter),
                                                            -rifle.Sight.SightHeight,
                                                            new Measurement <DistanceUnit>(0, DistanceUnit.Meter));

                var velocityVector = new Vector <VelocityUnit>(velocity * barrelElevation.Cos() * barrelAzimuth.Cos(),
                                                               velocity * barrelElevation.Sin(),
                                                               velocity * barrelElevation.Cos() * barrelAzimuth.Sin());

                Measurement <DistanceUnit> maximumRange   = rangeTo;
                Measurement <DistanceUnit> lastAtAltitude = new Measurement <DistanceUnit>(-1000000, DistanceUnit.Meter);
                DragTableNode dragTableNode = null;

                double adjustBallisticFactorForVelocityUnits = Measurement <VelocityUnit> .Convert(1, velocity.Unit, VelocityUnit.FeetPerSecond);

                double ballisicFactor    = 1 / ammunition.GetBallisticCoefficient();
                var    accumulatedFactor = PIR * adjustBallisticFactorForVelocityUnits * ballisicFactor;

                var earthGravity = (new Measurement <VelocityUnit>(Measurement <AccelerationUnit> .Convert(1, AccelerationUnit.EarthGravity, AccelerationUnit.MeterPerSecondSquare),
                                                                   VelocityUnit.MetersPerSecond)).To(velocity.Unit);

                //run all the way down the range
                while (rangeVector.X <= maximumRange)
                {
                    Measurement <DistanceUnit> alt = alt0 + rangeVector.Y;

                    //update density and Mach velocity each 10 feet
                    if (MeasurementMath.Abs(lastAtAltitude - alt) > altDelta)
                    {
                        atmosphere.AtAltitude(alt, out densityFactor, out mach);
                        lastAtAltitude = alt;
                    }

                    if (velocity < MinimumVelocity || rangeVector.Y < -MaximumDrop)
                    {
                        break;
                    }

                    TimeSpan deltaTime = BallisticMath.TravelTime(calculationStep, velocityVector.X);

                    double currentMach = velocity / mach;

                    //find Mach node for the first time
                    dragTableNode ??= dragTable.Find(currentMach);

                    //walk towards the beginning the table as velocity drops
                    while (dragTableNode.Previous != null && dragTableNode.Previous.Mach > currentMach)
                    {
                        dragTableNode = dragTableNode.Previous;
                    }

                    drag = accumulatedFactor * densityFactor * dragTableNode.CalculateDrag(currentMach) * velocity.Value;

                    velocityVector = new Vector <VelocityUnit>(
                        velocityVector.X - deltaTime.TotalSeconds * drag * velocityVector.X,
                        velocityVector.Y - deltaTime.TotalSeconds * drag * velocityVector.Y - earthGravity * deltaTime.TotalSeconds,
                        velocityVector.Z - deltaTime.TotalSeconds * drag * velocityVector.Z);

                    var deltaRangeVector = new Vector <DistanceUnit>(calculationStep,
                                                                     new Measurement <DistanceUnit>(velocityVector.Y.In(VelocityUnit.MetersPerSecond) * deltaTime.TotalSeconds, DistanceUnit.Meter),
                                                                     new Measurement <DistanceUnit>(velocityVector.Z.In(VelocityUnit.MetersPerSecond) * deltaTime.TotalSeconds, DistanceUnit.Meter));

                    rangeVector += deltaRangeVector;

                    if (rangeVector.X >= rifle.Zero.Distance)
                    {
                        if (Math.Abs(rangeVector.Y.In(DistanceUnit.Millimeter)) < 1)
                        {
                            return(sightAngle);
                        }

                        sightAngle += new Measurement <AngularUnit>(-rangeVector.Y.In(DistanceUnit.Centimeter) / rifle.Zero.Distance.In(DistanceUnit.Meter) * 100, AngularUnit.CmPer100Meters);
                        break;
                    }

                    velocity = velocityVector.Magnitude;
                    time     = time.Add(BallisticMath.TravelTime(deltaRangeVector.Magnitude, velocity));
                }
            }
            throw new InvalidOperationException("Cannot find zero parameters");
        }
Exemple #50
0
        /// <summary>
        /// Performs a high voltage calibration operation.
        /// </summary>
        /// <param name="voltage">The voltage to set in volts.</param>
        /// <param name="duration">The length of the measurement to take.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
        /// <exception cref="OperationCanceledException">Cancellation was requested.</exception>
        /// <exception cref="MCADeviceLostConnectionException">An error occurred communicating with the device.</exception>
        private void PerformHVCalibration(Measurement measurement, int voltage, TimeSpan duration, CancellationToken cancellationToken)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            try
            {
                m_logger.TraceEvent(LogLevels.Info, 0, "MCA527[{0}]: Started HV calibration", DeviceName);
                m_logger.Flush();
                cancellationToken.ThrowIfCancellationRequested();

                uint x = SetVoltage((ushort)voltage, MaxSetVoltageTime, cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();

                HVControl.HVStatus status = new HVControl.HVStatus();
                status.HVread  = (int)m_device.GetHighVoltage();
                status.HVsetpt = voltage;

                /// begin TakeMeasurement
                measurement.Cycles.Clear();
                Cycle cycle = new Cycle(m_logger);
                cycle.UpdateDataSourceId(DetectorDefs.ConstructedSource.Live, DetectorDefs.InstrType.MCA527, DateTimeOffset.Now, string.Empty);
                measurement.Add(cycle);
                RDT.StartCycle(cycle);
                cycle.ExpectedTS = new TimeSpan(duration.Ticks);                      // expected is that requested for HV, not acquire
                ((MCA527ProcessingState)(RDT.State)).writingFile = false;             // never for HV
                measurement.AnalysisParams = new CountingAnalysisParameters();
                measurement.AnalysisParams.Add(new BaseRate());                       // prep for a single cycle
                measurement.CountTimeInSeconds   = duration.TotalSeconds;             // the requested count time
                measurement.RequestedRepetitions = measurement.CurrentRepetition = 1; // 1 rep, always set to complete
                measurement.InitializeResultsSummarizers();                           // reset data structures
                RDT.SetupCountingAnalyzerHandler(NC.App.Config, DetectorDefs.ConstructedSourceExtensions.TimeBase(DetectorDefs.ConstructedSource.Live, DetectorDefs.InstrType.MCA527));
                RDT.PrepareAndStartCountingAnalyzers(measurement.AnalysisParams);     // 1 rate counter
                m_setvoltage = false;                                                 // override DB settings here
                PerformAssay(measurement, new MeasTrackParams()
                {
                    seq = 1, interval = duration.TotalSeconds
                }, cancellationToken);
                /// end TakeMeasurement

                for (int i = 0; i < 1; i++)
                {
                    status.counts[i] = (ulong)cycle.HitsPerChannel[i];
                }

                if (m_cancellationTokenSource != null)
                {
                    lock (m_monitor)
                    {
                        m_cancellationTokenSource.Dispose();
                        m_cancellationTokenSource = null;
                    }
                }

                DAQControl.gControl.AppendHVCalibration(status);
                DAQControl.gControl.StepHVCalibration();
            }
            catch (OperationCanceledException)
            {
                m_logger.TraceEvent(LogLevels.Info, 0, "MCA527[{0}]: Stopped HV calibration", DeviceName);
                m_logger.Flush();
                DAQControl.gControl.MajorOperationCompleted();                  // causes pending control thread caller to move forward
                PendingComplete();
                //throw;
            }
            catch (Exception ex)
            {
                m_logger.TraceEvent(LogLevels.Error, 0, "MCA527[{0}]: Error during HV calibration: {1}", DeviceName, ex.Message);
                m_logger.TraceException(ex, true);
                m_logger.Flush();
                DAQControl.gControl.MajorOperationCompleted();                  // causes pending control thread caller to move forward
                PendingComplete();
                //throw;
            }
        }
        public T Execute <T>(string measurement, Func <IMeasurement, T> action)
        {
            var m = new Measurement();

            return(DoExecute(measurement, m, () => action(m)));
        }
 internal static Measurement FromApi(ApiMeasurement measurement, Installation installation)
 => Measurement.Create(CalculateCurrentDisplayValue(measurement),
                       AirlyApiMeasurementItemAdapter.FromApi(measurement.Current, MeasurementItemType.Current),
                       measurement.History.Select(history => AirlyApiMeasurementItemAdapter.FromApi(history, MeasurementItemType.History)).ToList(),
                       measurement.Forecast.Select(forecast => AirlyApiMeasurementItemAdapter.FromApi(forecast, MeasurementItemType.Forecast)).ToList(),
                       installation);
        public async Task <T> ExecuteAsync <T>(string measurement, Func <IMeasurement, Task <T> > action)
        {
            var m = new Measurement();

            return(await DoExecuteAsync(measurement, m, async() => await action(m)));
        }
Exemple #54
0
 private static void GetMeasurementsWithTypeDifference(out Measurement heartRateMeasurement, out Measurement temperatureMeasurement)
 {
     heartRateMeasurement   = new Measurement(DateTime.MaxValue, 0d, MeasurementType.HeartRate);
     temperatureMeasurement = new Measurement(DateTime.MaxValue, 0d, MeasurementType.Temperature);
 }
Exemple #55
0
 private static void GetMeasurementsWithTimeDifference(out Measurement earlierMeasurement, out Measurement laterMeasurement)
 {
     earlierMeasurement = new Measurement(DateTime.MinValue, 0d, MeasurementType.HeartRate);
     laterMeasurement   = new Measurement(DateTime.MaxValue, 0d, MeasurementType.HeartRate);
 }
Exemple #56
0
        static void Main(string[] args)
        {
            Console.WriteLine("You are runnning the Measurements example.");
            Console.WriteLine("==========================================");
            Console.WriteLine();

            #region Specific Measurement Type Examples

            #region Angle

            Angle <double> angle1 = (90, Degrees);
            Angle <double> angle2 = (0.5, Revolutions);

            Console.WriteLine("  Angle--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    angle1 = " + angle1);
            Console.WriteLine("    angle2 = " + angle2);
            Console.WriteLine("    angle1 + angle2 = " + (angle1 + angle2));
            Console.WriteLine("    angle2 - angle1 = " + (angle2 - angle1));
            Console.WriteLine("    angle1 * 2 = " + (angle1 * 2));
            Console.WriteLine("    angle1 / 2 = " + (angle1 / 2));
            Console.WriteLine("    angle1 > angle2 = " + (angle1 > angle2));
            Console.WriteLine("    angle1 == angle2 = " + (angle1 == angle2));
            Console.WriteLine("    angle1 * 2 == angle2 = " + (angle1 * 2 == angle2));
            Console.WriteLine("    angle1 != angle2 = " + (angle1 != angle2));
            Console.WriteLine();

            #endregion

            #region Length

            Length <double> length1 = (1d, Meters);
            Length <double> length2 = (2d, Yards);

            Console.WriteLine("  Length--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    length1 = " + length1);
            Console.WriteLine("    length2 = " + length2);
            Console.WriteLine("    length1 + length2 = " + (length1 + length2));
            Console.WriteLine("    length2 - length1 = " + (length2 - length1));
            Console.WriteLine("    length1 * 2 = " + (length1 * 2));
            Console.WriteLine("    length1 / 2 = " + (length1 / 2));
            Console.WriteLine("    length1 > length2 = " + (length1 > length2));
            Console.WriteLine("    length1 == length2 = " + (length1 == length2));
            Console.WriteLine("    length1 * 2 == length2 = " + (length1 * 2 == length2));
            Console.WriteLine("    length1 != length2 = " + (length1 != length2));
            Console.WriteLine();

            //object result = angle1 + length1; // WILL NOT COMPILE (this is a good thing) :)

            #endregion

            #region Mass

            Mass <double> mass1 = (1d, Grams);
            Mass <double> mass2 = (2d, Kilograms);

            Console.WriteLine("  Mass--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    mass1 = " + mass1);
            Console.WriteLine("    mass2 = " + mass2);
            Console.WriteLine("    mass1 + mass2 = " + (mass1 + mass2));
            Console.WriteLine("    mass2 - mass1 = " + (mass2 - mass1));
            Console.WriteLine("    mass1 * 2 = " + (mass1 * 2));
            Console.WriteLine("    mass1 / 2 = " + (mass1 / 2));
            Console.WriteLine("    mass1 > mass2 = " + (mass1 > mass2));
            Console.WriteLine("    mass1 == mass2 = " + (mass1 == mass2));
            Console.WriteLine("    mass1 * 2 == mass2 = " + (mass1 * 2 == mass2));
            Console.WriteLine("    mass1 != mass2 = " + (mass1 != mass2));
            Console.WriteLine();

            #endregion

            #region Time

            Time <double> time1 = (1d, Seconds);
            Time <double> time2 = (2d, Minutes);

            Console.WriteLine("  Time--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    time1 = " + time1);
            Console.WriteLine("    time2 = " + time2);
            Console.WriteLine("    time1 + time2 = " + (time1 + time2));
            Console.WriteLine("    time2 - time1 = " + (time2 - time1));
            Console.WriteLine("    time1 * 2 = " + (time1 * 2));
            Console.WriteLine("    time1 / 2 = " + (time1 / 2));
            Console.WriteLine("    time1 > time2 = " + (time1 > time2));
            Console.WriteLine("    time1 == time2 = " + (time1 == time2));
            Console.WriteLine("    time1 * 2 == time2 = " + (time1 * 2 == time2));
            Console.WriteLine("    time1 != time2 = " + (time1 != time2));
            Console.WriteLine();

            #endregion

            #region Area

            Area <double> area1 = (1d, Meters *Meters);
            Area <double> area2 = (2d, Yards *Yards);

            Console.WriteLine("  Area--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    area1 = " + area1);
            Console.WriteLine("    area2 = " + area2);
            Console.WriteLine("    area1 + area2 = " + (area1 + area2));
            Console.WriteLine("    area2 - area1 = " + (area2 - area1));
            Console.WriteLine("    area1 * 2 = " + (area1 * 2));
            Console.WriteLine("    area1 / 2 = " + (area1 / 2));
            Console.WriteLine("    area1 > area2 = " + (area1 > area2));
            Console.WriteLine("    area1 == area2 = " + (area1 == area2));
            Console.WriteLine("    area1 * 2 == area2 = " + (area1 * 2 == area2));
            Console.WriteLine("    area1 != area2 = " + (area1 != area2));
            Console.WriteLine();

            #endregion

            #region Volume

            Volume <double> volume1 = (1d, Meters *Meters *Meters);
            Volume <double> volume2 = (2d, Yards *Yards *Yards);

            Console.WriteLine("  Volume--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    volume1 = " + volume1);
            Console.WriteLine("    volume2 = " + volume2);
            Console.WriteLine("    volume1 + volume2 = " + (volume1 + volume2));
            Console.WriteLine("    volume2 - volume1 = " + (volume2 - volume1));
            Console.WriteLine("    volume1 * 2 = " + (volume1 * 2));
            Console.WriteLine("    volume1 / 2 = " + (volume1 / 2));
            Console.WriteLine("    volume1 > volume2 = " + (volume1 > volume2));
            Console.WriteLine("    volume1 == volume2 = " + (volume1 == volume2));
            Console.WriteLine("    volume1 * 2 == volume2 = " + (volume1 * 2 == volume2));
            Console.WriteLine("    volume1 != volume2 = " + (volume1 != volume2));
            Area <double> area3 = volume1 / length1;
            Console.WriteLine("    volume1 / length1 = " + area3);
            Console.WriteLine();

            #endregion

            #region Speed

            Speed <double> speed1 = (1d, Meters / Seconds);
            Speed <double> speed2 = (2d, Inches / Milliseconds);

            Console.WriteLine("  Speed--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    speed1 = " + speed1);
            Console.WriteLine("    speed2 = " + speed2);
            Console.WriteLine("    speed1 + speed2 = " + (speed1 + speed2));
            Console.WriteLine("    speed2 - speed1 = " + (speed2 - speed1));
            Console.WriteLine("    speed1 * 2 = " + (speed1 * 2));
            Console.WriteLine("    speed1 / 2 = " + (speed1 / 2));
            Console.WriteLine("    speed1 > speed2 = " + (speed1 > speed2));
            Console.WriteLine("    speed1 == speed2 = " + (speed1 == speed2));
            Console.WriteLine("    speed1 * 2 == speed2 = " + (speed1 * 2 == speed2));
            Console.WriteLine("    speed1 != speed2 = " + (speed1 != speed2));
            Console.WriteLine("    speed1 * time2 = " + (speed1 * time2));
            Speed <double> speed3 = (6d, Knots);
            Console.WriteLine("    speed3 = " + speed3);
            Console.WriteLine("    speed1 + speed3 = " + (speed1 + speed3));
            Console.WriteLine();

            #endregion

            #region Acceleration

            Acceleration <double> acceleration1 = (5d, Meters / Seconds / Seconds);
            Acceleration <double> acceleration2 = (4d, Inches / Milliseconds / Milliseconds);

            Console.WriteLine("  Acceleration--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    acceleration1 = " + acceleration1);
            Console.WriteLine("    acceleration2 = " + acceleration2);
            Console.WriteLine("    acceleration1 + acceleration2 = " + (acceleration1 + acceleration2));
            Console.WriteLine("    acceleration2 - acceleration1 = " + (acceleration2 - acceleration1));
            Console.WriteLine("    acceleration1 * 2 = " + (acceleration1 * 2));
            Console.WriteLine("    acceleration1 / 2 = " + (acceleration1 / 2));
            Console.WriteLine("    acceleration1 > acceleration2 = " + (acceleration1 > acceleration2));
            Console.WriteLine("    acceleration1 == acceleration2 = " + (acceleration1 == acceleration2));
            Console.WriteLine("    acceleration1 * 2 == acceleration2 = " + (acceleration1 * 2 == acceleration2));
            Console.WriteLine("    acceleration1 != acceleration2 = " + (acceleration1 != acceleration2));
            Console.WriteLine("    acceleration1 * time2 = " + (acceleration1 * time2));
            Console.WriteLine();

            #endregion

            #region Force

            Force <double> force1 = (1d, Kilograms *Meters / Seconds / Seconds);
            Force <double> force2 = (2d, Newtons);

            Console.WriteLine("  Force--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    force1 = " + force1);
            Console.WriteLine("    force2 = " + force2);
            Console.WriteLine("    force1 + force2 = " + (force1 + force2));
            Console.WriteLine("    force2 - force1 = " + (force2 - force1));
            Console.WriteLine("    force1 * 2 = " + (force1 * 2));
            Console.WriteLine("    force1 / 2 = " + (force1 / 2));
            Console.WriteLine("    force1 > force2 = " + (force1 > force2));
            Console.WriteLine("    force1 == force2 = " + (force1 == force2));
            Console.WriteLine("    force1 * 2 == force2 = " + (force1 * 2 == force2));
            Console.WriteLine("    force1 != force2 = " + (force1 != force2));
            Console.WriteLine();

            #endregion

            #region Electric Current

            ElectricCurrent <double> electricCurrent1 = (5d, Coulombs / Seconds);
            ElectricCurrent <double> electricCurrent2 = (4d, Amperes);

            Console.WriteLine("  ElectricCurrent--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    electricCurrent1 = " + electricCurrent1);
            Console.WriteLine("    electricCurrent2 = " + electricCurrent2);
            Console.WriteLine("    electricCurrent1 + electricCurrent2 = " + (electricCurrent1 + electricCurrent2));
            Console.WriteLine("    acceleration2 - electricCurrent1 = " + (electricCurrent2 - electricCurrent1));
            Console.WriteLine("    electricCurrent1 * 2 = " + (electricCurrent1 * 2));
            Console.WriteLine("    electricCurrent1 / 2 = " + (electricCurrent1 / 2));
            Console.WriteLine("    electricCurrent1 > electricCurrent2 = " + (electricCurrent1 > electricCurrent2));
            Console.WriteLine("    electricCurrent1 == electricCurrent2 = " + (electricCurrent1 == electricCurrent2));
            Console.WriteLine("    electricCurrent1 * 2 == electricCurrent2 = " + (electricCurrent1 * 2 == electricCurrent2));
            Console.WriteLine("    electricCurrent1 != electricCurrent2 = " + (electricCurrent1 != electricCurrent2));
            Console.WriteLine();

            #endregion

            #region AngularSpeed

            AngularSpeed <double> angularSpeed1 = (10d, Radians / Seconds);
            AngularSpeed <double> angularSpeed2 = (2200d, Degrees / Milliseconds);

            Console.WriteLine("  AngularSpeed--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    angularSpeed1 = " + angularSpeed1);
            Console.WriteLine("    angularSpeed2 = " + angularSpeed2);
            Console.WriteLine("    angularSpeed1 + angularSpeed2 = " + (angularSpeed1 + angularSpeed2));
            Console.WriteLine("    angularSpeed2 - angularSpeed1 = " + (angularSpeed2 - angularSpeed1));
            Console.WriteLine("    angularSpeed1 * 2 = " + (angularSpeed1 * 2));
            Console.WriteLine("    angularSpeed1 / 2 = " + (angularSpeed1 / 2));
            Console.WriteLine("    angularSpeed1 > angularSpeed2 = " + (angularSpeed1 > angularSpeed2));
            Console.WriteLine("    angularSpeed1 == angularSpeed2 = " + (angularSpeed1 == angularSpeed2));
            Console.WriteLine("    angularSpeed1 * 2 == angularSpeed2 = " + (angularSpeed1 * 2 == angularSpeed2));
            Console.WriteLine("    angularSpeed1 != angularSpeed2 = " + (angularSpeed1 != angularSpeed2));
            Console.WriteLine("    angularSpeed1 * time2 = " + (angularSpeed1 * time2));
            Console.WriteLine();

            #endregion

            #region AngularAcceleration

            AngularAcceleration <double> angularAcceleration1 = (5000d, Radians / Seconds / Seconds);
            AngularAcceleration <double> angularAcceleration2 = (.4d, Degrees / Milliseconds / Milliseconds);

            Console.WriteLine("  AngularAcceleration--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    angularAcceleration1 = " + angularAcceleration1);
            Console.WriteLine("    angularAcceleration2 = " + angularAcceleration2);
            Console.WriteLine("    angularAcceleration1 + angularAcceleration2 = " + (angularAcceleration1 + angularAcceleration2));
            Console.WriteLine("    angularAcceleration2 - angularAcceleration1 = " + (angularAcceleration2 - angularAcceleration1));
            Console.WriteLine("    angularAcceleration1 * 2 = " + (angularAcceleration1 * 2));
            Console.WriteLine("    angularAcceleration1 / 2 = " + (angularAcceleration1 / 2));
            Console.WriteLine("    angularAcceleration1 > angularAcceleration2 = " + (angularAcceleration1 > angularAcceleration2));
            Console.WriteLine("    angularAcceleration1 == angularAcceleration2 = " + (angularAcceleration1 == angularAcceleration2));
            Console.WriteLine("    angularAcceleration1 * 2 == angularAcceleration2 = " + (angularAcceleration1 * 2 == angularAcceleration2));
            Console.WriteLine("    angularAcceleration1 != angularAcceleration2 = " + (angularAcceleration1 != angularAcceleration2));
            Console.WriteLine("    angularAcceleration1 * time2 = " + (angularAcceleration1 * time2));
            Console.WriteLine();

            #endregion

            #region Desnity

            Density <double> density1 = (5d, Kilograms / Meters / Meters / Meters);
            Density <double> density2 = (2000d, Grams / Meters / Meters / Meters);

            Console.WriteLine("  Density--------------------------------------");
            Console.WriteLine();
            Console.WriteLine("    density1 = " + density1);
            Console.WriteLine("    density2 = " + density2);
            Console.WriteLine("    density1 + density2 = " + (density1 + density2));
            Console.WriteLine("    density2 - density1 = " + (density2 - density1));
            Console.WriteLine("    density1 * 2 = " + (density1 * 2));
            Console.WriteLine("    density1 / 2 = " + (density1 / 2));
            Console.WriteLine("    density1 > density2 = " + (density1 > density2));
            Console.WriteLine("    density1 == density2 = " + (density1 == density2));
            Console.WriteLine("    density1 * 2 == density2 = " + (density1 * 2 == density2));
            Console.WriteLine("    density1 != density2 = " + (density1 != density2));
            Console.WriteLine();

            #endregion

            #endregion

            #region Static Unit Conversion Methods
            {
                // Examples of static measurement unit conversion methods

                // Note: I strongly recommend using the measurement types
                // versus just the conversion methods if you have the
                // ability to do so. You don't have type-safeness with
                // further operations you do with these values.

                double result1 = Measurement.Convert(7d,
                                                     Radians,  // from
                                                     Degrees); // to

                double result2 = Measurement.Convert(8d,
                                                     Meters / Seconds, // from
                                                     Miles / Hours);   // to

                double result3 = Measurement.Convert(9d,
                                                     Kilograms * Meters / Seconds / Seconds, // from
                                                     Grams * Miles / Hours / Hours);         // to
            }
            #endregion

            #region Syntax Sugar Example (removing the generic type via alias)

            // If you hate seeing the "<float>" or "<double>" you can add syntax
            // sugar to your files with an alias in C#:
            //
            // using Speedf = Towel.Measurements.Speed<float>;

            Speedf speedf = (1f, Meters / Seconds);

            #endregion

            #region Vectors Examples

            // You can use measurements inside Vectors in Towel.

            Vector <Speed <float> > velocity1 = new Vector <Speed <float> >(
                (1f, Meters / Seconds),
                (2f, Meters / Seconds),
                (3f, Meters / Seconds));

            Vector <Speedf> velocity2 = new Vector <Speedf>(
                (.1f, Centimeters / Seconds),
                (.2f, Centimeters / Seconds),
                (.3f, Centimeters / Seconds));

            Vector <Speed <float> > velocity3 = velocity1 + velocity2;

            #endregion

            #region Parsing

            string angle1String = angle1.ToString();
            Angle <double> .TryParse(angle1String, out Angle <double> angle1Parsed);

            string length1String = length1.ToString();
            Length <double> .TryParse(length1String, out Length <double> length1Parsed);

            string density1String = density1.ToString();
            Density <double> .TryParse(density1String, out Density <double> density1Parsed);

            string speedString = "20.5 Meters / Seconds";
            Speed <float> .TryParse(speedString, out Speed <float> parsedSpeed);

            string forceString = ".1234 Kilograms * Meters / Seconds / Seconds";
            Force <decimal> .TryParse(forceString, out Force <decimal> parsedForce);

            string densityString = "12.344 Kilograms / Centimeters / Centimeters / Centimeters";
            Density <double> .TryParse(densityString, out Density <double> parsedDensity);

            #endregion

            Console.WriteLine();
            Console.WriteLine("=================================================");
            Console.WriteLine("Example Complete...");
            Console.ReadLine();
        }
Exemple #57
0
 private static void GetMeasurementsWithValueDifference(out Measurement lowerMeasurement, out Measurement higherMeasurement)
 {
     lowerMeasurement  = new Measurement(DateTime.MaxValue, 0d, MeasurementType.HeartRate);
     higherMeasurement = new Measurement(DateTime.MaxValue, 1d, MeasurementType.HeartRate);
 }
Exemple #58
0
        private static List <ExecuteResult> Execute(ILogger logger, Benchmark benchmark, IToolchain toolchain, BuildResult buildResult, IConfig config, IResolver resolver, out GcStats gcStats)
        {
            var executeResults = new List <ExecuteResult>();

            gcStats = default(GcStats);

            logger.WriteLineInfo("// *** Execute ***");
            bool analyzeRunToRunVariance = benchmark.Job.ResolveValue(AccuracyMode.AnalyzeLaunchVarianceCharacteristic, resolver);
            bool autoLaunchCount         = !benchmark.Job.HasValue(RunMode.LaunchCountCharacteristic);
            int  defaultValue            = analyzeRunToRunVariance ? 2 : 1;
            int  launchCount             = Math.Max(
                1,
                autoLaunchCount ? defaultValue : benchmark.Job.Run.LaunchCount);

            for (int launchIndex = 0; launchIndex < launchCount; launchIndex++)
            {
                string printedLaunchCount = (analyzeRunToRunVariance &&
                                             autoLaunchCount &&
                                             launchIndex < 2)
                    ? ""
                    : " / " + launchCount;
                logger.WriteLineInfo($"// Launch: {launchIndex + 1}{printedLaunchCount}");

                var executeResult = toolchain.Executor.Execute(
                    new ExecuteParameters(buildResult, benchmark, logger, resolver, config));

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError($"Executable {buildResult.ArtifactsPaths.ExecutablePath} not found");
                }
                if (executeResult.ExitCode != 0)
                {
                    logger.WriteLineError("ExitCode != 0");
                }
                executeResults.Add(executeResult);

                var measurements = executeResults
                                   .SelectMany(r => r.Data)
                                   .Select(line => Measurement.Parse(logger, line, 0))
                                   .Where(r => r.IterationMode != IterationMode.Unknown).
                                   ToArray();

                if (!measurements.Any())
                {
                    // Something went wrong during the benchmark, don't bother doing more runs
                    logger.WriteLineError("No more Benchmark runs will be launched as NO measurements were obtained from the previous run!");
                    break;
                }

                if (autoLaunchCount && launchIndex == 1 && analyzeRunToRunVariance)
                {
                    // TODO: improve this logic
                    var idleApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.IdleTarget).Select(m => m.Nanoseconds)).Median;
                    var mainApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.MainTarget).Select(m => m.Nanoseconds)).Median;
                    var percent    = idleApprox / mainApprox * 100;
                    launchCount = (int)Math.Round(Math.Max(2, 2 + (percent - 1) / 3)); // an empirical formula
                }
            }
            logger.WriteLine();

            // Do a "Diagnostic" run, but DISCARD the results, so that the overhead of Diagnostics doesn't skew the overall results
            if (config.GetDiagnosers().Any(diagnoser => diagnoser.GetRunMode(benchmark) == Diagnosers.RunMode.ExtraRun))
            {
                logger.WriteLineInfo("// Run, Diagnostic");
                var compositeDiagnoser = config.GetCompositeDiagnoser(benchmark, Diagnosers.RunMode.ExtraRun);

                var executeResult = toolchain.Executor.Execute(
                    new ExecuteParameters(buildResult, benchmark, logger, resolver, config, compositeDiagnoser));

                var allRuns = executeResult.Data.Select(line => Measurement.Parse(logger, line, 0)).Where(r => r.IterationMode != IterationMode.Unknown).ToList();
                gcStats = GcStats.Parse(executeResult.Data.Last());
                var report = new BenchmarkReport(benchmark, null, null, new[] { executeResult }, allRuns, gcStats);
                compositeDiagnoser.ProcessResults(benchmark, report);

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError("Executable not found");
                }
                logger.WriteLine();
            }

            foreach (var diagnoser in config.GetDiagnosers().Where(diagnoser => diagnoser.GetRunMode(benchmark) == Diagnosers.RunMode.SeparateLogic))
            {
                logger.WriteLineInfo("// Run, Diagnostic [SeparateLogic]");

                diagnoser.ProcessResults(benchmark, null);
            }

            return(executeResults);
        }
Exemple #59
0
 public MeasurementCalculator(Measurement measurements, IIntegratingModule integrator)
 {
     this._measurement = measurements;
     this.initializeBoundaries();
     this._integrator = integrator;
 }
 private static string DemonPlayerStr(Horns horns, PlayerBase player)
 {
     if (horns.numHorns <= 2)
     {
         return(" A small pair of pointed horns has broken through the " + player.face.facialSkin.LongDescription() + " on your forehead, " +
                "proclaiming some demonic taint to any who see them.");
     }
     else if (horns.numHorns <= 4)
     {
         return(" A quartet of prominent horns has broken through your " + player.face.facialSkin.LongDescription() + ". The back pair are longer, " +
                "and curve back along your head. The front pair protrude forward demonically.");
     }
     else if (horns.numHorns <= 6)
     {
         return(" Six horns have sprouted through your " + player.face.facialSkin.LongDescription() + ", the back two pairs curve backwards over your head " +
                "and down towards your neck, while the front two horns stand almost " + Measurement.ToNearestSmallUnit(horns.significantHornSize, false, true) + " " +
                "long upwards and a little forward.");
     }
     else             //if (horns.numHorns >= 8)
     {
         return(" A large number of thick demonic horns sprout through your " + player.face.facialSkin.LongDescription() + ", each pair sprouting behind the ones before. " +
                "The front jut forwards nearly " + Measurement.ToNearestSmallUnit(horns.significantHornSize, false, true) + " while the rest curve back over your head, " +
                "some of the points ending just below your ears. You estimate you have a total of " + Utils.NumberAsText(horns.numHorns) + " horns.");
     }
 }