예제 #1
0
 /// <summary>
 /// Static Constructor
 /// </summary>
 static Values()
 {
     G = new Quantity(9.80665d, Acceleration.MetersPerSecondSquared);
     // TODO: Specific Gas Constant: potentially deserving of its own dimension: E M^-1 Theta^-1
     R = new Quantity(287.058d, E.Joule, M.Kilogram.Invert(), Theta.Kelvin.Invert());
     SeaLevelAirDensityQty = new Quantity(1.225d, D.KilogramPerCubicMeter);
 }
        /// <summary>
        /// Returns the calculated angle Beta, ß, given any two of <paramref name="aQty"/>,
        /// <paramref name="bQty"/>, or <paramref name="cQty"/>. If all three are provided, then
        /// the first two are selected. If one or none are provided, then an exception is thrown.
        /// </summary>
        /// <param name="aQty"></param>
        /// <param name="bQty"></param>
        /// <param name="cQty"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public IQuantity CalculateAngleBeta(IQuantity aQty = null,
            IQuantity bQty = null, IQuantity cQty = null)
        {
            VerifyAngleCalculationTriangleSides(aQty, bQty, cQty);

            var m = L.Meter;
            IQuantity betaQty = null;

            if (AreNotNull(aQty, bQty))
            {
                var a = VerifyDimensions(aQty, m);
                var b = VerifyDimensions(bQty, m);
                betaQty = ((Quantity) b/a).Atan();
            }

            if (AreNotNull(aQty, cQty))
            {
                var a = VerifyDimensions(aQty, m);
                var c = VerifyDimensions(cQty, m);
                betaQty = ((Quantity) a/c).Acos();
            }

            if (AreNotNull(bQty, cQty))
            {
                var b = VerifyDimensions(bQty, m);
                var c = VerifyDimensions(cQty, m);
                betaQty = ((Quantity) b/c).Asin();
            }

            var rad = Theta.Radian;

            return VerifyDimensions(betaQty, rad);
        }
예제 #3
0
 /// <summary>
 /// Returns the calculated Area given the <paramref name="qty"/>.
 /// </summary>
 /// <param name="qty"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public IQuantity CalculateArea(IQuantity qty,
     CircularCalculationType type = CircularCalculationType.Diameter)
 {
     return VerifyDimensions(
         CalculateAreaFromRadius(qty, type)
         ?? CalculateAreaFromDiameter(qty, type), A.SquareMeter);
 }
예제 #4
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="qty"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public IQuantity CalculateCircumference(IQuantity qty,
     CircularCalculationType type = CircularCalculationType.Diameter)
 {
     return VerifyDimensions(
         CalculateCircumferenceFromRadius(qty, type)
         ?? CalculateCircumferenceFromDiameter(qty, type), L.Meter);
 }
        /// <summary>
        /// Calculates the trajectory components at the specified <paramref name="timeQty"/>.
        /// </summary>
        /// <param name="timeQty"></param>
        /// <returns></returns>
        public IDictionary<TrajectoryComponent, IQuantity> Calculate(IQuantity timeQty)
        {
            IDictionary<TrajectoryComponent, IQuantity> results;

            TryCalculate(timeQty, out results);

            return results;
        }
