public static string GetAbbreviation(PowerUnit unit, [CanBeNull] string cultureName)
        {
            // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx
            IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName);

            return(UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit));
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Dynamically convert from value and unit enum <see cref="PowerUnit" /> to <see cref="Power" />.
        /// </summary>
        /// <param name="value">Value to convert from.</param>
        /// <param name="fromUnit">Unit to convert from.</param>
        /// <returns>Power unit value.</returns>
        public static Power?From(double?value, PowerUnit fromUnit)
        {
            if (!value.HasValue)
            {
                return(null);
            }
            switch (fromUnit)
            {
            case PowerUnit.BoilerHorsepower:
                return(FromBoilerHorsepower(value.Value));

            case PowerUnit.ElectricalHorsepower:
                return(FromElectricalHorsepower(value.Value));

            case PowerUnit.Femtowatt:
                return(FromFemtowatts(value.Value));

            case PowerUnit.Gigawatt:
                return(FromGigawatts(value.Value));

            case PowerUnit.HydraulicHorsepower:
                return(FromHydraulicHorsepower(value.Value));

            case PowerUnit.Kilowatt:
                return(FromKilowatts(value.Value));

            case PowerUnit.MechanicalHorsepower:
                return(FromMechanicalHorsepower(value.Value));

            case PowerUnit.Megawatt:
                return(FromMegawatts(value.Value));

            case PowerUnit.MetricHorsepower:
                return(FromMetricHorsepower(value.Value));

            case PowerUnit.Microwatt:
                return(FromMicrowatts(value.Value));

            case PowerUnit.Milliwatt:
                return(FromMilliwatts(value.Value));

            case PowerUnit.Nanowatt:
                return(FromNanowatts(value.Value));

            case PowerUnit.Petawatt:
                return(FromPetawatts(value.Value));

            case PowerUnit.Picowatt:
                return(FromPicowatts(value.Value));

            case PowerUnit.Terawatt:
                return(FromTerawatts(value.Value));

            case PowerUnit.Watt:
                return(FromWatts(value.Value));

            default:
                throw new NotImplementedException("fromUnit: " + fromUnit);
            }
        }
