예제 #1
0
 public void ParseTest()
 {
     #region Test parsing
     {
         var metricSystem = new MetricSystem("metricSystemX");
         var quantity     = new BaseQuantity("quantityX");
         var unit         = new BaseUnit(metricSystem, quantity, "unitX", "X");
         #region Test valid parsing
         {
             try
             {
                 var parsedUnit = Unit.Parse("X");
                 Assert.AreEqual(unit, parsedUnit, "Valid value should parse into " +
                                 "the correct unit.");
             }
             catch (Exception e)
             {
                 Assert.Fail("Valid value parsing should not fail.", e);
             }
         }
         #endregion
         #region Test invalid parsing
         //Test invalid parsing
         {
             try
             {
                 Unit.Parse("Z");
                 Assert.Fail("Invalid value parsing should fail.");
             }
             catch (Exception) { }
         }
         #endregion
     }
     #endregion
 }
예제 #2
0
 public void BaseQuantity_ToUnitSystem()
 {
     for (var i = 0; i < BenchmarkConstants.NbUnits; i++)
     {
         Consumer.Consume(BaseQuantity.ToUnit(UnitSystems[0]));
     }
 }
예제 #3
0
 public void BaseQuantity_ToUnit()
 {
     for (var i = 0; i < BenchmarkConstants.NbUnits; i++)
     {
         var conversion = BaseUnitConversions[BaseQuantityIndex];
         Consumer.Consume(BaseQuantity.ToUnit((LengthUnit)conversion.Value));
     }
 }
예제 #4
0
        /// <summary>
        /// Override of the get hash code method.
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            //Get hash code for the nullable fields.
            int hashName       = Name == null ? 0 : Name.GetHashCode();
            int hashCategories = Categories == null ? 0 : Categories.Distinct().Aggregate(0, (x, y) => x.GetHashCode() ^ y.GetHashCode());;

            //Calculate the hash code for the GPOPolicy.
            return(_id.GetHashCode() ^ BaseQuantity.GetHashCode() ^ PriceUnit.GetHashCode() ^ hashName ^ hashCategories);
        }
예제 #5
0
        public DerivedQuantity(float exponent, params AnyQuantity <T>[] internalQuantities)
            : base(exponent)
        {
            InternalQuantities = internalQuantities;
            var qtypes = from qt in internalQuantities
                         select new Tuple <Type, float>(qt.GetType().GetGenericTypeDefinition(), qt.Exponent);

            BaseQuantity.SetInternalQuantities(this.GetType().GetGenericTypeDefinition(), qtypes.ToArray());
        }