예제 #6
0
		/// <summary>
		/// Copy constructor
		/// </summary>
		/// <param name="source">The quantity to copy</param>
		public Quantity(IQuantity source)
		{
			Description = source.Description;
			Dimension = source.Dimension;
			ID = source.ID;
			Unit = source.Unit;
			ValueType = source.ValueType;
		}
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="ilhQty">An initial launch height quantity.</param>
 /// <param name="vlaQty">A vertical launch angle quantity.</param>
 /// <param name="hlaQty">A horizontal launch angle quantity.</param>
 /// <param name="ivQty">An initial velocity quantity.</param>
 public TrajectoryParameters(IQuantity ilhQty, IQuantity vlaQty, IQuantity hlaQty, IQuantity ivQty)
 {
     InitialLaunchHeightQty = ilhQty;
     VerticalLaunchAngleQty = vlaQty;
     HorizontalLaunchAngleQty = hlaQty;
     InitialVelocityQty = ivQty;
     PreviousTimeQty = null;
     TimeQty = null;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="ilhQty"></param>
 /// <param name="vlaQty"></param>
 /// <param name="hlaQty"></param>
 /// <param name="ivQty"></param>
 /// <param name="projectileMassQty"></param>
 /// <param name="projectileAreaQty"></param>
 /// <param name="rhoQty">An air density (&#961;, rho) quantity.</param>
 /// <param name="cdQty"></param>
 public AtmosphericTrajectoryParameters(IQuantity ilhQty, IQuantity vlaQty, IQuantity hlaQty,
     IQuantity ivQty, IQuantity projectileMassQty, IQuantity projectileAreaQty, IQuantity rhoQty,
     IQuantity cdQty)
     : base(ilhQty, vlaQty, hlaQty, ivQty)
 {
     ProjectileMassQty = projectileMassQty;
     ProjectileAreaQty = projectileAreaQty;
     AirDensityQty = rhoQty;
     DragCoefficientQty = cdQty;
 }
예제 #9
0
        /// <summary>
        /// Protected Constructor
        /// </summary>
        protected TimeableClockBase()
        {
            const int infinite = Timeout.Infinite;
            _timer = new Timer(ProtectedTimerCallback, null, infinite, infinite);

            var s = T.Second;

            TimePerStepQty = new Quantity(1d, s);
            _timerIntervalQty = new Quantity(double.NegativeInfinity, s);
        }
        /// <summary>
        /// Calculates the <see cref="TrajectoryComponent.MaxHeight"/> component. Effectively
        /// ignores the <paramref name="timeQty"/> part, for purposes of this component.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="timeQty"></param>
        /// <returns></returns>
        public override IQuantity Calculate(ITrajectoryParameters parameters, IQuantity timeQty)
        {
            var ivv = VerifyDimensions(parameters.InitialVerticalVelocityQty, V.MetersPerSecond);

            var g = Values.G;

            // http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html#tra5
            var resultQty = (Quantity) ivv.Squared()/((Quantity) g*2d);

            return VerifyDimensions(resultQty, L.Meter);
        }
        /// <summary>
        /// Executes the operation.
        /// </summary>
        /// <param name="lhs">The LHS quantity.</param>
        /// <param name="rhs">The RHS quantity.</param>
        /// <returns>
        /// The resulting value.
        /// </returns>
        public double Execute(IQuantity lhs, IUnit rhs)
        {
            var valueUnit = lhs.Unit;
            var value = lhs.Value;
            if (!UnitHelper.AreUnitsEqual(valueUnit, rhs))
            {
                value = rhs.FromBase(valueUnit.ToBase(value));
            }

            return value;
        }
        /// <summary>
        /// Calculates the <see cref="TrajectoryComponent.MaxTime"/> component. Effectively
        /// ignores the <paramref name="timeQty"/> part, for purposes of this component.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="timeQty"></param>
        /// <returns></returns>
        public override IQuantity Calculate(ITrajectoryParameters parameters, IQuantity timeQty)
        {
            // ReSharper disable once InvertIf
            if (ReferenceEquals(null, _componentQty))
            {
                var ivv = VerifyDimensions(parameters.InitialVerticalVelocityQty, V.MetersPerSecond);
                var vla = VerifyDimensions(parameters.VerticalLaunchAngleQty, Theta.Radian);

                var g = Values.G;

                _componentQty = (2d*(Quantity) ivv*vla.Sin())/g;
            }

            return VerifyDimensions(_componentQty, T.Second);
        }
예제 #13
0
        /// <summary>
        /// Returns the <paramref name="qty"/> with verified <paramref name="dimensions"/>.
        /// </summary>
        /// <param name="qty"></param>
        /// <param name="dimensions"></param>
        /// <returns></returns>
        protected static IQuantity VerifyDimensions(IQuantity qty, params IDimension[] dimensions)
        {
            if (ReferenceEquals(null, qty))
                throw new ArgumentNullException("qty", "qty instance is expected.");

            // ReSharper disable once InvertIf
            if (!qty.Dimensions.AreCompatible(dimensions, true))
            {
                var message = string.Format("qty force dimensions incorrect expected: {{{0}}} but was: {{{1}}}",
                    string.Join(" ", from x in dimensions select x.ToString()), qty);
                throw new ArgumentException(message, "qty");
            }

            return qty;
        }
        string IQuantityFormatter.Format(IQuantity quantity)
        {
            if (quantity == null)
            {
                return string.Empty;
            }

            if (!(quantity is Acceleration))
            {
                return "wrong type";
            }

            var qty = (Acceleration)quantity;
            var culture = NumericBox.GetCulture(this);
            return qty.ToString(this.Unit, this.SymbolFormat, culture);
        }
예제 #15
0
        /// <summary>
        /// calculates air density, ρ (rho), given <paramref name="absolutePressureQty">absolute pressure,
        /// p</paramref>, <paramref name="dryAirSpecificGasConstantQty">specific gas constant for dry air,
        /// R<sub>specific</sub></paramref>, and <paramref name="temperatureQty">absolute temperature,
        /// K</paramref>.
        /// </summary>
        /// <param name="absolutePressureQty"></param>
        /// <param name="dryAirSpecificGasConstantQty"></param>
        /// <param name="temperatureQty"></param>
        /// <returns></returns>
        /// <a href="!:http://en.wikipedia.org/wiki/Density_of_air#Temperature_and_pressure" >Density of air,
        /// Temperature and pressure</a>
        public IQuantity Calculate(IQuantity absolutePressureQty,
            IQuantity dryAirSpecificGasConstantQty,
            IQuantity temperatureQty)
        {
            var kg = M.Kilogram;
            // ReSharper disable InconsistentNaming
            var K = Theta.Kelvin;

            var p = VerifyDimensions(absolutePressureQty, P.Pascal);

            var Rspecific = VerifyDimensions(dryAirSpecificGasConstantQty, E.Joule, kg.Invert(), K.Invert());

            var T = VerifyDimensions(temperatureQty, K);

            return VerifyDimensions((Quantity) p/((Quantity) Rspecific*T), kg, L.Meter.Cubed().Invert());
        }
        /// <summary>
        /// Calculates a trajectory component given <paramref name="parameters"/> and <paramref name="timeQty"/>.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="timeQty"></param>
        /// <returns></returns>
        public override IQuantity Calculate(ITrajectoryParameters parameters, IQuantity timeQty)
        {
            var m = L.Meter;
            var s = T.Second;

            var t = VerifyDimensions(timeQty, s);

            var ihv = VerifyDimensions(parameters.InitialHorizontalVelocityQty, m, s.Invert());

            /* x = ( V cos A ) t
             * Ditto re: vertical component calculations: we already have initial horizontal velocity ready.
             * This calculation intentionally ignores Forces due to aerodynamic drag. */
            var resultQty = (Quantity) ihv*t;

            // Should be left with a Length dimension.
            return VerifyDimensions(resultQty, m);
        }
        public override IQuantity Calculate(ITrajectoryParameters parameters, IQuantity timeQty)
        {
            // ReSharper disable once InvertIf
            if (ReferenceEquals(null, _componentQty))
            {
                var iv = VerifyDimensions(parameters.InitialVelocityQty, V.MetersPerSecond);
                var vla = VerifyDimensions(parameters.VerticalLaunchAngleQty, Theta.Radian);

                var g = Values.G;

                //TODO: also does not take into consideration the initial launch height, i.e. from which thrown, punted, etc.

                // Also, leverages trig identity: sin( 2 Θ ) = 2 sin( Θ ) cos( Θ )
                _componentQty = ((Quantity) iv.Squared()*((Quantity) vla*2d).Sin())/g;
            }

            return VerifyDimensions(_componentQty, L.Meter);
        }
        /// <summary>
        /// Calculates a trajectory component given <paramref name="parameters"/> and <paramref name="timeQty"/>.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="timeQty"></param>
        /// <returns></returns>
        public override IQuantity Calculate(ITrajectoryParameters parameters, IQuantity timeQty)
        {
            var m = L.Meter;
            var s = T.Second;

            var t = VerifyDimensions(timeQty, s);

            var ivv = VerifyDimensions(parameters.InitialVerticalVelocityQty, m, s.Invert());

            // TODO: TBD: Forces due to aerodynamic lift must also play a role here, but not in this "simple" component calculator...
            var g = VerifyDimensions(Values.StandardGravity, m, s.Squared().Invert());

            /* y = ( V sin A ) t - g t^2 / 2
             * Or in this case, we have already calculated the initial vertical velocity component.
             * ref: http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html#tra12 */
            var resultQty = (Quantity) ivv*t - ((Quantity) g*t.Squared())/2d;

            // Should be left with a Length dimension.
            return VerifyDimensions(resultQty, m);
        }
        /// <summary>
        /// Gets the math ml.
        /// </summary>
        /// <param name="quantity">The quantity.</param>
        /// <param name="unitFormat">The unit format.</param>
        /// <param name="multiplicationSign">The multiplication sign.</param>
        /// <returns>The root <see cref="XElement"/> node.</returns>
        public XElement GetMathML(
            IQuantity quantity,
            UnitFormat unitFormat = UnitFormat.Default,
            MultiplicationSign multiplicationSign = MultiplicationSign.Invisible)
        {
            var mn = new XElement(MathML.Mn, quantity.Value);
            var mrow = new XElement(MathML.Mrow, mn);
            var unitElement = mrow;
            if (unitFormat.HasFlag(UnitFormat.SurroundInBrackets))
            {
                var mfenced = new XElement(MathML.Mfenced, MathML.OpenLeftBracket, MathML.CloseRightBrack);
                mrow.Add(mfenced);
                unitElement = mfenced;
            }

            ExpressionToMathMLVisitor.DefaultMathMLVisitor.Visit(
                quantity.Unit.GetExpression(),
                multiplicationSign,
                unitElement);
            return new XElement(MathML.Math, new XAttribute(MathML.NamespaceAlias, MathML.Namespace), mrow);
        }
예제 #20
0
 public bool IsGreaterThan(IQuantity other)
 {
     return this.Amount > other.ConvertTo(this.Units).Amount;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MagneticFluxDensity" /> class.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 public MagneticFluxDensity(IQuantity quantity)
     : base(quantity)
 {
 }
예제 #22
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="qty"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static IQuantity CalculateRadiusFromDiameter(IQuantity qty, CircularCalculationType type)
        {
            if (!type.HasMask(CircularCalculationType.Diameter)) return null;

            // The dimension should be consistently Length, although the unit itself may be different.
            qty.VerifyDimensions(L.Meter);

            var resultQty = (Quantity) qty/2d;

            return resultQty;
        }
예제 #23
0
 private static IQuantity Add(IQuantity a, double b, Func <double, double, double> adder)
 {
     a.VerifyDimensions();
     return(new Quantity(adder(a.Value, b)));
 }
예제 #24
0
        public QuantityInfo(QuantityType quantityType, [NotNull] Enum[] units, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions)
        {
            if (quantityType == QuantityType.Undefined)
            {
                throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType));
            }
            if (units == null)
            {
                throw new ArgumentNullException(nameof(units));
            }
            if (baseUnit == null)
            {
                throw new ArgumentNullException(nameof(baseUnit));
            }
            if (zero == null)
            {
                throw new ArgumentNullException(nameof(zero));
            }
            if (baseDimensions == null)
            {
                throw new ArgumentNullException(nameof(baseDimensions));
            }

            Name           = quantityType.ToString();
            QuantityType   = quantityType;
            UnitType       = UnitEnumTypes.First(t => t.Name == $"{quantityType}Unit");
            UnitInfos      = units.Select(unit => new UnitInfo(unit)).ToArray();
            UnitNames      = UnitInfos.Select(unitInfo => unitInfo.Name).ToArray();
            Units          = units;
            BaseUnitInfo   = new UnitInfo(baseUnit);
            BaseUnit       = BaseUnitInfo.Value;
            Zero           = zero;
            ValueType      = zero.GetType();
            BaseDimensions = baseDimensions;
        }
 /// <summary>
 /// Converts the quantity to the specified unit.
 /// </summary>
 /// <param name="unit">The unit.</param>
 /// <returns>The amount of the specified unit.</returns>
 double IQuantity.ConvertTo(IQuantity unit)
 {
     return(this.ConvertTo((TypographicLength)unit));
 }
예제 #26
0
 public ParseData(string stringValue, Func <string, IQuantity> parseMethod, IQuantity quantity)
 {
     this.StringValue = stringValue;
     this.ParseMethod = parseMethod;
     this.Quantity    = quantity;
 }
예제 #27
0
 /// <summary>
 /// Converts the quantity to the specified unit.
 /// </summary>
 /// <param name="unit">The unit.</param>
 /// <returns>The amount of the specified unit.</returns>
 double IQuantity.ConvertTo(IQuantity unit)
 {
     return(this.ConvertTo((KinematicViscosity)unit));
 }
예제 #28
0
 public override IQuantity <double> From(IQuantity <double> quantity)
 {
     return(Joule.From(quantity));
 }
예제 #29
0
 /// <summary>
 /// Converts the quantity to the specified unit.
 /// </summary>
 /// <param name="unit">The unit.</param>
 /// <returns>The amount of the specified unit.</returns>
 double IQuantity.ConvertTo(IQuantity unit)
 {
     return(this.ConvertTo((Illuminance)unit));
 }
예제 #30
0
 /// <summary>
 /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
 /// </summary>
 /// <param name="quantity">A quantity to compare with this instance.</param>
 /// <returns>
 /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="quantity" /> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="quantity" />. Greater than zero This instance follows <paramref name="quantity" /> in the sort order.
 /// </returns>
 public int CompareTo(IQuantity quantity)
 {
     return QuantityHelper.CompareTo(this, quantity);
 }