Exemplo n.º 3
0
// ReSharper restore VirtualMemberNeverOverriden.Global

        protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(PowerUnit unit)
        {
            return(unit switch
            {
                PowerUnit.BoilerHorsepower => (BoilerHorsepowerInOneWatt, BoilerHorsepowerTolerance),
                PowerUnit.BritishThermalUnitPerHour => (BritishThermalUnitsPerHourInOneWatt, BritishThermalUnitsPerHourTolerance),
                PowerUnit.Decawatt => (DecawattsInOneWatt, DecawattsTolerance),
                PowerUnit.Deciwatt => (DeciwattsInOneWatt, DeciwattsTolerance),
                PowerUnit.ElectricalHorsepower => (ElectricalHorsepowerInOneWatt, ElectricalHorsepowerTolerance),
                PowerUnit.Femtowatt => (FemtowattsInOneWatt, FemtowattsTolerance),
                PowerUnit.GigajoulePerHour => (GigajoulesPerHourInOneWatt, GigajoulesPerHourTolerance),
                PowerUnit.Gigawatt => (GigawattsInOneWatt, GigawattsTolerance),
                PowerUnit.HydraulicHorsepower => (HydraulicHorsepowerInOneWatt, HydraulicHorsepowerTolerance),
                PowerUnit.JoulePerHour => (JoulesPerHourInOneWatt, JoulesPerHourTolerance),
                PowerUnit.KilobritishThermalUnitPerHour => (KilobritishThermalUnitsPerHourInOneWatt, KilobritishThermalUnitsPerHourTolerance),
                PowerUnit.KilojoulePerHour => (KilojoulesPerHourInOneWatt, KilojoulesPerHourTolerance),
                PowerUnit.Kilowatt => (KilowattsInOneWatt, KilowattsTolerance),
                PowerUnit.MechanicalHorsepower => (MechanicalHorsepowerInOneWatt, MechanicalHorsepowerTolerance),
                PowerUnit.MegajoulePerHour => (MegajoulesPerHourInOneWatt, MegajoulesPerHourTolerance),
                PowerUnit.Megawatt => (MegawattsInOneWatt, MegawattsTolerance),
                PowerUnit.MetricHorsepower => (MetricHorsepowerInOneWatt, MetricHorsepowerTolerance),
                PowerUnit.Microwatt => (MicrowattsInOneWatt, MicrowattsTolerance),
                PowerUnit.MillijoulePerHour => (MillijoulesPerHourInOneWatt, MillijoulesPerHourTolerance),
                PowerUnit.Milliwatt => (MilliwattsInOneWatt, MilliwattsTolerance),
                PowerUnit.Nanowatt => (NanowattsInOneWatt, NanowattsTolerance),
                PowerUnit.Petawatt => (PetawattsInOneWatt, PetawattsTolerance),
                PowerUnit.Picowatt => (PicowattsInOneWatt, PicowattsTolerance),
                PowerUnit.Terawatt => (TerawattsInOneWatt, TerawattsTolerance),
                PowerUnit.Watt => (WattsInOneWatt, WattsTolerance),
                _ => throw new NotSupportedException()
            });
Exemplo n.º 4
0
Arquivo: Power.cs Projeto: sotaria/gsf
        /// <summary>
        /// Converts the <paramref name="value"/> in the specified <paramref name="sourceUnit"/> to a new <see cref="Power"/> in watts.
        /// </summary>
        /// <param name="value">Source value.</param>
        /// <param name="sourceUnit">Source value units.</param>
        /// <returns>New <see cref="Power"/> from the specified <paramref name="value"/> in <paramref name="sourceUnit"/>.</returns>
        public static Power ConvertFrom(double value, PowerUnit sourceUnit)
        {
            switch (sourceUnit)
            {
            case PowerUnit.Watts:
                return(value);

            case PowerUnit.Horsepower:
                return(FromHorsepower(value));

            case PowerUnit.MetricHorsepower:
                return(FromMetricHorsepower(value));

            case PowerUnit.BoilerHorsepower:
                return(FromBoilerHorsepower(value));

            case PowerUnit.BTUPerSecond:
                return(FromBTUPerSecond(value));

            case PowerUnit.CaloriesPerSecond:
                return(FromCaloriesPerSecond(value));

            case PowerUnit.LitersAtmospherePerSecond:
                return(FromLitersAtmospherePerSecond(value));

            default:
                throw new ArgumentOutOfRangeException(nameof(sourceUnit), sourceUnit, null);
            }
        }
Exemplo n.º 5
0
Arquivo: Power.cs Projeto: sotaria/gsf
        /// <summary>
        /// Converts the <see cref="Power"/> to the specified <paramref name="targetUnit"/>.
        /// </summary>
        /// <param name="targetUnit">Target units.</param>
        /// <returns><see cref="Power"/> converted to <paramref name="targetUnit"/>.</returns>
        public double ConvertTo(PowerUnit targetUnit)
        {
            switch (targetUnit)
            {
            case PowerUnit.Watts:
                return(m_value);

            case PowerUnit.Horsepower:
                return(ToHorsepower());

            case PowerUnit.MetricHorsepower:
                return(ToMetricHorsepower());

            case PowerUnit.BoilerHorsepower:
                return(ToBoilerHorsepower());

            case PowerUnit.BTUPerSecond:
                return(ToBTUPerSecond());

            case PowerUnit.CaloriesPerSecond:
                return(ToCaloriesPerSecond());

            case PowerUnit.LitersAtmospherePerSecond:
                return(ToLitersAtmospherePerSecond());

            default:
                throw new ArgumentOutOfRangeException(nameof(targetUnit), targetUnit, null);
            }
        }
Exemplo n.º 6
0
        //HeatFluxDensityUnit heatTransferCoefficient;
        //ForceUnit force;
        //SurfaceTensionUnit surfaceTension;

        public UnitSystem(TemperatureUnit temperature, PressureUnit pressure, MassFlowRateUnit massFlowRate,
                          VolumeFlowRateUnit volumeFlowRate, MoistureContentUnit moistureContent,
                          RatioUnit relativeHumidity, SpecificEnergyUnit enthalpy,
                          SpecificHeatUnit specificHeat, EnergyUnit energy, PowerUnit power, DensityUnit density,
                          DynamicViscosityUnit dynamicViscosity, KinematicViscosityUnit kinematicViscosity,
                          ThermalConductivityUnit conductivity, DiffusivityUnit diffusivity, MassUnit mass,
                          LengthUnit length, AreaUnit area, VolumeUnit volume, TimeUnit Time, string name) //ep
        {
            this.temperature        = temperature;
            this.pressure           = pressure;
            this.massFlowRate       = massFlowRate;
            this.volumeFlowRate     = volumeFlowRate;
            this.moistureContent    = moistureContent;
            this.relativeHumidity   = relativeHumidity;
            this.enthalpy           = enthalpy;
            this.specificHeat       = specificHeat;
            this.energy             = energy;
            this.power              = power;
            this.density            = density;
            this.dynamicViscosity   = dynamicViscosity;
            this.kinematicViscosity = kinematicViscosity;
            this.conductivity       = conductivity;
            this.diffusivity        = diffusivity;
            this.mass     = mass;
            this.length   = length;
            this.area     = area;
            this.volume   = volume;
            this.time     = time;
            this.Name     = name;  //ep
            this.readOnly = false; //ep
        }
Exemplo n.º 7
0
 public UnitSystem()
 {
     this.temperature        = TemperatureUnit.Celsius;
     this.pressure           = PressureUnit.Pascal;
     this.massFlowRate       = MassFlowRateUnit.KgPerSec;
     this.volumeFlowRate     = VolumeFlowRateUnit.CubicMeterPerSec;
     this.moistureContent    = MoistureContentUnit.KgPerKg;
     this.relativeHumidity   = RatioUnit.Percent;
     this.enthalpy           = SpecificEnergyUnit.JoulePerKg;
     this.specificHeat       = SpecificHeatUnit.JoulePerKgKelvin;
     this.energy             = EnergyUnit.Joule;
     this.power              = PowerUnit.JoulePerSec;
     this.density            = DensityUnit.KgPerCubicMeter;
     this.dynamicViscosity   = DynamicViscosityUnit.PascalSecond;
     this.kinematicViscosity = KinematicViscosityUnit.SquareMeterPerSec;
     this.conductivity       = ThermalConductivityUnit.WattPerMeterKelvin;
     this.diffusivity        = DiffusivityUnit.SquareMeterPerSec;
     this.mass     = MassUnit.Kilogram;
     this.length   = LengthUnit.Meter;
     this.area     = AreaUnit.SquareMeter;
     this.volume   = VolumeUnit.CubicMeter;
     this.time     = TimeUnit.Second;
     this.Name     = "SI"; //ep
     this.readOnly = true;
 }
        public void DeserializeCustomUnitAsPredefined_ShouldReturnValidResult()
        {
            // arrange
            var someUnit = new PowerUnit(
                name: "some unit",
                abbreviation: "su",
                valueInWatts: (number)123.456m);
            string json      = @"{
  'unit': 'su'
}";
            var    converter = new PowerUnitJsonConverter(
                serializationFormat: LinearUnitJsonSerializationFormat.PredefinedAsString,
                tryReadCustomPredefinedUnit: (string value, out PowerUnit predefinedUnit) =>
            {
                if (value == someUnit.Abbreviation)
                {
                    predefinedUnit = someUnit;
                    return(true);
                }

                predefinedUnit = default(PowerUnit);
                return(false);
            });

            // act
            var result = JsonConvert.DeserializeObject <SomeUnitOwner <PowerUnit> >(json, converter);

            // assert
            result.Unit.Should().Be(someUnit);
        }