예제 #6
0
        public void EqualsTest()
        {
            #region Test equality comparison
            {
                var metricSystem = new MetricSystem("metricSystemX");
                var quantity     = new BaseQuantity("quantityX");
                var baseUnitA    = new BaseUnit(metricSystem, quantity, "unitX", "X");
                var baseUnitB    = new BaseUnit(metricSystem, quantity, "unitY", "Y");
                try
                {
                    #region For base units
                    {
                        #region For equal units
                        {
                            Assert.AreEqual(baseUnitA, baseUnitA, "Equivalent units should test equal.");
                        }
                        #endregion
                        #region For different units
                        {
                            Assert.AreNotEqual(baseUnitA, baseUnitB, "Equivalent units should test equal.");
                        }
                        #endregion
                    }
                    #endregion
                    #region For derived units
                    {
                        var derivedUnitA = baseUnitA * baseUnitA;
                        var derivedUnitB = baseUnitA * baseUnitB;
                        #region For equal units
                        {
                            Assert.AreEqual(derivedUnitA, derivedUnitA, "Equivalent " +
                                            "derived units should test equal.");
                        }
                        #endregion
                        #region For different units
                        {
                            Assert.AreNotEqual(derivedUnitA, derivedUnitB, "Equivalent " +
                                               "derived units should test equal.");
                        }
                        #endregion
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    if (e is UnitTestAssertException)
                    {
                        throw e;
                    }

                    Assert.Fail("Testing for equality should not fail internally.", e);
                }
            }
            #endregion
        }
예제 #7
0
 static BaseQuantities()
 {
     Angle      = DefineNewBaseQuantity(nameof(Angle), "Radian", unitSymbol: "rad");
     SolidAngle = DefineNewBaseQuantity(nameof(SolidAngle), "Steradian", unitSymbol: "sr");
     // TODO improve name system to allow spaces or underscores
     ElectricCurrent   = DefineNewBaseQuantity(nameof(ElectricCurrent), "Ampere", quantitySymbol: "I", unitSymbol: "A");
     Information       = DefineNewBaseQuantity(nameof(Information), "Bit", unitSymbol: "b");
     Length            = DefineNewBaseQuantity(nameof(Length), "Meter", quantitySymbol: "l", unitSymbol: "m");
     Mass              = DefineNewBaseQuantity(nameof(Mass), "Gram", unitPrefix: Prefixes.Kilo, quantitySymbol: "M", unitSymbol: "g");
     Temperature       = DefineNewBaseQuantity(nameof(Temperature), "Kelvin", quantitySymbol: "Θ", unitSymbol: "K");
     Time              = DefineNewBaseQuantity(nameof(Time), "Second", quantitySymbol: "T", unitSymbol: "s");
     LuminousIntensity = DefineNewBaseQuantity(nameof(LuminousIntensity), "Candela", quantitySymbol: "J", unitSymbol: "cd");
 }
예제 #8
0
        /// <summary>
        /// Override of the equality method.
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public bool Equals(Ingredients o)
        {
            //Check whether the compared object is null.
            if (ReferenceEquals(o, null))
            {
                return(false);
            }

            //Check whether the compared object references the same data.
            if (ReferenceEquals(this, o))
            {
                return(true);
            }

            //Check whether the Ingredients' properties are equal.
            return(_id.Equals(o._id) && BaseQuantity.Equals(o.BaseQuantity) && PriceUnit.Equals(o.PriceUnit) && Name.Equals(o.Name) && Tools.SequenceEqual(Categories, o.Categories));
        }
예제 #9
0
        public void TryParseTest()
        {
            #region Test Parsing
            {
                var metricSystem = new MetricSystem("metricSystemX");
                var quantity     = new BaseQuantity("quantityX");
                var unit         = new BaseUnit(metricSystem, quantity, "unitX", "X");
                try
                {
                    #region Test valid parsing
                    {
                        Unit parsedUnit;
                        if (Unit.TryParse("X", out parsedUnit))
                        {
                            Assert.AreEqual(unit, parsedUnit, "Valid value should parse" +
                                            " into the correct unit.");
                        }
                        else
                        {
                            Assert.Fail("Valid unit parsing should not fail.");
                        }
                    }
                    #endregion
                    #region Test invalid parsing
                    {
                        Unit parsedUnit;
                        if (Unit.TryParse("Y", out parsedUnit))
                        {
                            Assert.Fail("Invalid value parsing should fail.");
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e is UnitTestAssertException)
                    {
                        throw e;
                    }

                    Assert.Fail("Parsing should not fail internally.", e);
                }
                #endregion
            }
            #endregion
        }
        public override string GetStepParameters()
        {
            var parameters = new List <string>();

            parameters.Add(GlobalId != null ? GlobalId.ToStepValue() : "$");
            parameters.Add(OwnerHistory != null ? OwnerHistory.ToStepValue() : "$");
            parameters.Add(Name != null ? Name.ToStepValue() : "$");
            parameters.Add(Description != null ? Description.ToStepValue() : "$");
            parameters.Add(ObjectType != null ? ObjectType.ToStepValue() : "$");
            parameters.Add(Identification != null ? Identification.ToStepValue() : "$");
            parameters.Add(LongDescription != null ? LongDescription.ToStepValue() : "$");
            parameters.Add(Usage != null ? Usage.ToStepValue() : "$");
            parameters.Add(BaseCosts != null ? BaseCosts.ToStepValue() : "$");
            parameters.Add(BaseQuantity != null ? BaseQuantity.ToStepValue() : "$");
            parameters.Add(PredefinedType.ToStepValue());

            return(string.Join(", ", parameters.ToArray()));
        }
예제 #11
0
        public override string GetStepParameters()
        {
            var parameters = new List <string>();

            parameters.Add(GlobalId != null ? GlobalId.ToStepValue() : "$");
            parameters.Add(OwnerHistory != null ? OwnerHistory.ToStepValue() : "$");
            parameters.Add(Name != null ? Name.ToStepValue() : "$");
            parameters.Add(Description != null ? Description.ToStepValue() : "$");
            parameters.Add(ApplicableOccurrence != null ? ApplicableOccurrence.ToStepValue() : "$");
            parameters.Add(HasPropertySets != null ? HasPropertySets.ToStepValue() : "$");
            parameters.Add(Identification != null ? Identification.ToStepValue() : "$");
            parameters.Add(LongDescription != null ? LongDescription.ToStepValue() : "$");
            parameters.Add(ResourceType != null ? ResourceType.ToStepValue() : "$");
            parameters.Add(BaseCosts != null ? BaseCosts.ToStepValue() : "$");
            parameters.Add(BaseQuantity != null ? BaseQuantity.ToStepValue() : "$");
            parameters.Add(PredefinedType.ToStepValue());

            return(string.Join(", ", parameters.ToArray()));
        }
예제 #12
0
        public void TestUnitCompositions()
        {
            var quantA = BaseQuantity.DefineNewBaseQuantity("quantA",
                                                            "a");

            var a      = (BaseUnit)quantA.FundamentalUnit;
            var b      = new BaseUnit("b", a, 2);
            var prefix = new Prefix("prefix", 4);
            var c      = PrefixedUnit.GetPrefixedUnit(a, prefix);

            var composition =
                a.UnitComposition *
                b.UnitComposition /
                c.UnitComposition;

            var d = Unit.DefineFromComposition("d", composition);

            Assert.AreSame(quantA, d.Quantity);
            Assert.IsInstanceOfType(d, typeof(BaseUnit));
            Assert.AreEqual(0.5m, d.FundamentalMultiplier);
        }
예제 #13
0
        public void CollapseTest()
        {
            #region Test unit collapsing
            {
                var metricSystem = new MetricSystem("metricSystemX");
                var quantity     = new BaseQuantity("quantityX");
                try
                {
                    var unit = new BaseUnit(metricSystem, quantity, "unitX", "X");
                    #region For base unit
                    {
                        var collapsedUnit = unit.Collapse();
                        Assert.AreEqual(unit, collapsedUnit, "A collapsed base unit " +
                                        "should be equal to itself.");
                    }
                    #endregion ;

                    var derivedUnit = unit * unit / unit;
                    #region For derived unit
                    {
                        var collapsedDerivedUnit = derivedUnit.Collapse();
                        Assert.AreEqual(unit, collapsedDerivedUnit, "A collapsed derived unit " +
                                        "X*X/X should result in X.");
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    if (e is UnitTestAssertException)
                    {
                        throw e;
                    }

                    Assert.Fail("Collapsing should not fail internally.", e);
                }
            }
            #endregion
        }
예제 #14
0
        /// <summary>
        /// Converts the unit to a series of reference unit factors. (Unrecognized units will be assumed to be reference units.)
        /// </summary>
        /// <param name="Magnitude">Reference magnitude.</param>
        /// <returns>Unit consisting of reference unit factors.</returns>
        public Unit FromReferenceUnits(ref double Magnitude)
        {
            if (this.hasReferenceUnits)
            {
                return(this);
            }

            lock (synchObject)
            {
                if (baseUnits is null)
                {
                    Search();
                }

                bool HasNonReference = false;

                foreach (KeyValuePair <AtomicUnit, int> Factor in this.factors)
                {
                    if (!referenceUnits.ContainsKey(Factor.Key.Name))
                    {
                        HasNonReference = true;
                        break;
                    }
                }

                if (HasNonReference)
                {
                    LinkedList <KeyValuePair <AtomicUnit, int> > ReferenceFactors = new LinkedList <KeyValuePair <AtomicUnit, int> >();
                    int    Exponent = Prefixes.PrefixToExponent(this.prefix);
                    int    FactorExponent;
                    string Name;

                    foreach (KeyValuePair <AtomicUnit, int> Factor in this.factors)
                    {
                        FactorExponent = Factor.Value;

                        if (referenceUnits.ContainsKey(Name = Factor.Key.Name))
                        {
                            this.Add(ReferenceFactors, Factor.Key, Factor.Value);
                        }
                        else if (baseUnits.TryGetValue(Name, out IBaseQuantity BaseQuantity))
                        {
                            if (BaseQuantity.FromReferenceUnit(ref Magnitude, Name, FactorExponent))
                            {
                                this.Add(ReferenceFactors, BaseQuantity.ReferenceUnit, FactorExponent);
                            }
                            else
                            {
                                this.Add(ReferenceFactors, Factor.Key, Factor.Value);
                            }
                        }
                        else if (derivedUnits.TryGetValue(Name, out PhysicalQuantity Quantity))
                        {
                            Magnitude *= Math.Pow(Quantity.Magnitude, FactorExponent);
                            Exponent  += Prefixes.PrefixToExponent(Quantity.Unit.prefix) * FactorExponent;

                            foreach (KeyValuePair <AtomicUnit, int> Segment in Quantity.Unit.factors)
                            {
                                if (referenceUnits.ContainsKey(Name = Segment.Key.Name))
                                {
                                    this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                }
                                else if (baseUnits.TryGetValue(Name, out BaseQuantity))
                                {
                                    if (BaseQuantity.FromReferenceUnit(ref Magnitude, Name, Segment.Value * FactorExponent))
                                    {
                                        this.Add(ReferenceFactors, BaseQuantity.ReferenceUnit, Segment.Value * FactorExponent);
                                    }
                                    else
                                    {
                                        this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                    }
                                }
                                else
                                {
                                    this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                }
                            }
                        }
                        else if (compoundUnits.TryGetValue(Name, out KeyValuePair <AtomicUnit, int>[] Units))
                        {
                            foreach (KeyValuePair <AtomicUnit, int> Segment in Units)
                            {
                                if (referenceUnits.ContainsKey(Name = Segment.Key.Name))
                                {
                                    this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                }
                                else if (baseUnits.TryGetValue(Name, out BaseQuantity))
                                {
                                    if (BaseQuantity.FromReferenceUnit(ref Magnitude, Name, Segment.Value * FactorExponent))
                                    {
                                        this.Add(ReferenceFactors, BaseQuantity.ReferenceUnit, Segment.Value * FactorExponent);
                                    }
                                    else
                                    {
                                        this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                    }
                                }
                                else
                                {
                                    this.Add(ReferenceFactors, Segment.Key, Segment.Value * FactorExponent);
                                }
                            }
                        }
                        else
                        {
                            this.Add(ReferenceFactors, Factor.Key, Factor.Value);
                        }
                    }

                    Unit Result = new Unit(Prefixes.ExponentToPrefix(Exponent, out FactorExponent), ReferenceFactors);
                    if (FactorExponent != 0)
                    {
                        Magnitude *= Math.Pow(10, FactorExponent);
                    }

                    Result.hasBaseUnits      = true;
                    Result.hasReferenceUnits = true;

                    return(Result);
                }
                else
                {
                    this.hasBaseUnits      = true;
                    this.hasReferenceUnits = true;
                    return(this);
                }
            }
        }
 /// <summary>
 /// Extension method to convert degrees to radians
 /// </summary>
 /// <param name="val">quantity measured in degrees</param>
 /// <returns>quantity measured in radians</returns>
 public static Quantity <double, RadiansPerSecond> ToRadians <T>(this BaseQuantity <T, DegreesPerSecond> val) where T : IConvertible
 {
     return(new Quantity <double, RadiansPerSecond>(
                Convert.ToDouble(val.Value) * Deg2Rad
                ));
 }
 /// <summary>
 /// Extension method to convert G to MetrePerSecondSq
 /// </summary>
 /// <param name="val">quantity measured in G</param>
 /// <returns>quantity measured in MetrePerSecondSq</returns>
 public static Quantity <double, MetrePerSecondSq> ToMetrePerSecondSq <T>(this BaseQuantity <T, G> val) where T : IConvertible
 {
     return(new Quantity <double, MetrePerSecondSq>(
                Convert.ToDouble(val.Value) * 9.80665
                ));
 }
예제 #17
0
 /// <summary>
 /// Extension method to convert Foot to Inch
 /// </summary>
 /// <param name="val">quantity measured in Foot</param>
 /// <returns>quantity measured in Inch</returns>
 public static Quantity <double, Inch> ToInch <T>(this BaseQuantity <T, Foot> val) where T : IConvertible
 {
     return(new Quantity <double, Inch>(
                Convert.ToDouble(val.Value) * ((1d / (5280)) * (63360))
                ));
 }
예제 #18
0
 /// <summary>
 /// Extension method to convert Foot to Mile
 /// </summary>
 /// <param name="val">quantity measured in Foot</param>
 /// <returns>quantity measured in Mile</returns>
 public static Quantity <double, Mile> ToMile <T>(this BaseQuantity <T, Foot> val) where T : IConvertible
 {
     return(new Quantity <double, Mile>(
                Convert.ToDouble(val.Value) * (1d / (5280))
                ));
 }
예제 #19
0
 /// <summary>
 /// Extension method to convert Mile to Foot
 /// </summary>
 /// <param name="val">quantity measured in Mile</param>
 /// <returns>quantity measured in Foot</returns>
 public static Quantity <double, Foot> ToFoot <T>(this BaseQuantity <T, Mile> val) where T : IConvertible
 {
     return(new Quantity <double, Foot>(
                Convert.ToDouble(val.Value) * 5280
                ));
 }
예제 #20
0
 /// <summary>
 /// Extension method to convert Inch to League
 /// </summary>
 /// <param name="val">quantity measured in Inch</param>
 /// <returns>quantity measured in League</returns>
 public static Quantity <double, League> ToLeague <T>(this BaseQuantity <T, Inch> val) where T : IConvertible
 {
     return(new Quantity <double, League>(
                Convert.ToDouble(val.Value) * ((1d / (63360)) * (0.289659))
                ));
 }
예제 #21
0
 /// <summary>
 /// Extension method to convert Inch to Yard
 /// </summary>
 /// <param name="val">quantity measured in Inch</param>
 /// <returns>quantity measured in Yard</returns>
 public static Quantity <double, Yard> ToYard <T>(this BaseQuantity <T, Inch> val) where T : IConvertible
 {
     return(new Quantity <double, Yard>(
                Convert.ToDouble(val.Value) * ((1d / (63360)) * (1760))
                ));
 }
예제 #22
0
 /// <summary>
 /// Extension method to convert League to Foot
 /// </summary>
 /// <param name="val">quantity measured in League</param>
 /// <returns>quantity measured in Foot</returns>
 public static Quantity <double, Foot> ToFoot <T>(this BaseQuantity <T, League> val) where T : IConvertible
 {
     return(new Quantity <double, Foot>(
                Convert.ToDouble(val.Value) * ((1d / (0.289659)) * (5280))
                ));
 }
예제 #23
0
 /// <summary>
 /// Extension method to convert League to Mile
 /// </summary>
 /// <param name="val">quantity measured in League</param>
 /// <returns>quantity measured in Mile</returns>
 public static Quantity <double, Mile> ToMile <T>(this BaseQuantity <T, League> val) where T : IConvertible
 {
     return(new Quantity <double, Mile>(
                Convert.ToDouble(val.Value) * (1d / (0.289659))
                ));
 }
예제 #24
0
 /// <summary>
 /// Extension method to convert Mile to Yard
 /// </summary>
 /// <param name="val">quantity measured in Mile</param>
 /// <returns>quantity measured in Yard</returns>
 public static Quantity <double, Yard> ToYard <T>(this BaseQuantity <T, Mile> val) where T : IConvertible
 {
     return(new Quantity <double, Yard>(
                Convert.ToDouble(val.Value) * 1760
                ));
 }
예제 #25
0
 /// <summary>
 /// Extension method to convert Mile to Inch
 /// </summary>
 /// <param name="val">quantity measured in Mile</param>
 /// <returns>quantity measured in Inch</returns>
 public static Quantity <double, Inch> ToInch <T>(this BaseQuantity <T, Mile> val) where T : IConvertible
 {
     return(new Quantity <double, Inch>(
                Convert.ToDouble(val.Value) * 63360
                ));
 }
예제 #26
0
        public void TestConversionsAndDefinitions()
        {
            /*  A = fundamental
             *      A = 2*B + 40
             *      A = 8*C + 360
             *
             *  B = (A/2) - 20 = 4*C + 160
             *      B.multiplier = 2
             *      B.offset = 20
             *
             *  C = (B/4) - 40 = (A/8) - 45
             *      C.multiplier = 8
             *      C.offset = 45
             */

            var quant = BaseQuantity.DefineNewBaseQuantity(
                "quantity", "a");

            var      a = (BaseUnit)quant.FundamentalUnit;
            BaseUnit b = new ("b", a,
                              multiplier : 2m,
                              offset : 20m);

            BaseUnit c = new ("c", b,
                              multiplier : 4m,
                              offset : 40m);


            Assert.AreEqual(1m, a.FundamentalMultiplier);
            Assert.AreEqual(0m, a.FundamentalOffset);

            Assert.AreEqual(2m, b.FundamentalMultiplier);
            Assert.AreEqual(20m, b.FundamentalOffset);

            Assert.AreEqual(8m, c.FundamentalMultiplier);
            Assert.AreEqual(45m, c.FundamentalOffset);

            {
                // Convert to fundamental
                var aAsFund = a.ConvertToFundamental(3m);
                Assert.AreEqual(3m, aAsFund.Magnitude);
                Assert.AreSame(a, aAsFund.Unit);

                var bAsFund = b.ConvertToFundamental(3m);
                Assert.AreEqual(46m, bAsFund.Magnitude);
                Assert.AreSame(a, bAsFund.Unit);

                var cAsFund = c.ConvertToFundamental(3m);
                Assert.AreEqual(384m, cAsFund.Magnitude);
                Assert.AreSame(a, cAsFund.Unit);
            }

            {
                // Convert to A
                var aAsA = a.ConvertTo(3m, a);
                Assert.AreEqual(3m, aAsA.Magnitude);
                Assert.AreSame(a, aAsA.Unit);

                var bAsA = b.ConvertToFundamental(3m);
                Assert.AreEqual(46m, bAsA.Magnitude);
                Assert.AreSame(a, bAsA.Unit);

                var cAsA = c.ConvertToFundamental(3m);
                Assert.AreEqual(384m, cAsA.Magnitude);
                Assert.AreSame(a, cAsA.Unit);
            }

            {
                // Convert to B
                var aAsB = a.ConvertTo(4m, b);
                Assert.AreEqual(-18m, aAsB.Magnitude);
                Assert.AreSame(b, aAsB.Unit);

                var bAsB = b.ConvertTo(3m, b);
                Assert.AreEqual(3m, bAsB.Magnitude);
                Assert.AreSame(b, bAsB.Unit);

                var cAsB = c.ConvertTo(2m, b);
                Assert.AreEqual(168m, cAsB.Magnitude);
                Assert.AreSame(b, cAsB.Unit);
            }

            {
                // Convert to C
                var aAsC = a.ConvertTo(16m, c);
                Assert.AreEqual(-43m, aAsC.Magnitude);
                Assert.AreSame(c, aAsC.Unit);

                var bAsC = b.ConvertTo(8m, c);
                Assert.AreEqual(-38m, bAsC.Magnitude);
                Assert.AreSame(c, bAsC.Unit);

                var cAsC = c.ConvertTo(3m, c);
                Assert.AreEqual(3m, cAsC.Magnitude);
                Assert.AreSame(c, cAsC.Unit);
            }

            Prefix testPrefix = new("TestPrefix", 10m);
            var    pA         = PrefixedUnit.GetPrefixedUnit(a, testPrefix);
            var    pB         = PrefixedUnit.GetPrefixedUnit(b, testPrefix);
            var    pC         = PrefixedUnit.GetPrefixedUnit(c, testPrefix);

            Assert.AreEqual(10m, pA.FundamentalMultiplier);
            Assert.AreEqual(0m, pA.FundamentalOffset);

            Assert.AreEqual(20m, pB.FundamentalMultiplier);
            Assert.AreEqual(2m, pB.FundamentalOffset);

            Assert.AreEqual(80m, pC.FundamentalMultiplier);
            Assert.AreEqual(4.5m, pC.FundamentalOffset);

            {
                var aAsPa = a.ConvertTo(20m, pA);
                Assert.AreEqual(2m, aAsPa.Magnitude);
                Assert.AreSame(pA, aAsPa.Unit);

                var cAsPc = c.ConvertTo(20m, pC);
                Assert.AreEqual(2m, cAsPc.Magnitude);
                Assert.AreSame(pC, cAsPc.Unit);

                var paAsA = pA.ConvertTo(2m, a);
                Assert.AreEqual(20m, paAsA.Magnitude);
                Assert.AreSame(a, paAsA.Unit);

                var pcAsC = pC.ConvertTo(2m, c);
                Assert.AreEqual(20m, pcAsC.Magnitude);
                Assert.AreSame(c, pcAsC.Unit);
            }

            {
                var aAsPc = a.ConvertTo(3200m, pC);
                Assert.AreEqual(35.5m, aAsPc.Magnitude);
                Assert.AreSame(pC, aAsPc.Unit);

                var cAsPa = c.ConvertTo(30m, pA);
                Assert.AreEqual(60m, cAsPa.Magnitude);
                Assert.AreSame(pA, cAsPa.Unit);

                var paAsC = pA.ConvertTo(60m, c);
                Assert.AreEqual(30m, paAsC.Magnitude);
                Assert.AreSame(c, paAsC.Unit);

                var pCAsA = pC.ConvertTo(35.5m, a);
                Assert.AreEqual(3200m, pCAsA.Magnitude);
                Assert.AreSame(a, pCAsA.Unit);
            }
        }
예제 #27
0
        /// <summary>
        /// Construct a unit based on the default units of the internal quantities of passed quantity instance.
        /// Dimensionless quantity will return their native sub quantities units.
        /// this connstructor is useful like when you pass torque quantity it will return "N.m"
        /// but when you use Energy Quantity it will return J.
        /// </summary>
        /// <param name="quantity"></param>
        public static Unit DiscoverUnit(BaseQuantity quantity)
        {
            Type m_QuantityType = quantity.GetType();

            var gen_q = m_QuantityType.GetGenericTypeDefinition();

            if (gen_q == typeof(Currency <>))
            {
                return(new QuantitySystem.Units.Currency.Coin());
            }
            if (gen_q == typeof(Digital <>))
            {
                return(new QuantitySystem.Units.Digital.Bit());
            }

            if (gen_q == typeof(PolarLength <>))
            {
                //because all length units associated with the Length<> Type
                m_QuantityType = typeof(Length <>).MakeGenericType(m_QuantityType.GetGenericArguments()[0]);
            }



            if (quantity.Dimension.IsDimensionless)
            {
                Type QtyType = m_QuantityType;
                if (!QtyType.IsGenericTypeDefinition)
                {
                    QtyType = QtyType.GetGenericTypeDefinition();
                }

                if (QtyType == typeof(DimensionlessQuantity <>))
                {
                    return(DiscoverUnit(QuantityDimension.Dimensionless));
                }
            }



            List <Unit> SubUnits = new List <Unit>();

            //try direct mapping first to get the unit

            Type InnerUnitType = GetDefaultSIUnitTypeOf(m_QuantityType);


            if (InnerUnitType == null) //no direct mapping so get it from the inner quantities
            {
                BaseQuantity[] InternalQuantities;

                //I can't cast BaseQuantity to AnyQuantity<object>  very annoying
                //so I used reflection.

                MethodInfo GIQ = m_QuantityType.GetMethod("GetInternalQuantities");

                //casted the array to BaseQuantity array also
                InternalQuantities = GIQ.Invoke(quantity, null) as BaseQuantity[];

                foreach (var InnerQuantity in InternalQuantities)
                {
                    //try to get the quantity direct unit
                    Type l2_InnerUnitType = GetDefaultSIUnitTypeOf(InnerQuantity.GetType());

                    if (l2_InnerUnitType == null)
                    {
                        //this means for this quantity there is no direct mapping to SI Unit
                        // so we should create unit for this quantity

                        Unit un = DiscoverUnit(InnerQuantity);
                        if (un.SubUnits != null && un.SubUnits.Count > 0)
                        {
                            SubUnits.AddRange(un.SubUnits);
                        }
                        else
                        {
                            SubUnits.Add(un);
                        }
                    }
                    else
                    {
                        //found :) create it with the exponent

                        Unit un = (Unit)Activator.CreateInstance(l2_InnerUnitType);
                        un.UnitExponent  = InnerQuantity.Exponent;
                        un.UnitDimension = InnerQuantity.Dimension;

                        SubUnits.Add(un);
                    }
                }
            }
            else
            {
                //subclass of AnyQuantity
                //use direct mapping with the exponent of the quantity

                Unit un = (Unit)Activator.CreateInstance(InnerUnitType);
                un.UnitExponent  = quantity.Exponent;
                un.UnitDimension = quantity.Dimension;

                return(un);
            }


            return(new Unit(m_QuantityType, SubUnits.ToArray()));
        }
예제 #28
0
 /// <summary>
 /// Extension method to convert radians to degrees
 /// </summary>
 /// <param name="val">quantity measured in radians</param>
 /// <returns>quantity measured in degrees</returns>
 public static Quantity <double, Degrees> ToDegrees <T>(this BaseQuantity <T, Radians> val) where T : IConvertible
 {
     return(new Quantity <double, Degrees>(
                Convert.ToDouble(val.Value) * Rad2Deg
                ));
 }