예제 #31
0
 /// <summary>
 /// Determines whether the specified <see cref="IQuantity" />, is equal to this instance.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 /// <returns>
 ///   <c>true</c> if the specified <see cref="IQuantity" /> is equal to this instance; otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(IQuantity quantity)
 {
     return QuantityHelper.AreEqual(this, quantity);
 }
예제 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Quantity" /> struct.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 public Quantity(IQuantity quantity)
     : this(quantity.Value, quantity.Unit)
 {
 }
예제 #33
0
 /// <summary>
 /// Static Constructor
 /// </summary>
 static Values()
 {
     G = SiValues.G.ConvertTo(Acceleration.FeetPerSecondSquared);
     Gmph = SiValues.G.ConvertTo(Acceleration.MilesPerHourSquared);
 }
예제 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Frequency"/> class.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 public Frequency(IQuantity quantity)
     : base(quantity)
 {
 }
예제 #35
0
 /// <summary>
 /// Converts the quantity to the specified unit.
 /// </summary>
 /// <param name="unit">The unit.</param>
 /// <returns>The amount of the specified unit.</returns>
 double IQuantity.ConvertTo(IQuantity unit)
 {
     return(this.ConvertTo((Flow)unit));
 }
 private QuantitySelection selectionFrom(IQuantity quantity)
 {
     return(new QuantitySelection(_entityPathResolver.PathFor(quantity), quantity.QuantityType));
 }
예제 #37
0
 public QuantitySpecification(IReadOnlyList <ICondition> conditions, IQuantity quantity)
 {
     Conditions = conditions;
     Quantity   = quantity;
 }
        public void GetValues()
        {
            IQuantity   riverModelOutflowQuantity = simpleRiver.Outputs[0].ValueDefinition as IQuantity;
            IElementSet riverModelNodeElement     = ((ITimeSpaceOutput)simpleRiver.Outputs[0]).ElementSet();

            Input queryItem1;
            var   dischargeQuantity  = new Quantity(new Unit(PredefinedUnits.CubicMeterPerSecond), null, "Discharge");
            var   waterlevelQuantity = new Quantity(new Unit(PredefinedUnits.Meter), null, "Water Level");

            var idBasedElementSetA = new ElementSet(null, "ElmSet-A", ElementType.IdBased);

            idBasedElementSetA.AddElement(new Element("elm-1"));

            queryItem1         = new Input("discharge, to be retrieved from some output item", dischargeQuantity, idBasedElementSetA);
            queryItem1.TimeSet = new TimeSet();

            // Connect the queryItem with the first output item using a time interpolator
            TimeBufferer buffer = new TimeInterpolator((ITimeSpaceOutput)simpleRiver.Outputs[0]);

            simpleRiver.Outputs[0].AddAdaptedOutput(buffer);
            buffer.AddConsumer(queryItem1);

            simpleRiver.Validate();

            simpleRiver.Prepare();

            //IListener eventListener = new EventListener();
            //for (int i = 0; i < eventListener.GetAcceptedEventTypeCount(); i++)
            //{
            //    for (int n = 0; n < simpleRiver.GetPublishedEventTypeCount(); n++)
            //    {
            //        if (eventListener.GetAcceptedEventType(i) == simpleRiver.GetPublishedEventType(n))
            //        {
            //            simpleRiver.Subscribe(eventListener, eventListener.GetAcceptedEventType(i));
            //        }
            //    }
            //}

            double startTime = simpleRiver.TimeExtent.TimeHorizon.StampAsModifiedJulianDay;

            ITime[] times = new ITime[5];
            times[0] = new Time(startTime + 1);
            times[1] = new Time(startTime + 2);
            times[2] = new Time(startTime + 3);
            times[3] = new Time(startTime + 4);
            times[4] = new Time(startTime + 5);

            ITimeSpaceValueSet values;

            queryItem1.TimeSet.SetSingleTimeStamp(times[0].StampAsModifiedJulianDay);
            values = ((ITimeSpaceOutput)queryItem1.Provider).GetValues(queryItem1);
            Assert.AreEqual(0.55, values.GetValue(0, 0));

            queryItem1.TimeSet.SetSingleTimeStamp(times[1].StampAsModifiedJulianDay);
            values = ((ITimeSpaceOutput)queryItem1.Provider).GetValues(queryItem1);
            Assert.AreEqual(1.1, values.GetValue(0, 0));

            queryItem1.TimeSet.SetSingleTimeStamp(times[2].StampAsModifiedJulianDay);
            values = ((ITimeSpaceOutput)queryItem1.Provider).GetValues(queryItem1);
            Assert.AreEqual(1.6, values.GetValue(0, 0));

            queryItem1.TimeSet.SetSingleTimeStamp(times[3].StampAsModifiedJulianDay);
            values = ((ITimeSpaceOutput)queryItem1.Provider).GetValues(queryItem1);
            Assert.AreEqual(2.1, values.GetValue(0, 0));

            queryItem1.TimeSet.SetSingleTimeStamp(times[4].StampAsModifiedJulianDay);
            values = ((ITimeSpaceOutput)queryItem1.Provider).GetValues(queryItem1);
            Assert.AreEqual(2.6, values.GetValue(0, 0));
        }
예제 #39
0
 public override IQuantity <double> From(IQuantity <double> quantity)
 {
     return(Kilometer.From(quantity));
 }