Exemplo n.º 9
0
        private void btnRefreshUnits_Click(object sender, EventArgs e)
        {
            PowerUnit Unit = Newport.GetPowerUnit();

            switch (Unit)
            {
            case PowerUnit.Amperes:
                cmbPower.Text = "Amps";
                break;

            case PowerUnit.DecibalMilliwattts:
                cmbPower.Text = "DBm";
                break;

            case PowerUnit.Watts:
                cmbPower.Text = "Watts";
                break;

            case PowerUnit.WattsPerSquareCentimeter:
                cmbPower.Text = "Watts/cm2";
                break;

            default:
                cmbPower.Text = "Unknown";
                break;
            }
        }
Exemplo n.º 10
0
        private void btnSetUnit_Click(object sender, EventArgs e)
        {
            PowerUnit Unit = PowerUnit.Unknown;

            if (cmbPower.Text.Equals("Amps"))
            {
                Unit = PowerUnit.Amperes;
            }
            else if (cmbPower.Text.Equals("DBm"))
            {
                Unit = PowerUnit.DecibalMilliwattts;
            }
            else if (cmbPower.Text.Equals("Watts"))
            {
                Unit = PowerUnit.Watts;
            }
            else if (cmbPower.Text.Equals("Watts/cm2"))
            {
                Unit = PowerUnit.WattsPerSquareCentimeter;
            }

            try
            {
                Newport.SetPowerUnit(Unit);
            }
            catch (NewportMeterException ex)
            {
                MessageBox.Show(ex.ErrorCode.ToString() + ": " + ex.Message, "Can not set power units", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public string ToString(PowerUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix)
        {
            double value  = As(unit);
            string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);

            return(ToString(unit, cultureName, format));
        }
Exemplo n.º 12
0
        public string ToString(PowerUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix)
        {
            double value  = As(unit);
            string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);

            return(ToString(unit, provider, format));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Returns total sum of distance between cities represnted in the chromosome
        /// </summary>
        /// <param name="phenotype"></param>
        /// <returns></returns>
        public double CalculateScore(IMLMethod phenotype)
        {
            try
            {
                FourBitCustomGenome genome     = (FourBitCustomGenome)phenotype;
                FourBitGene []      genomeData = ((FourBitCustomGenome)genome).Data;
                //double maxPossiblePower = PowerUnits.Sum(x => x.UnitCapacity);

                new PowerUnitGALogic().DisplayGeneAsString(genome, genomeData);

                var intervalFitnessDataRepository = new IntervalFitnessDataRepository(MaxPossiblePower);
                var intervalRawData = intervalFitnessDataRepository.IntervalRawData;

                for (int i = 0; i < NumberOfIntervals; i++)
                {
                    IntervalsFitnessData interval = intervalRawData[i];
                    //interval.MaxReserve = maxPossiblePower;
                    for (int j = 0; j < genomeData.Length; j++)
                    {
                        PowerUnit   powerUnit             = PowerUnits[j];
                        FourBitGene fourBitGene           = genomeData[j];
                        int         geneBitIndex          = i;
                        var         isPowerUnitMaintained = fourBitGene.Gene[geneBitIndex] == 1;
                        if (isPowerUnitMaintained)
                        {
                            interval.ReducedAmountOnMaintainance = interval.ReducedAmountOnMaintainance + (1 * powerUnit.UnitCapacity);
                        }
                        else
                        {
                            interval.ReducedAmountOnMaintainance = interval.ReducedAmountOnMaintainance + (0 * powerUnit.UnitCapacity);
                        }
                    }

                    var totalPowerReductionOnMaintanceAndUsage =
                        interval.PowerRequirement + interval.ReducedAmountOnMaintainance;
                    interval.ReserveAfterMaintainance = interval.MaxReserve - totalPowerReductionOnMaintanceAndUsage;
                    //if (interval.ReserveAfterMaintainance < 0.0)
                    //{
                    //    // the chromosome is not suitable for out requirement
                    //    chromosomeFitness = 0.0;
                    //}
                }

                var reserveAfterMaintainanceMin = intervalRawData.Min(x => x.ReserveAfterMaintainance);
                // minimal rerserve after maintainance and usage provides chormosomes fitness
                //var chromosomeFitness = reserveAfterMaintainanceMin > 0.0 ? reserveAfterMaintainanceMin : 0.0;
                var chromosomeFitness = reserveAfterMaintainanceMin;
                Console.WriteLine("\tFitness = {0} - of {1}, {2}, {3}, {4}", chromosomeFitness,
                                  intervalRawData[0].ReserveAfterMaintainance, intervalRawData[1].ReserveAfterMaintainance,
                                  intervalRawData[2].ReserveAfterMaintainance, intervalRawData[3].ReserveAfterMaintainance);
                return(chromosomeFitness);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
 public void PowerConversions(double value1, PowerUnit units1, double value2, PowerUnit units2)
 {
     new Power(value1, units1) {
         Units = units2
     }.Value.ShouldBeWithinEpsilonOf(value2);
     new Power(value2, units2) {
         Units = units1
     }.Value.ShouldBeWithinEpsilonOf(value1);
 }
Exemplo n.º 15
0
        private FourBitGene GetRandomGeneForPowerUnit(PowerUnit powerUnitInfo)
        {
            try
            {
                var randomGene   = new FourBitGene();
                var random       = new Random();
                var randomNumber = random.Next(1, 101); // random number is between 0 and 100

                // add maintainace gene bits
                switch (powerUnitInfo.NumberOfIntervalsRequiredForMaintainance)
                {
                case 1:
                {
                    var remainder = randomNumber % 4;            // either zero or one or two or three
                    randomGene.Gene = remainder == 0 ? new[] { 0, 0, 0, 1 } :
                    remainder == 1 ? new[] { 0, 0, 1, 0 } :
                    remainder == 2 ? new[] { 0, 1, 0, 0 } : new[] { 1, 0, 0, 0 };
                    break;
                }

                case 2:
                {
                    var remainder = randomNumber % 3;            // either zero or one or two
                    randomGene.Gene = remainder == 0 ? new[] { 0, 0, 1, 1 } :
                    remainder == 1 ? new[] { 0, 1, 1, 0 } : new[] { 1, 1, 0, 0 };
                    break;
                }

                case 3:
                {
                    var remainder = randomNumber % 2;            // either zero or one
                    randomGene.Gene = remainder == 0 ? new[] { 0, 1, 1, 1 } : new[] { 1, 1, 1, 0 };
                    break;
                }

                case 4:
                {
                    var remainder = randomNumber % 2;            // either zero or one
                    randomGene.Gene = remainder == 0 ? new[] { 0, 0, 0, 0 } : new[] { 1, 1, 1, 1 };
                    break;
                }

                default:
                {
                    randomGene.Gene = new[] { 0, 0, 0, 0 };
                    break;
                }
                }
                return(randomGene);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Convert to the unit representation <paramref name="unit" />.
        /// </summary>
        /// <returns>Value in new unit if successful, exception otherwise.</returns>
        /// <exception cref="NotImplementedException">If conversion was not successful.</exception>
        public double As(PowerUnit unit)
        {
            switch (unit)
            {
            case PowerUnit.BoilerHorsepower:
                return(BoilerHorsepower);

            case PowerUnit.ElectricalHorsepower:
                return(ElectricalHorsepower);

            case PowerUnit.Femtowatt:
                return(Femtowatts);

            case PowerUnit.Gigawatt:
                return(Gigawatts);

            case PowerUnit.HydraulicHorsepower:
                return(HydraulicHorsepower);

            case PowerUnit.Kilowatt:
                return(Kilowatts);

            case PowerUnit.MechanicalHorsepower:
                return(MechanicalHorsepower);

            case PowerUnit.Megawatt:
                return(Megawatts);

            case PowerUnit.MetricHorsepower:
                return(MetricHorsepower);

            case PowerUnit.Microwatt:
                return(Microwatts);

            case PowerUnit.Milliwatt:
                return(Milliwatts);

            case PowerUnit.Nanowatt:
                return(Nanowatts);

            case PowerUnit.Petawatt:
                return(Petawatts);

            case PowerUnit.Picowatt:
                return(Picowatts);

            case PowerUnit.Terawatt:
                return(Terawatts);

            case PowerUnit.Watt:
                return(Watts);

            default:
                throw new NotImplementedException("unit: " + unit);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        ///     Creates the quantity with the given numeric value and unit.
        /// </summary>
        /// <param name="numericValue">The numeric value  to contruct this quantity with.</param>
        /// <param name="unit">The unit representation to contruct this quantity with.</param>
        /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks>
        /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
        private Power(double numericValue, PowerUnit unit)
        {
            if (unit == PowerUnit.Undefined)
            {
                throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
            }

            _value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
            _unit  = unit;
        }
Exemplo n.º 18
0
            public void ShouldConvertToExpectedValue(Power originalPower, PowerUnit targetUnit, Power expectedPower)
            {
                // arrange
                // act
                var actualPower = originalPower.Convert(targetUnit);

                // assert
                actualPower.Should().Be(expectedPower);
                actualPower.Unit.Should().Be(targetUnit);
            }
        private void cmbPowerMeterUnit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isPowerMeterConnected)
            {
                return;
            }
            PowerUnit unit = (PowerUnit)this.cmbPowerMeterUnit.SelectedIndex;

            powerMeter.PowerUnitChange(unit);
        }
Exemplo n.º 20
0
        /// <summary>
        ///     Creates the quantity with the given numeric value and unit.
        /// </summary>
        /// <param name="numericValue">The numeric value  to contruct this quantity with.</param>
        /// <param name="unit">The unit representation to contruct this quantity with.</param>
        /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks>
        /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
        private Power(decimal numericValue, PowerUnit unit)
        {
            if (unit == PowerUnit.Undefined)
            {
                throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
            }

            _value = numericValue;
            _unit  = unit;
        }
Exemplo n.º 21
0
        private decimal AsBaseNumericType(PowerUnit unit)
        {
            if (Unit == unit)
            {
                return(_value);
            }

            var baseUnitValue = AsBaseUnit();

            switch (unit)
            {
            case PowerUnit.BoilerHorsepower: return(baseUnitValue / 9812.5m);

            case PowerUnit.BritishThermalUnitPerHour: return(baseUnitValue / 0.293071m);

            case PowerUnit.Decawatt: return((baseUnitValue) / 1e1m);

            case PowerUnit.Deciwatt: return((baseUnitValue) / 1e-1m);

            case PowerUnit.ElectricalHorsepower: return(baseUnitValue / 746m);

            case PowerUnit.Femtowatt: return((baseUnitValue) / 1e-15m);

            case PowerUnit.Gigawatt: return((baseUnitValue) / 1e9m);

            case PowerUnit.HydraulicHorsepower: return(baseUnitValue / 745.69988145m);

            case PowerUnit.KilobritishThermalUnitPerHour: return((baseUnitValue / 0.293071m) / 1e3m);

            case PowerUnit.Kilowatt: return((baseUnitValue) / 1e3m);

            case PowerUnit.MechanicalHorsepower: return(baseUnitValue / 745.69m);

            case PowerUnit.Megawatt: return((baseUnitValue) / 1e6m);

            case PowerUnit.MetricHorsepower: return(baseUnitValue / 735.49875m);

            case PowerUnit.Microwatt: return((baseUnitValue) / 1e-6m);

            case PowerUnit.Milliwatt: return((baseUnitValue) / 1e-3m);

            case PowerUnit.Nanowatt: return((baseUnitValue) / 1e-9m);

            case PowerUnit.Petawatt: return((baseUnitValue) / 1e15m);

            case PowerUnit.Picowatt: return((baseUnitValue) / 1e-12m);

            case PowerUnit.Terawatt: return((baseUnitValue) / 1e12m);

            case PowerUnit.Watt: return(baseUnitValue);

            default:
                throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        ///     Convert to the unit representation <paramref name="unit" />.
        /// </summary>
        /// <returns>Value converted to the specified unit.</returns>
        public double As(PowerUnit unit)
        {
            if (Unit == unit)
            {
                return(Convert.ToDouble(Value));
            }

            var converted = AsBaseNumericType(unit);

            return(Convert.ToDouble(converted));
        }
Exemplo n.º 23
0
        /// <summary>
        ///     Convert to the unit representation <paramref name="unit" />.
        /// </summary>
        /// <returns>Value converted to the specified unit.</returns>
        public decimal As(PowerUnit unit)
        {
            if (Unit == unit)
            {
                return(Convert.ToDecimal(Value));
            }

            var converted = AsBaseNumericType(unit);

            return(Convert.ToDecimal(converted));
        }
Exemplo n.º 24
0
 public UnitSystem(
     string id,
     WeightUnit baseWeightUnit,
     LengthUnit baseLengthUnit,
     PowerUnit basePowerUnit)
 {
     ID             = Assert.IsNotNullOrWhiteSpace(id, nameof(id));
     BaseWeightUnit = baseWeightUnit;
     BaseLengthUnit = baseLengthUnit;
     BasePowerUnit  = basePowerUnit;
 }
            public void ParamlessConstructedPowerUnit_ShouldBeEqualToWatt()
            {
                // arrange
                var paramlessConstructedPowerUnit = new PowerUnit();
                var watt = PowerUnit.Watt;

                // act
                // assert
                watt.Equals(paramlessConstructedPowerUnit).Should().BeTrue(because: "'PowerUnit.Watt' should be equal 'new PowerUnit()'");
                paramlessConstructedPowerUnit.Equals(watt).Should().BeTrue(because: "'new PowerUnit()' should be equal 'PowerUnit.Watt'");
            }
Exemplo n.º 26
0
        //public virtual void Add(PowerUnit com, string name)
        //{
        //    //if (_components.Where(curObj => curObj.Site != null).Any(curObj => curObj.Site.Name.Equals(name)))
        //    //{
        //    //    throw new SystemException("컨테이너에 같은 이름이 존재합니다!");
        //    //}
        //    foreach (var component in _components)
        //    {
        //        var curObj = (PowerUnit)component;
        //        if (curObj.Site != null)
        //        {
        //            if (curObj.Site.Name.Equals(name))
        //                throw new SystemException("컨테이너에 같은 이름이 존재합니다!");
        //        }
        //    }
        //    _components.Add(com);
        //}

        public void Remove(PowerUnit com)
        {
            for (int i = 0; i < Components.Count; ++i)
            {
                if (com.Equals(Components[i]))
                {
                    Components.RemoveAt(i);
                    break;
                }
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Converts the <see cref="Power"/> to the specified <paramref name="targetUnit"/>.
 /// </summary>
 /// <param name="targetUnit">Target units.</param>
 /// <returns><see cref="Power"/> converted to <paramref name="targetUnit"/>.</returns>
 public double ConvertTo(PowerUnit targetUnit)
 {
     return(targetUnit switch
     {
         PowerUnit.Watts => m_value,
         PowerUnit.Horsepower => ToHorsepower(),
         PowerUnit.MetricHorsepower => ToMetricHorsepower(),
         PowerUnit.BoilerHorsepower => ToBoilerHorsepower(),
         PowerUnit.BTUPerSecond => ToBTUPerSecond(),
         PowerUnit.CaloriesPerSecond => ToCaloriesPerSecond(),
         PowerUnit.LitersAtmospherePerSecond => ToLitersAtmospherePerSecond(),
         _ => throw new ArgumentOutOfRangeException(nameof(targetUnit), targetUnit, null)
     });
Exemplo n.º 28
0
        /// <summary>
        ///     Parse a string of the format "&lt;quantity&gt; &lt;unit&gt;".
        /// </summary>
        /// <example>
        ///     Length.Parse("5.5 m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="ArgumentException">
        ///     Expected 2 words. Input string needs to be in the format "&lt;quantity&gt; &lt;unit
        ///     &gt;".
        /// </exception>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        public static Power Parse(string str, IFormatProvider formatProvider = null)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

            var numFormat = formatProvider != null ?
                            (NumberFormatInfo)formatProvider.GetFormat(typeof(NumberFormatInfo)) :
                            NumberFormatInfo.CurrentInfo;

            var numRegex = string.Format(@"[\d., {0}{1}]*\d",               // allows digits, dots, commas, and spaces in the quantity (must end in digit)
                                         numFormat.NumberGroupSeparator,    // adds provided (or current) culture's group separator
                                         numFormat.NumberDecimalSeparator); // adds provided (or current) culture's decimal separator
            var regexString = string.Format("(?<value>[-+]?{0}{1}{2}{3}",
                                            numRegex,                       // capture base (integral) Quantity value
                                            @"(?:[eE][-+]?\d+)?)",          // capture exponential (if any), end of Quantity capturing
                                            @"\s?",                         // ignore whitespace (allows both "1kg", "1 kg")
                                            @"(?<unit>\S+)");               // capture Unit (non-whitespace) input

            var             regex  = new Regex(regexString);
            GroupCollection groups = regex.Match(str.Trim()).Groups;

            var valueString = groups["value"].Value;
            var unitString  = groups["unit"].Value;

            if (valueString == "" || unitString == "")
            {
                var ex = new ArgumentException(
                    "Expected valid quantity and unit. Input string needs to be in the format \"<quantity><unit> or <quantity> <unit>\".", "str");
                ex.Data["input"]          = str;
                ex.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                throw ex;
            }

            try
            {
                PowerUnit unit  = ParseUnit(unitString, formatProvider);
                double    value = double.Parse(valueString, formatProvider);

                return(From(value, unit));
            }
            catch (Exception e)
            {
                var newEx = new UnitsNetException("Error parsing string.", e);
                newEx.Data["input"]          = str;
                newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                throw newEx;
            }
        }
        public void DeserializePredefinedUnitString_ShouldReturnValidResult(PowerUnit expectedUnit)
        {
            // arrange
            string json      = $@"{{
  'unit': '{expectedUnit.Abbreviation}'
}}";
            var    converter = new PowerUnitJsonConverter();

            // act
            var result = JsonConvert.DeserializeObject <SomeUnitOwner <PowerUnit> >(json, converter);

            // assert
            result.Unit.Should().Be(expectedUnit);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 单位切换
        /// </summary>
        /// <param name="unit">DBM,W</param>
        public override bool PowerUnitChange(PowerUnit unit)
        {
            string sendMsg = ":UNIT0:POW " + unit.ToString();

            try
            {
                base.WriteString(sendMsg);
                return(true);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Exemplo n.º 31
0
        /// <summary>
        ///     Parse a string given a particular regular expression.
        /// </summary>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        private static List <Power> ParseWithRegex(string regexString, string str, IFormatProvider formatProvider = null)
        {
            var             regex     = new Regex(regexString);
            MatchCollection matches   = regex.Matches(str.Trim());
            var             converted = new List <Power>();

            foreach (Match match in matches)
            {
                GroupCollection groups = match.Groups;

                var valueString = groups["value"].Value;
                var unitString  = groups["unit"].Value;
                if (groups["invalid"].Value != "")
                {
                    var newEx = new UnitsNetException("Invalid string detected: " + groups["invalid"].Value);
                    newEx.Data["input"]          = str;
                    newEx.Data["matched value"]  = valueString;
                    newEx.Data["matched unit"]   = unitString;
                    newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                    throw newEx;
                }
                if (valueString == "" && unitString == "")
                {
                    continue;
                }

                try
                {
                    PowerUnit unit  = ParseUnit(unitString, formatProvider);
                    double    value = double.Parse(valueString, formatProvider);

                    converted.Add(From(value, unit));
                }
                catch (AmbiguousUnitParseException ambiguousException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    var newEx = new UnitsNetException("Error parsing string.", ex);
                    newEx.Data["input"]          = str;
                    newEx.Data["matched value"]  = valueString;
                    newEx.Data["matched unit"]   = unitString;
                    newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                    throw newEx;
                }
            }
            return(converted);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Is called when data is recieved
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Port0_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //Capture power
            var readPower = "";
            var annunciator = 0;

            try
            {
                readPower = _deviceManager.Devices[0].Port.ReadExisting();
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (_powerUnit != PowerUnit.None && readPower.Length == 8)
            {
                try
                {
                    _power = Convert.ToInt32(readPower.Substring(0, 7));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("power extraction error: " + ex.Message);
                }
                finally
                {
                    _powerUnit = PowerUnit.None;
                }
            }

            if (readPower.Length >= 8)
            {
                try
                {
                    annunciator = Convert.ToInt32(readPower.Substring(3, 2));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("annunciator extraction error: " + ex.Message);
                }
            }

            if (annunciator == AnnunciatorW)
            {
                _powerUnit = PowerUnit.Watt;
                _powerSymbol = "W";
            }

            if (annunciator == AnnunciatorkW)
            {
                _powerUnit = PowerUnit.KiloWatt;
                _powerSymbol = "kW";
            }

            if (_powerUnit == PowerUnit.None || readPower.Length != 16) return;
            try
            {
                _power = Convert.ToInt32(readPower.Substring(7, 8));
            }
            catch (Exception ex)
            {
                Console.WriteLine("power extraction error: " + ex.Message);
            }
            finally
            {
                _powerUnit = PowerUnit.None;
            }
        }
 protected static string CreateSuffix(SymbolFormat format, PowerUnit unit)
 {
     return default(Power).ToString(unit, format).Trim('0');
 }