예제 #40
0
        /// <summary>
        /// Constructs a new <see cref="PropertyManager">PropertyManager</see> from <c>object</c>
        /// of known type.
        /// </summary>
        /// <param name="obj">Object of known type.</param>
        /// <param name="allReadOnly">If true, all properties are readonly.</param>
        /// <returns>Returns new <see cref="PropertyManager">PropertyManager</see>
        /// or <c>null</c> if object's type isn't known.</returns>
        /// <remarks>A this time this method knowns following types:
        /// <list>
        /// <item><see cref="IQuantity">IQuantity</see></item>
        /// <item><see cref="IElementSet">IElementSet</see></item>
        /// <item><see cref="IDataOperation">IDataOperation</see></item>
        /// <item><see cref="ILinkableComponent">ILinkableComponent</see></item>
        /// </list>
        /// Method saves <c>obj</c> parameter to <see cref="Tag">Tag</see> property, but you can
        /// use it for any purpose.
        /// </remarks>
        public static PropertyManager ConstructPropertyManager(object obj, bool allReadOnly)
        {
            PropertyManager prop = null;

            if (obj is IQuantity)
            {
                IQuantity quantity = (IQuantity)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("Description", quantity.Description, true, "Description of this Quantity.", "General");
                prop.SetProperty("ID", quantity.ID, true, "ID of this Quantity.", "General");
                prop.SetProperty("ValueType", quantity.ValueType.ToString(), true, "Type of this Quantity's value.", "General");

                // Dimensions
                prop.SetProperty("AmountOfSubstance", quantity.Dimension.GetPower(DimensionBase.AmountOfSubstance).ToString(), true, "The amount of substance in mole.", "Dimensions");
                prop.SetProperty("Currency", quantity.Dimension.GetPower(DimensionBase.Currency).ToString(), true, "Currency in Euro.", "Dimensions");
                prop.SetProperty("ElectricCurrent", quantity.Dimension.GetPower(DimensionBase.ElectricCurrent).ToString(), true, "Electric current in ampere.", "Dimensions");
                prop.SetProperty("Length", quantity.Dimension.GetPower(DimensionBase.Length).ToString(), true, "Length in meter.", "Dimensions");
                prop.SetProperty("LuminousIntensity", quantity.Dimension.GetPower(DimensionBase.LuminousIntensity).ToString(), true, "Luminous intensity in candela.", "Dimensions");
                prop.SetProperty("Mass", quantity.Dimension.GetPower(DimensionBase.Mass).ToString(), true, "Mass in kilogram.", "Dimensions");
                prop.SetProperty("Temperature", quantity.Dimension.GetPower(DimensionBase.Temperature).ToString(), true, "Temperature in kelvin.", "Dimensions");
                prop.SetProperty("Time", quantity.Dimension.GetPower(DimensionBase.Time).ToString(), true, "Time in second.", "Dimensions");

                // Unit
                prop.SetProperty("ConversionFactorToSI", quantity.Unit.ConversionFactorToSI.ToString(), true, "Multiplicative coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("OffSetToSI", quantity.Unit.OffSetToSI.ToString(), true, "Additive coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("UnitDescription", quantity.Unit.Description, true, "Description of this unit.", "Unit");
                prop.SetProperty("UnitID", quantity.Unit.ID, true, "ID of this unit.", "Unit");
            }
            else if (obj is IElementSet)
            {
                IElementSet elementSet = (IElementSet)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("ID", elementSet.ID, true, "ID of this ElementSet", "General");
                prop.SetProperty("Version", elementSet.Version.ToString(), true, "Version of this ElementSet.", "General");
                string spatialReference = string.Empty;
                if (elementSet.SpatialReference != null)
                {
                    spatialReference = elementSet.SpatialReference.ID;
                }
                prop.SetProperty("SpatialReferenceID", spatialReference, true, "ID of this ElementSet's SpatialReference", "General");
                prop.SetProperty("Description", elementSet.Description, true, "Description of this ElementSet.", "General");
                prop.SetProperty("ElementCount", elementSet.ElementCount.ToString(), true, "Count of elements of this ElementSet.", "General");
                prop.SetProperty("ElementType", elementSet.ElementType.ToString(), true, "Type of elements in this ElementSet.", "General");
            }
            else if (obj is IDataOperation)
            {
                IDataOperation dataOperation = (IDataOperation)obj;
                prop = new PropertyManager();

                string DataOperationID = "DataOperationID";

                // small trick to avoid that some argument's name is same as DataOperationID.
                // it's not quite pure, but it works:-)
                bool conflict;
                do
                {
                    conflict = false;
                    for (int i = 0; i < dataOperation.ArgumentCount; i++)
                    {
                        if (dataOperation.GetArgument(i).Key == DataOperationID)
                        {
                            DataOperationID += " ";
                            conflict         = true;
                            break;
                        }
                    }
                }while(conflict);

                // General
                prop.SetProperty(DataOperationID, dataOperation.ID, true, "ID of this DataOperation", "General");

                // Arguments
                for (int i = 0; i < dataOperation.ArgumentCount; i++)
                {
                    IArgument arg = dataOperation.GetArgument(i);
                    prop.SetProperty(arg.Key, arg.Value, arg.ReadOnly || allReadOnly, arg.Description, "Arguments");
                }
            }
            else if (obj is ILinkableComponent)
            {
                ILinkableComponent linkableComponent = (ILinkableComponent)obj;
                prop = new PropertyManager();

                DateTime timeHorizonStart = DateTime.MinValue;
                DateTime timeHorizonEnd   = DateTime.MaxValue;
                if (linkableComponent.TimeHorizon != null)
                {
                    timeHorizonStart = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.Start.ModifiedJulianDay);
                    timeHorizonEnd   = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.End.ModifiedJulianDay);
                }

                DateTime earliestInputTime = DateTime.MinValue;
                if (linkableComponent.EarliestInputTime != null)
                {
                    earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.EarliestInputTime.ModifiedJulianDay);
                }

                // General
                prop.SetProperty("ComponentID", linkableComponent.ComponentID, true, "ID the component.", "General");
                prop.SetProperty("ComponentDescription", linkableComponent.ComponentDescription, true, "Description of this component.", "General");
                prop.SetProperty("InputExchangeItemCount", linkableComponent.InputExchangeItemCount.ToString(), true, "Number of input exchange items.", "General");
                prop.SetProperty("OutputExchangeItemCount", linkableComponent.OutputExchangeItemCount.ToString(), true, "Number of output exchange items.", "General");
                prop.SetProperty("ModelID", linkableComponent.ModelID, true, "ID of the model (model=component+data).", "General");
                prop.SetProperty("ModelDescription", linkableComponent.ModelDescription, true, "Description of the model.", "General");
                prop.SetProperty("TimeHorizonStart", timeHorizonStart.ToString(), true, "Start of component's timehorizon.", "General");
                prop.SetProperty("TimeHorizonEnd", timeHorizonEnd.ToString(), true, "End of component's timehorizon.", "General");
                prop.SetProperty("ValidationMessage", linkableComponent.Validate(), true, "Validation string generated by component. No error ocured if it's empty.", "General");
                prop.SetProperty("EarliestInputTime", earliestInputTime.ToString(), true, "Earliest time for which component needs next input.", "General");

                string implementsIManageState = obj is IManageState ? "yes" : "no";
                prop.SetProperty("ImplementsIManageState", implementsIManageState, true, "Describes whether model implements IManageState interface.", "General");
            }

            if (prop != null)
            {
                prop.Tag = obj;
            }

            return(prop);
        }
 public override void RestoreExecutionData(IMoBiContext context)
 {
     base.RestoreExecutionData(context);
     _quantity = context.Get <IQuantity>(_quantityId);
 }
예제 #42
0
 private static Constraint CheckNaN(IQuantity qty)
 {
     return double.IsNaN(qty.Value) ? Is.NaN : null;
 }
 protected override void ClearReferences()
 {
     base.ClearReferences();
     _quantity = null;
 }
예제 #44
0
 public ITrigonometryContext Function(Func<IQuantity, IQuantity> function)
 {
     Assert.That(function, Is.Not.Null);
     _actualQty = function(_startingPart.Qty);
     return this;
 }
예제 #45
0
 /// <summary>
 /// Returns a new <see cref="IQuantity"/> with <paramref name="value"/> and with the same
 /// dimensionality as <paramref name="qty"/>.
 /// </summary>
 /// <param name="qty"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static IQuantity CloneDimensions(this IQuantity qty, double value = default(double))
 {
     return(new Quantity(value, ReferenceEquals(null, qty) ?  new IDimension[0] : qty.Dimensions.ToArray()));
 }
예제 #46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializableQuantity{TQuantity}" /> class.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 protected SerializableQuantity(IQuantity quantity)
 {
     this.Value = quantity.Value;
     this.Unit  = quantity.Unit.GetNotation(CultureInfo.InvariantCulture);
 }
예제 #47
0
 /// <summary>
 /// This is the elliptical form of the same area calculation. Instead of Radius times two,
 /// we have simply <paramref name="aQty"/> times <paramref name="bQty"/>.
 /// </summary>
 /// <param name="aQty"></param>
 /// <param name="bQty"></param>
 /// <returns></returns>
 /// <a href="!:http://www.coolmath.com/reference/circles-geometry#The_area_of_a_circle" >circles geometry (the area of a circle)</a>
 public IQuantity CalculateArea(IQuantity aQty, IQuantity bQty)
 {
     return VerifyDimensions(
         CalculateEllipticalArea(aQty, bQty), A.SquareMeter);
 }
 private void updateCompartmentElementToQuantityDisplayName(PathElements pathElements, IQuantity quantity)
 {
     pathElements[PathElement.BottomCompartment] = CreatePathElementDTO(_representationInfoRepository.DisplayNameFor(quantity));
 }
예제 #49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="qty"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static IQuantity CalculateAreaFromDiameter(IQuantity qty, CircularCalculationType type)
        {
            if (!type.HasFlag(CircularCalculationType.Diameter)) return null;

            // The dimension should be consistently Length, although the unit itself may be different.
            qty.VerifyDimensions(L.Meter);

            var resultQty = (Quantity) ((Quantity) qty/2d).Squared()*Math.PI;

            return resultQty;
        }
예제 #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Energy"/> class.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 public Energy(IQuantity quantity)
     : base(quantity)
 {
 }
예제 #51
0
 public IQuantity Plus(IQuantity other)
 {
     if(null == other) return this;
       return new Quantity(Amount + other.ConvertTo(Units).Amount, Units);
 }
예제 #52
0
        /// <summary>
        ///     Try to dynamically parse a quantity string representation.
        /// </summary>
        /// <param name="formatProvider">The format provider to use for lookup. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
        /// <param name="quantityType">Type of quantity, such as <see cref="Length"/>.</param>
        /// <param name="quantityString">Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type.</param>
        /// <param name="quantity">The resulting quantity if successful, otherwise <c>default</c>.</param>
        /// <returns>The parsed quantity.</returns>
        public static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString, out IQuantity quantity)
        {
            quantity = default(IQuantity);

            if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType))
            {
                return(false);
            }

            var parser = QuantityParser.Default;

            switch (quantityType)
            {
            case Type _ when quantityType == typeof(Acceleration):
                return(parser.TryParse <Acceleration, AccelerationUnit>(quantityString, formatProvider, Acceleration.From, out quantity));

            case Type _ when quantityType == typeof(AmountOfSubstance):
                return(parser.TryParse <AmountOfSubstance, AmountOfSubstanceUnit>(quantityString, formatProvider, AmountOfSubstance.From, out quantity));

            case Type _ when quantityType == typeof(AmplitudeRatio):
                return(parser.TryParse <AmplitudeRatio, AmplitudeRatioUnit>(quantityString, formatProvider, AmplitudeRatio.From, out quantity));

            case Type _ when quantityType == typeof(Angle):
                return(parser.TryParse <Angle, AngleUnit>(quantityString, formatProvider, Angle.From, out quantity));

            case Type _ when quantityType == typeof(ApparentEnergy):
                return(parser.TryParse <ApparentEnergy, ApparentEnergyUnit>(quantityString, formatProvider, ApparentEnergy.From, out quantity));

            case Type _ when quantityType == typeof(ApparentPower):
                return(parser.TryParse <ApparentPower, ApparentPowerUnit>(quantityString, formatProvider, ApparentPower.From, out quantity));

            case Type _ when quantityType == typeof(Area):
                return(parser.TryParse <Area, AreaUnit>(quantityString, formatProvider, Area.From, out quantity));

            case Type _ when quantityType == typeof(AreaDensity):
                return(parser.TryParse <AreaDensity, AreaDensityUnit>(quantityString, formatProvider, AreaDensity.From, out quantity));

            case Type _ when quantityType == typeof(AreaMomentOfInertia):
                return(parser.TryParse <AreaMomentOfInertia, AreaMomentOfInertiaUnit>(quantityString, formatProvider, AreaMomentOfInertia.From, out quantity));

            case Type _ when quantityType == typeof(BitRate):
                return(parser.TryParse <BitRate, BitRateUnit>(quantityString, formatProvider, BitRate.From, out quantity));

            case Type _ when quantityType == typeof(BrakeSpecificFuelConsumption):
                return(parser.TryParse <BrakeSpecificFuelConsumption, BrakeSpecificFuelConsumptionUnit>(quantityString, formatProvider, BrakeSpecificFuelConsumption.From, out quantity));

            case Type _ when quantityType == typeof(Capacitance):
                return(parser.TryParse <Capacitance, CapacitanceUnit>(quantityString, formatProvider, Capacitance.From, out quantity));

            case Type _ when quantityType == typeof(CoefficientOfThermalExpansion):
                return(parser.TryParse <CoefficientOfThermalExpansion, CoefficientOfThermalExpansionUnit>(quantityString, formatProvider, CoefficientOfThermalExpansion.From, out quantity));

            case Type _ when quantityType == typeof(Density):
                return(parser.TryParse <Density, DensityUnit>(quantityString, formatProvider, Density.From, out quantity));

            case Type _ when quantityType == typeof(Duration):
                return(parser.TryParse <Duration, DurationUnit>(quantityString, formatProvider, Duration.From, out quantity));

            case Type _ when quantityType == typeof(DynamicViscosity):
                return(parser.TryParse <DynamicViscosity, DynamicViscosityUnit>(quantityString, formatProvider, DynamicViscosity.From, out quantity));

            case Type _ when quantityType == typeof(ElectricAdmittance):
                return(parser.TryParse <ElectricAdmittance, ElectricAdmittanceUnit>(quantityString, formatProvider, ElectricAdmittance.From, out quantity));

            case Type _ when quantityType == typeof(ElectricCharge):
                return(parser.TryParse <ElectricCharge, ElectricChargeUnit>(quantityString, formatProvider, ElectricCharge.From, out quantity));

            case Type _ when quantityType == typeof(ElectricChargeDensity):
                return(parser.TryParse <ElectricChargeDensity, ElectricChargeDensityUnit>(quantityString, formatProvider, ElectricChargeDensity.From, out quantity));

            case Type _ when quantityType == typeof(ElectricConductance):
                return(parser.TryParse <ElectricConductance, ElectricConductanceUnit>(quantityString, formatProvider, ElectricConductance.From, out quantity));

            case Type _ when quantityType == typeof(ElectricConductivity):
                return(parser.TryParse <ElectricConductivity, ElectricConductivityUnit>(quantityString, formatProvider, ElectricConductivity.From, out quantity));

            case Type _ when quantityType == typeof(ElectricCurrent):
                return(parser.TryParse <ElectricCurrent, ElectricCurrentUnit>(quantityString, formatProvider, ElectricCurrent.From, out quantity));

            case Type _ when quantityType == typeof(ElectricCurrentDensity):
                return(parser.TryParse <ElectricCurrentDensity, ElectricCurrentDensityUnit>(quantityString, formatProvider, ElectricCurrentDensity.From, out quantity));

            case Type _ when quantityType == typeof(ElectricCurrentGradient):
                return(parser.TryParse <ElectricCurrentGradient, ElectricCurrentGradientUnit>(quantityString, formatProvider, ElectricCurrentGradient.From, out quantity));

            case Type _ when quantityType == typeof(ElectricField):
                return(parser.TryParse <ElectricField, ElectricFieldUnit>(quantityString, formatProvider, ElectricField.From, out quantity));

            case Type _ when quantityType == typeof(ElectricInductance):
                return(parser.TryParse <ElectricInductance, ElectricInductanceUnit>(quantityString, formatProvider, ElectricInductance.From, out quantity));

            case Type _ when quantityType == typeof(ElectricPotential):
                return(parser.TryParse <ElectricPotential, ElectricPotentialUnit>(quantityString, formatProvider, ElectricPotential.From, out quantity));

            case Type _ when quantityType == typeof(ElectricPotentialAc):
                return(parser.TryParse <ElectricPotentialAc, ElectricPotentialAcUnit>(quantityString, formatProvider, ElectricPotentialAc.From, out quantity));

            case Type _ when quantityType == typeof(ElectricPotentialDc):
                return(parser.TryParse <ElectricPotentialDc, ElectricPotentialDcUnit>(quantityString, formatProvider, ElectricPotentialDc.From, out quantity));

            case Type _ when quantityType == typeof(ElectricResistance):
                return(parser.TryParse <ElectricResistance, ElectricResistanceUnit>(quantityString, formatProvider, ElectricResistance.From, out quantity));

            case Type _ when quantityType == typeof(ElectricResistivity):
                return(parser.TryParse <ElectricResistivity, ElectricResistivityUnit>(quantityString, formatProvider, ElectricResistivity.From, out quantity));

            case Type _ when quantityType == typeof(Energy):
                return(parser.TryParse <Energy, EnergyUnit>(quantityString, formatProvider, Energy.From, out quantity));

            case Type _ when quantityType == typeof(Entropy):
                return(parser.TryParse <Entropy, EntropyUnit>(quantityString, formatProvider, Entropy.From, out quantity));

            case Type _ when quantityType == typeof(Force):
                return(parser.TryParse <Force, ForceUnit>(quantityString, formatProvider, Force.From, out quantity));

            case Type _ when quantityType == typeof(ForceChangeRate):
                return(parser.TryParse <ForceChangeRate, ForceChangeRateUnit>(quantityString, formatProvider, ForceChangeRate.From, out quantity));

            case Type _ when quantityType == typeof(ForcePerLength):
                return(parser.TryParse <ForcePerLength, ForcePerLengthUnit>(quantityString, formatProvider, ForcePerLength.From, out quantity));

            case Type _ when quantityType == typeof(Frequency):
                return(parser.TryParse <Frequency, FrequencyUnit>(quantityString, formatProvider, Frequency.From, out quantity));

            case Type _ when quantityType == typeof(HeatFlux):
                return(parser.TryParse <HeatFlux, HeatFluxUnit>(quantityString, formatProvider, HeatFlux.From, out quantity));

            case Type _ when quantityType == typeof(HeatTransferCoefficient):
                return(parser.TryParse <HeatTransferCoefficient, HeatTransferCoefficientUnit>(quantityString, formatProvider, HeatTransferCoefficient.From, out quantity));

            case Type _ when quantityType == typeof(Illuminance):
                return(parser.TryParse <Illuminance, IlluminanceUnit>(quantityString, formatProvider, Illuminance.From, out quantity));

            case Type _ when quantityType == typeof(Information):
                return(parser.TryParse <Information, InformationUnit>(quantityString, formatProvider, Information.From, out quantity));

            case Type _ when quantityType == typeof(Irradiance):
                return(parser.TryParse <Irradiance, IrradianceUnit>(quantityString, formatProvider, Irradiance.From, out quantity));

            case Type _ when quantityType == typeof(Irradiation):
                return(parser.TryParse <Irradiation, IrradiationUnit>(quantityString, formatProvider, Irradiation.From, out quantity));

            case Type _ when quantityType == typeof(KinematicViscosity):
                return(parser.TryParse <KinematicViscosity, KinematicViscosityUnit>(quantityString, formatProvider, KinematicViscosity.From, out quantity));

            case Type _ when quantityType == typeof(LapseRate):
                return(parser.TryParse <LapseRate, LapseRateUnit>(quantityString, formatProvider, LapseRate.From, out quantity));

            case Type _ when quantityType == typeof(Length):
                return(parser.TryParse <Length, LengthUnit>(quantityString, formatProvider, Length.From, out quantity));

            case Type _ when quantityType == typeof(Level):
                return(parser.TryParse <Level, LevelUnit>(quantityString, formatProvider, Level.From, out quantity));

            case Type _ when quantityType == typeof(LinearDensity):
                return(parser.TryParse <LinearDensity, LinearDensityUnit>(quantityString, formatProvider, LinearDensity.From, out quantity));

            case Type _ when quantityType == typeof(LuminousFlux):
                return(parser.TryParse <LuminousFlux, LuminousFluxUnit>(quantityString, formatProvider, LuminousFlux.From, out quantity));

            case Type _ when quantityType == typeof(LuminousIntensity):
                return(parser.TryParse <LuminousIntensity, LuminousIntensityUnit>(quantityString, formatProvider, LuminousIntensity.From, out quantity));

            case Type _ when quantityType == typeof(MagneticField):
                return(parser.TryParse <MagneticField, MagneticFieldUnit>(quantityString, formatProvider, MagneticField.From, out quantity));

            case Type _ when quantityType == typeof(MagneticFlux):
                return(parser.TryParse <MagneticFlux, MagneticFluxUnit>(quantityString, formatProvider, MagneticFlux.From, out quantity));

            case Type _ when quantityType == typeof(Magnetization):
                return(parser.TryParse <Magnetization, MagnetizationUnit>(quantityString, formatProvider, Magnetization.From, out quantity));

            case Type _ when quantityType == typeof(Mass):
                return(parser.TryParse <Mass, MassUnit>(quantityString, formatProvider, Mass.From, out quantity));

            case Type _ when quantityType == typeof(MassFlow):
                return(parser.TryParse <MassFlow, MassFlowUnit>(quantityString, formatProvider, MassFlow.From, out quantity));

            case Type _ when quantityType == typeof(MassFlux):
                return(parser.TryParse <MassFlux, MassFluxUnit>(quantityString, formatProvider, MassFlux.From, out quantity));

            case Type _ when quantityType == typeof(MassMomentOfInertia):
                return(parser.TryParse <MassMomentOfInertia, MassMomentOfInertiaUnit>(quantityString, formatProvider, MassMomentOfInertia.From, out quantity));

            case Type _ when quantityType == typeof(MolarEnergy):
                return(parser.TryParse <MolarEnergy, MolarEnergyUnit>(quantityString, formatProvider, MolarEnergy.From, out quantity));

            case Type _ when quantityType == typeof(MolarEntropy):
                return(parser.TryParse <MolarEntropy, MolarEntropyUnit>(quantityString, formatProvider, MolarEntropy.From, out quantity));

            case Type _ when quantityType == typeof(Molarity):
                return(parser.TryParse <Molarity, MolarityUnit>(quantityString, formatProvider, Molarity.From, out quantity));

            case Type _ when quantityType == typeof(MolarMass):
                return(parser.TryParse <MolarMass, MolarMassUnit>(quantityString, formatProvider, MolarMass.From, out quantity));

            case Type _ when quantityType == typeof(Permeability):
                return(parser.TryParse <Permeability, PermeabilityUnit>(quantityString, formatProvider, Permeability.From, out quantity));

            case Type _ when quantityType == typeof(Permittivity):
                return(parser.TryParse <Permittivity, PermittivityUnit>(quantityString, formatProvider, Permittivity.From, out quantity));

            case Type _ when quantityType == typeof(Power):
                return(parser.TryParse <Power, PowerUnit>(quantityString, formatProvider, Power.From, out quantity));

            case Type _ when quantityType == typeof(PowerDensity):
                return(parser.TryParse <PowerDensity, PowerDensityUnit>(quantityString, formatProvider, PowerDensity.From, out quantity));

            case Type _ when quantityType == typeof(PowerRatio):
                return(parser.TryParse <PowerRatio, PowerRatioUnit>(quantityString, formatProvider, PowerRatio.From, out quantity));

            case Type _ when quantityType == typeof(Pressure):
                return(parser.TryParse <Pressure, PressureUnit>(quantityString, formatProvider, Pressure.From, out quantity));

            case Type _ when quantityType == typeof(PressureChangeRate):
                return(parser.TryParse <PressureChangeRate, PressureChangeRateUnit>(quantityString, formatProvider, PressureChangeRate.From, out quantity));

            case Type _ when quantityType == typeof(Ratio):
                return(parser.TryParse <Ratio, RatioUnit>(quantityString, formatProvider, Ratio.From, out quantity));

            case Type _ when quantityType == typeof(ReactiveEnergy):
                return(parser.TryParse <ReactiveEnergy, ReactiveEnergyUnit>(quantityString, formatProvider, ReactiveEnergy.From, out quantity));

            case Type _ when quantityType == typeof(ReactivePower):
                return(parser.TryParse <ReactivePower, ReactivePowerUnit>(quantityString, formatProvider, ReactivePower.From, out quantity));

            case Type _ when quantityType == typeof(RotationalAcceleration):
                return(parser.TryParse <RotationalAcceleration, RotationalAccelerationUnit>(quantityString, formatProvider, RotationalAcceleration.From, out quantity));

            case Type _ when quantityType == typeof(RotationalSpeed):
                return(parser.TryParse <RotationalSpeed, RotationalSpeedUnit>(quantityString, formatProvider, RotationalSpeed.From, out quantity));

            case Type _ when quantityType == typeof(RotationalStiffness):
                return(parser.TryParse <RotationalStiffness, RotationalStiffnessUnit>(quantityString, formatProvider, RotationalStiffness.From, out quantity));

            case Type _ when quantityType == typeof(RotationalStiffnessPerLength):
                return(parser.TryParse <RotationalStiffnessPerLength, RotationalStiffnessPerLengthUnit>(quantityString, formatProvider, RotationalStiffnessPerLength.From, out quantity));

            case Type _ when quantityType == typeof(SolidAngle):
                return(parser.TryParse <SolidAngle, SolidAngleUnit>(quantityString, formatProvider, SolidAngle.From, out quantity));

            case Type _ when quantityType == typeof(SpecificEnergy):
                return(parser.TryParse <SpecificEnergy, SpecificEnergyUnit>(quantityString, formatProvider, SpecificEnergy.From, out quantity));

            case Type _ when quantityType == typeof(SpecificEntropy):
                return(parser.TryParse <SpecificEntropy, SpecificEntropyUnit>(quantityString, formatProvider, SpecificEntropy.From, out quantity));

            case Type _ when quantityType == typeof(SpecificVolume):
                return(parser.TryParse <SpecificVolume, SpecificVolumeUnit>(quantityString, formatProvider, SpecificVolume.From, out quantity));

            case Type _ when quantityType == typeof(SpecificWeight):
                return(parser.TryParse <SpecificWeight, SpecificWeightUnit>(quantityString, formatProvider, SpecificWeight.From, out quantity));

            case Type _ when quantityType == typeof(Speed):
                return(parser.TryParse <Speed, SpeedUnit>(quantityString, formatProvider, Speed.From, out quantity));

            case Type _ when quantityType == typeof(Temperature):
                return(parser.TryParse <Temperature, TemperatureUnit>(quantityString, formatProvider, Temperature.From, out quantity));

            case Type _ when quantityType == typeof(TemperatureChangeRate):
                return(parser.TryParse <TemperatureChangeRate, TemperatureChangeRateUnit>(quantityString, formatProvider, TemperatureChangeRate.From, out quantity));

            case Type _ when quantityType == typeof(TemperatureDelta):
                return(parser.TryParse <TemperatureDelta, TemperatureDeltaUnit>(quantityString, formatProvider, TemperatureDelta.From, out quantity));

            case Type _ when quantityType == typeof(ThermalConductivity):
                return(parser.TryParse <ThermalConductivity, ThermalConductivityUnit>(quantityString, formatProvider, ThermalConductivity.From, out quantity));

            case Type _ when quantityType == typeof(ThermalResistance):
                return(parser.TryParse <ThermalResistance, ThermalResistanceUnit>(quantityString, formatProvider, ThermalResistance.From, out quantity));

            case Type _ when quantityType == typeof(Torque):
                return(parser.TryParse <Torque, TorqueUnit>(quantityString, formatProvider, Torque.From, out quantity));

            case Type _ when quantityType == typeof(VitaminA):
                return(parser.TryParse <VitaminA, VitaminAUnit>(quantityString, formatProvider, VitaminA.From, out quantity));

            case Type _ when quantityType == typeof(Volume):
                return(parser.TryParse <Volume, VolumeUnit>(quantityString, formatProvider, Volume.From, out quantity));

            case Type _ when quantityType == typeof(VolumeFlow):
                return(parser.TryParse <VolumeFlow, VolumeFlowUnit>(quantityString, formatProvider, VolumeFlow.From, out quantity));

            case Type _ when quantityType == typeof(VolumePerLength):
                return(parser.TryParse <VolumePerLength, VolumePerLengthUnit>(quantityString, formatProvider, VolumePerLength.From, out quantity));

            default:
                return(false);
            }
        }
        /**
         * Returns the ValueSet that corresponds to requestTime.
         */
        public IValueSet GetValues(ITime requestedTime, IQuantity quantity, IElementSet elementSet, PrefetchManager prefetchManager, ILink link)
        {
            try
            {
                // generate the key of the buffer entry we're looking for
                var key = ValueSetEntry.CreateKey(webServiceManager.FindServiceIdForQuantity(quantity.ID), quantity.ID, elementSet.ID, requestedTime, scenarioId);

                traceFile.Append("GetValues: " + key);

                var mapValueSet = client.getMap<string, ValueSetEntry>("valueSet");
                var mapElementSet = client.getMap<string, ElementSetEntry>("elementSet");
                var queueValueSetRequest = client.getQueue<ValueSetRequestEntry>("valueSetRequest");

                // record this request
                statistics.Add("GetValuesCount", 1);

                // measure our wait time
                var waitStopwatch = Stopwatch.StartNew();

                // see if the requested values are in the cache
                var valueSetEntry = mapValueSet.get(key);

                // if the value set does not exist then request it
                if (valueSetEntry == null)
                {
                    traceFile.Append("Requesting Value Set: " + key);

                    // insert the element set if necessary
                    if (elementSetsPut.Contains(elementSet.ID) == false)
                    {
                        elementSetsPut.Add(elementSet.ID);
                        mapElementSet.put(elementSet.ID, new ElementSetEntry(elementSet));
                    }

                    while (valueSetEntry == null)
                    {
                        // if we're prefetching, we may have already requested this
                        // value set in a previous prefetch that hasn't been fulfilled
                        // yet in which case we do not want to issue the request again.
                        if (prefetchManager.timeIsFetched(link, (TimeStamp)requestedTime) == false)
                        {
                            // insert the request into the queue
                            var insertRequestStopwatch = Stopwatch.StartNew();

                            // create the request entry
                            var valueSetRequestEntry = new ValueSetRequestEntry(webServiceManager.FindServiceIdForQuantity(quantity.ID), quantity.ID, elementSet.ID, Utils.ITimeToDateTime(requestedTime), scenarioId);

                            // BLOCKING
                            queueValueSetRequest.put(valueSetRequestEntry);

                            statistics.Add("RequestInsertTimeMS", insertRequestStopwatch.ElapsedMilliseconds);
                            traceFile.Append("RequestInsertTime:" + string.Format("{0:0.0}", insertRequestStopwatch.ElapsedMilliseconds) + "ms");
                        }

                        // PERFORMANCE STUDY: start delay at 100 and double each time
                        // we check and it's not available

                        // poll for the value set
                        var delay = 1000;
                        while (true)
                        {
                            // we know that the value set is not in the cache since
                            // we just checked that above, so wait immediately after
                            // making the request
                            Thread.Sleep(delay);

                            valueSetEntry = mapValueSet.get(key);
                            if (valueSetEntry != null)
                            {
                                break;
                            }
                            //delay *= 2;
                            traceFile.Append(string.Format("Waiting ({0}) For Value Set: ({1})", delay, key));

                            if (delay > 20000)
                            {
                                statistics.Add("RequestRetry", 1);
                                break;
                            }
                        }
                    }
                }

                statistics.Add("CacheWaitTimeMS", waitStopwatch.ElapsedMilliseconds);
                traceFile.Append("WaitTime:" + string.Format("{0:0.0}", waitStopwatch.ElapsedMilliseconds) + "ms");

                return new ScalarSet(valueSetEntry.Values());
            }
            catch (Exception e)
            {
                traceFile.Exception(e);
                return null;
            }
        }
예제 #54
0
        /// <summary>
        ///     Try to dynamically construct a quantity.
        /// </summary>
        /// <param name="value">Numeric value.</param>
        /// <param name="unit">Unit enum value.</param>
        /// <param name="quantity">The resulting quantity if successful, otherwise <c>default</c>.</param>
        /// <returns><c>True</c> if successful with <paramref name="quantity"/> assigned the value, otherwise <c>false</c>.</returns>
        public static bool TryFrom(QuantityValue value, Enum unit, out IQuantity quantity)
        {
            switch (unit)
            {
            case AccelerationUnit accelerationUnit:
                quantity = Acceleration.From(value, accelerationUnit);
                return(true);

            case AmountOfSubstanceUnit amountOfSubstanceUnit:
                quantity = AmountOfSubstance.From(value, amountOfSubstanceUnit);
                return(true);

            case AmplitudeRatioUnit amplitudeRatioUnit:
                quantity = AmplitudeRatio.From(value, amplitudeRatioUnit);
                return(true);

            case AngleUnit angleUnit:
                quantity = Angle.From(value, angleUnit);
                return(true);

            case ApparentEnergyUnit apparentEnergyUnit:
                quantity = ApparentEnergy.From(value, apparentEnergyUnit);
                return(true);

            case ApparentPowerUnit apparentPowerUnit:
                quantity = ApparentPower.From(value, apparentPowerUnit);
                return(true);

            case AreaUnit areaUnit:
                quantity = Area.From(value, areaUnit);
                return(true);

            case AreaDensityUnit areaDensityUnit:
                quantity = AreaDensity.From(value, areaDensityUnit);
                return(true);

            case AreaMomentOfInertiaUnit areaMomentOfInertiaUnit:
                quantity = AreaMomentOfInertia.From(value, areaMomentOfInertiaUnit);
                return(true);

            case BitRateUnit bitRateUnit:
                quantity = BitRate.From(value, bitRateUnit);
                return(true);

            case BrakeSpecificFuelConsumptionUnit brakeSpecificFuelConsumptionUnit:
                quantity = BrakeSpecificFuelConsumption.From(value, brakeSpecificFuelConsumptionUnit);
                return(true);

            case CapacitanceUnit capacitanceUnit:
                quantity = Capacitance.From(value, capacitanceUnit);
                return(true);

            case CoefficientOfThermalExpansionUnit coefficientOfThermalExpansionUnit:
                quantity = CoefficientOfThermalExpansion.From(value, coefficientOfThermalExpansionUnit);
                return(true);

            case DensityUnit densityUnit:
                quantity = Density.From(value, densityUnit);
                return(true);

            case DurationUnit durationUnit:
                quantity = Duration.From(value, durationUnit);
                return(true);

            case DynamicViscosityUnit dynamicViscosityUnit:
                quantity = DynamicViscosity.From(value, dynamicViscosityUnit);
                return(true);

            case ElectricAdmittanceUnit electricAdmittanceUnit:
                quantity = ElectricAdmittance.From(value, electricAdmittanceUnit);
                return(true);

            case ElectricChargeUnit electricChargeUnit:
                quantity = ElectricCharge.From(value, electricChargeUnit);
                return(true);

            case ElectricChargeDensityUnit electricChargeDensityUnit:
                quantity = ElectricChargeDensity.From(value, electricChargeDensityUnit);
                return(true);

            case ElectricConductanceUnit electricConductanceUnit:
                quantity = ElectricConductance.From(value, electricConductanceUnit);
                return(true);

            case ElectricConductivityUnit electricConductivityUnit:
                quantity = ElectricConductivity.From(value, electricConductivityUnit);
                return(true);

            case ElectricCurrentUnit electricCurrentUnit:
                quantity = ElectricCurrent.From(value, electricCurrentUnit);
                return(true);

            case ElectricCurrentDensityUnit electricCurrentDensityUnit:
                quantity = ElectricCurrentDensity.From(value, electricCurrentDensityUnit);
                return(true);

            case ElectricCurrentGradientUnit electricCurrentGradientUnit:
                quantity = ElectricCurrentGradient.From(value, electricCurrentGradientUnit);
                return(true);

            case ElectricFieldUnit electricFieldUnit:
                quantity = ElectricField.From(value, electricFieldUnit);
                return(true);

            case ElectricInductanceUnit electricInductanceUnit:
                quantity = ElectricInductance.From(value, electricInductanceUnit);
                return(true);

            case ElectricPotentialUnit electricPotentialUnit:
                quantity = ElectricPotential.From(value, electricPotentialUnit);
                return(true);

            case ElectricPotentialAcUnit electricPotentialAcUnit:
                quantity = ElectricPotentialAc.From(value, electricPotentialAcUnit);
                return(true);

            case ElectricPotentialDcUnit electricPotentialDcUnit:
                quantity = ElectricPotentialDc.From(value, electricPotentialDcUnit);
                return(true);

            case ElectricResistanceUnit electricResistanceUnit:
                quantity = ElectricResistance.From(value, electricResistanceUnit);
                return(true);

            case ElectricResistivityUnit electricResistivityUnit:
                quantity = ElectricResistivity.From(value, electricResistivityUnit);
                return(true);

            case EnergyUnit energyUnit:
                quantity = Energy.From(value, energyUnit);
                return(true);

            case EntropyUnit entropyUnit:
                quantity = Entropy.From(value, entropyUnit);
                return(true);

            case ForceUnit forceUnit:
                quantity = Force.From(value, forceUnit);
                return(true);

            case ForceChangeRateUnit forceChangeRateUnit:
                quantity = ForceChangeRate.From(value, forceChangeRateUnit);
                return(true);

            case ForcePerLengthUnit forcePerLengthUnit:
                quantity = ForcePerLength.From(value, forcePerLengthUnit);
                return(true);

            case FrequencyUnit frequencyUnit:
                quantity = Frequency.From(value, frequencyUnit);
                return(true);

            case HeatFluxUnit heatFluxUnit:
                quantity = HeatFlux.From(value, heatFluxUnit);
                return(true);

            case HeatTransferCoefficientUnit heatTransferCoefficientUnit:
                quantity = HeatTransferCoefficient.From(value, heatTransferCoefficientUnit);
                return(true);

            case IlluminanceUnit illuminanceUnit:
                quantity = Illuminance.From(value, illuminanceUnit);
                return(true);

            case InformationUnit informationUnit:
                quantity = Information.From(value, informationUnit);
                return(true);

            case IrradianceUnit irradianceUnit:
                quantity = Irradiance.From(value, irradianceUnit);
                return(true);

            case IrradiationUnit irradiationUnit:
                quantity = Irradiation.From(value, irradiationUnit);
                return(true);

            case KinematicViscosityUnit kinematicViscosityUnit:
                quantity = KinematicViscosity.From(value, kinematicViscosityUnit);
                return(true);

            case LapseRateUnit lapseRateUnit:
                quantity = LapseRate.From(value, lapseRateUnit);
                return(true);

            case LengthUnit lengthUnit:
                quantity = Length.From(value, lengthUnit);
                return(true);

            case LevelUnit levelUnit:
                quantity = Level.From(value, levelUnit);
                return(true);

            case LinearDensityUnit linearDensityUnit:
                quantity = LinearDensity.From(value, linearDensityUnit);
                return(true);

            case LuminousFluxUnit luminousFluxUnit:
                quantity = LuminousFlux.From(value, luminousFluxUnit);
                return(true);

            case LuminousIntensityUnit luminousIntensityUnit:
                quantity = LuminousIntensity.From(value, luminousIntensityUnit);
                return(true);

            case MagneticFieldUnit magneticFieldUnit:
                quantity = MagneticField.From(value, magneticFieldUnit);
                return(true);

            case MagneticFluxUnit magneticFluxUnit:
                quantity = MagneticFlux.From(value, magneticFluxUnit);
                return(true);

            case MagnetizationUnit magnetizationUnit:
                quantity = Magnetization.From(value, magnetizationUnit);
                return(true);

            case MassUnit massUnit:
                quantity = Mass.From(value, massUnit);
                return(true);

            case MassFlowUnit massFlowUnit:
                quantity = MassFlow.From(value, massFlowUnit);
                return(true);

            case MassFluxUnit massFluxUnit:
                quantity = MassFlux.From(value, massFluxUnit);
                return(true);

            case MassMomentOfInertiaUnit massMomentOfInertiaUnit:
                quantity = MassMomentOfInertia.From(value, massMomentOfInertiaUnit);
                return(true);

            case MolarEnergyUnit molarEnergyUnit:
                quantity = MolarEnergy.From(value, molarEnergyUnit);
                return(true);

            case MolarEntropyUnit molarEntropyUnit:
                quantity = MolarEntropy.From(value, molarEntropyUnit);
                return(true);

            case MolarityUnit molarityUnit:
                quantity = Molarity.From(value, molarityUnit);
                return(true);

            case MolarMassUnit molarMassUnit:
                quantity = MolarMass.From(value, molarMassUnit);
                return(true);

            case PermeabilityUnit permeabilityUnit:
                quantity = Permeability.From(value, permeabilityUnit);
                return(true);

            case PermittivityUnit permittivityUnit:
                quantity = Permittivity.From(value, permittivityUnit);
                return(true);

            case PowerUnit powerUnit:
                quantity = Power.From(value, powerUnit);
                return(true);

            case PowerDensityUnit powerDensityUnit:
                quantity = PowerDensity.From(value, powerDensityUnit);
                return(true);

            case PowerRatioUnit powerRatioUnit:
                quantity = PowerRatio.From(value, powerRatioUnit);
                return(true);

            case PressureUnit pressureUnit:
                quantity = Pressure.From(value, pressureUnit);
                return(true);

            case PressureChangeRateUnit pressureChangeRateUnit:
                quantity = PressureChangeRate.From(value, pressureChangeRateUnit);
                return(true);

            case RatioUnit ratioUnit:
                quantity = Ratio.From(value, ratioUnit);
                return(true);

            case ReactiveEnergyUnit reactiveEnergyUnit:
                quantity = ReactiveEnergy.From(value, reactiveEnergyUnit);
                return(true);

            case ReactivePowerUnit reactivePowerUnit:
                quantity = ReactivePower.From(value, reactivePowerUnit);
                return(true);

            case RotationalAccelerationUnit rotationalAccelerationUnit:
                quantity = RotationalAcceleration.From(value, rotationalAccelerationUnit);
                return(true);

            case RotationalSpeedUnit rotationalSpeedUnit:
                quantity = RotationalSpeed.From(value, rotationalSpeedUnit);
                return(true);

            case RotationalStiffnessUnit rotationalStiffnessUnit:
                quantity = RotationalStiffness.From(value, rotationalStiffnessUnit);
                return(true);

            case RotationalStiffnessPerLengthUnit rotationalStiffnessPerLengthUnit:
                quantity = RotationalStiffnessPerLength.From(value, rotationalStiffnessPerLengthUnit);
                return(true);

            case SolidAngleUnit solidAngleUnit:
                quantity = SolidAngle.From(value, solidAngleUnit);
                return(true);

            case SpecificEnergyUnit specificEnergyUnit:
                quantity = SpecificEnergy.From(value, specificEnergyUnit);
                return(true);

            case SpecificEntropyUnit specificEntropyUnit:
                quantity = SpecificEntropy.From(value, specificEntropyUnit);
                return(true);

            case SpecificVolumeUnit specificVolumeUnit:
                quantity = SpecificVolume.From(value, specificVolumeUnit);
                return(true);

            case SpecificWeightUnit specificWeightUnit:
                quantity = SpecificWeight.From(value, specificWeightUnit);
                return(true);

            case SpeedUnit speedUnit:
                quantity = Speed.From(value, speedUnit);
                return(true);

            case TemperatureUnit temperatureUnit:
                quantity = Temperature.From(value, temperatureUnit);
                return(true);

            case TemperatureChangeRateUnit temperatureChangeRateUnit:
                quantity = TemperatureChangeRate.From(value, temperatureChangeRateUnit);
                return(true);

            case TemperatureDeltaUnit temperatureDeltaUnit:
                quantity = TemperatureDelta.From(value, temperatureDeltaUnit);
                return(true);

            case ThermalConductivityUnit thermalConductivityUnit:
                quantity = ThermalConductivity.From(value, thermalConductivityUnit);
                return(true);

            case ThermalResistanceUnit thermalResistanceUnit:
                quantity = ThermalResistance.From(value, thermalResistanceUnit);
                return(true);

            case TorqueUnit torqueUnit:
                quantity = Torque.From(value, torqueUnit);
                return(true);

            case VitaminAUnit vitaminAUnit:
                quantity = VitaminA.From(value, vitaminAUnit);
                return(true);

            case VolumeUnit volumeUnit:
                quantity = Volume.From(value, volumeUnit);
                return(true);

            case VolumeFlowUnit volumeFlowUnit:
                quantity = VolumeFlow.From(value, volumeFlowUnit);
                return(true);

            case VolumePerLengthUnit volumePerLengthUnit:
                quantity = VolumePerLength.From(value, volumePerLengthUnit);
                return(true);

            default:
            {
                quantity = default(IQuantity);
                return(false);
            }
            }
        }
 private void adjustDisplayPathForTotalFractionOfDose(PathElements pathElements, IQuantity quantity)
 {
     pathElements[PathElement.Container]    = pathElements[PathElement.TopContainer];
     pathElements[PathElement.TopContainer] = new PathElementDTO();
 }
예제 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MagneticFlux" /> class.
 /// </summary>
 /// <param name="quantity">The quantity.</param>
 public MagneticFlux(IQuantity quantity)
     : base(quantity)
 {
 }
예제 #57
0
 private Constraint CheckValue(IQuantity qty)
 {
     return HasEpsilon
         ? Is.EqualTo(qty.Value).Within(Epsilon)
         : Is.EqualTo(qty.Value);
 }
        private void adjustDisplayPathForNeighborhood(PathElements pathElements, IQuantity quantity)
        {
            var neighborhood = quantity.NeighborhoodAncestor();

            pathElements[PathElement.Container] = CreatePathElementDTO(neighborhood.FirstNeighbor.ParentContainer);
        }
예제 #59
0
        private static Constraint CheckInfinity(IQuantity qty)
        {
            var result = double.IsPositiveInfinity(qty.Value)
                ? Is.EqualTo(double.PositiveInfinity)
                : null;

            return result ?? (double.IsNegativeInfinity(qty.Value)
                ? Is.EqualTo(double.NegativeInfinity)
                : null);
        }
 private void adjustDisplayPathForContainerObserver(PathElements pathElements, IQuantity quantity)
 {
     updateCompartmentElementToQuantityDisplayName(pathElements, quantity);
     updateNameElementToQuantityDimensionName(pathElements, quantity);
 }