Esempio n. 1
0
 public Armor()
 {
     _varianceArmorFactor = 0.0f;
     _varianceResistance = 0.0f;
     _varianceDefenseBonus = 0;
     _storedVarianceDefenseBonus = 0;
 }
        protected internal override void Process(Single deltaSeconds, ref ParticleIterator iterator)
#endif
        {
            Single initialForceDeltaX = this.InitialForce.X * deltaSeconds;
            Single initialForceDeltaY = this.InitialForce.Y * deltaSeconds;
            Single initialForceDeltaZ = this.InitialForce.Z * deltaSeconds;

            Single finalForceDeltaX = this.FinalForce.X * deltaSeconds;
            Single finalForceDeltaY = this.FinalForce.Y * deltaSeconds;
            Single finalForceDeltaZ = this.FinalForce.Z * deltaSeconds;

            var particle = iterator.First;

            do
            {
#if UNSAFE
                particle->Velocity.X += initialForceDeltaX + ((finalForceDeltaX - initialForceDeltaX) * particle->Age);
                particle->Velocity.Y += initialForceDeltaY + ((finalForceDeltaY - initialForceDeltaY) * particle->Age);
                particle->Velocity.Z += initialForceDeltaZ + ((finalForceDeltaZ - initialForceDeltaZ) * particle->Age);
#else
                particle.Velocity.X += initialForceDeltaX + ((finalForceDeltaX - initialForceDeltaX) * particle.Age);
                particle.Velocity.Y += initialForceDeltaY + ((finalForceDeltaY - initialForceDeltaY) * particle.Age);
                particle.Velocity.Z += initialForceDeltaZ + ((finalForceDeltaZ - initialForceDeltaZ) * particle.Age);
#endif
            }
#if UNSAFE
            while (iterator.MoveNext(&particle));
#else
            while (iterator.MoveNext(ref particle));
#endif
        }
Esempio n. 3
0
 public void Add(Single value)
 {
     if(Words.Count <= 14)
     {
         Words.Add(new Word(value));
     }
 }
Esempio n. 4
0
 public BigPointsAwardedEvent(Int32 score, Single x, Single y, Boolean increasesMultiplier)
 {
     this.Score = score;
     this.X = x;
     this.Y = y;
     this.IncreasesMultiplier = increasesMultiplier;
 }
Esempio n. 5
0
        static LightingManager()
        {
            ambientLightColour = Rgba32.Black;
            emissiveColour = Rgba32.DarkSlateGrey;
            specularColour = Rgba32.DarkGrey;
            specularPower = 2f;

            fogEnabled = true;
            fogStart = 100f;
            fogEnd = 1000f;
            fogColour = Rgba32.BlueViolet;

            dirLight0Direction = new Vector3(-0.3f, -0.9f, +0.3f);
            Vector3.Normalise(ref dirLight0Direction, out dirLight0Direction);
            dirLight0DiffuseColour = Rgba32.DimGrey;
            dirLight0SpecularColour = Rgba32.DarkGreen;

            dirLight1Direction = new Vector3(0.3f, 0.1f, -0.3f);
            Vector3.Normalise(ref dirLight1Direction, out dirLight1Direction);
            dirLight1DiffuseColour = Rgba32.DimGrey;
            dirLight1SpecularColour = Rgba32.DarkRed;

            dirLight2Direction = new Vector3( -0.7f, -0.3f, +0.1f);
            Vector3.Normalise(ref dirLight2Direction, out dirLight2Direction);
            dirLight2DiffuseColour = Rgba32.DimGrey;
            dirLight2SpecularColour = Rgba32.DarkBlue;
        }
Esempio n. 6
0
 /// <summary> 
 /// Encodes the specified value, returning the result as a byte array.
 /// </summary>
 /// <param name="parameterValue">the value to Encode
 /// </param>
 /// <returns> 
 /// a byte array containing the encoded value
 /// An array of bytes with length 2.
 /// </returns>
 public static byte[] Encode(Single val)
 {
     byte[] buf = BitConverter.GetBytes(val);
     if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
         EncodingHelpers.ReverseBytes(buf);
     return buf;
 }
Esempio n. 7
0
 public static void Encode(Stream stream, Single val)
 {
     byte[] buf = BitConverter.GetBytes(val);
     if (EncodingHelpers.Endian != EndianTypes.LittleEndian)
         EncodingHelpers.ReverseBytes(buf);
     stream.Write(buf, 0, buf.Length);
 }
Esempio n. 8
0
        /// <summary>
        /// Plays the specified song.
        /// </summary>
        /// <param name="song">The song to play.</param>
        /// <param name="volume">A value from 0.0 (silent) to 1.0 (full volume) representing the song's volume.</param>
        /// <param name="pitch">A value from -1.0 (down one octave) to 1.0 (up one octave) indicating the song's pitch adjustment.</param>
        /// <param name="pan">A value from -1.0 (full left) to 1.0 (full right) representing the song's panning position.</param>
        /// <param name="loop">A value indicating whether to loop the song.</param>
        /// <returns>true if the song began playing successfully; otherwise, false.</returns>
        public override Boolean Play(Song song, Single volume, Single pitch, Single pan, Boolean loop = false)
        {
            Contract.EnsureNotDisposed(this, Disposed);
            Contract.Require(song, "song");

            return PlayInternal(song, volume, pitch, pan, loop);
        }
        public override void UnSerialize(XElement elem)
        {
            FirstStateSlot = (Byte)(Int32)elem.Attribute("slot");

            var autoComp = elem.Element("AutoComplete");
            if (autoComp != null && !autoComp.IsEmpty)
                AutoComplete = (Int32)autoComp != 0;

            var autoCompDist = elem.Element("AutoCompleteDistance");
            if (autoCompDist != null && !autoCompDist.IsEmpty)
                AutoCompleteDistance = (Single)autoCompDist;

            var autoFail = elem.Element("AutoFail");
            if (autoFail != null && !autoFail.IsEmpty)
                AutoFail = (Int32)autoFail != 0;

            var autoFailDist = elem.Element("AutoFailDistance");
            if (autoFailDist != null && !autoFailDist.IsEmpty)
                AutoFailDistance = (Single)autoFailDist;

            var contId = elem.Element("ContinentCBID");
            if (contId != null && !contId.IsEmpty)
                ContinentId = (Int32)contId;

            var laps = elem.Element("Laps");
            if (laps != null && !laps.IsEmpty)
                Laps = (Int32)laps;

            foreach (var el in elem.Elements("GenericTargetCOID"))
                if (TargetCount < 10)
                    GenericTargets[TargetCount++] = (Int64)el;
        }
Esempio n. 10
0
        public void UpdateRow(CategoryEntity category, Single fontSize, SizeF imageViewSize)
        {
            LabelView.Text = category.Name;
            
            if (category.Picture != null && category.Picture != "BsonNull")
            {
                try
                {
                    var webClient = new WebClient();
                    webClient.DownloadDataCompleted += (s, e) =>
                    {
                        var bytes = e.Result; // get the downloaded data
                            ImageView.Image = ImageHandler.BytesToImage(bytes); // convert the data to an actual image
                    };
                    webClient.DownloadDataAsync(new Uri(category.Picture));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Something went wrong loading image for cell..." + ex.Message);
                }
                
            }
     
            LabelView.Font = UIFont.FromName("HelveticaNeue-Bold", fontSize);

            ImageView.Frame = new RectangleF(0, 0, imageViewSize.Width, imageViewSize.Height);
            // Position category label below image
            LabelView.Frame = new RectangleF(0, (float) ImageView.Frame.Bottom+60, imageViewSize.Width, (float) (ContentView.Frame.Height - ImageView.Frame.Bottom));
        }
Esempio n. 11
0
		/// <summary>
		/// Plays a sound.
		/// </summary>
		/// <param name="id">The ChannelId identifing the SoundManger playing the sound and the channel number.</param>
		/// <param name="buffer">A SecondaryBuffer containing the sound to be playing.</param>
		/// <param name="frequencymultiplier">The multiplier applied the sound to change its pitch. 1.0f for no change.</param>
		/// <param name="looping">Whether the sound should loop automatically until stopped.</param>
		/// <param name="volume">The volume level of the sound.</param>
		public void Play(ChannelId id, SecondaryBuffer buffer, Single frequencymultiplier, Boolean looping, Int32 volume)
		{
			if (buffer == null) throw new ArgumentNullException("buffer");
			if (volume > (Int32)Volume.Max || volume < (Int32)Volume.Min) throw new ArgumentOutOfRangeException("volume");

			Stop();

			m_usingid = id;
			m_buffer = buffer;

			BufferPlayFlags flags = (looping == true) ? BufferPlayFlags.Looping : BufferPlayFlags.Default;

			m_buffer.Frequency = (Int32)(m_buffer.Frequency * frequencymultiplier);
			m_buffer.SetCurrentPosition(0);
			m_buffer.Pan = (Int32)Pan.Center;
			m_buffer.Volume = volume;

			m_playflags = flags;

			try
			{
				m_buffer.Play(0, flags);
			}
			catch { }
		}
Esempio n. 12
0
        /**
        * @brief 正準オイラー角の3つ組を決定する
        */
        public void canonize()
        {
            pitch = LDMathUtil.wrapPi(pitch);

            if (pitch < -LDMathUtil.PI_OVER_2)
            {
                pitch = -LDMathUtil.PI - pitch;
                heading += LDMathUtil.PI;
                bank += LDMathUtil.PI;
            }
            else if (pitch > LDMathUtil.PI_OVER_2)
            {
                pitch = LDMathUtil.PI - pitch;
                heading += LDMathUtil.PI;
                bank += LDMathUtil.PI;
            }

            // ジンバルロックのケースをチェックする
            if (Math.Abs(pitch) > LDMathUtil.PI_OVER_2 - LDMathUtil.GINBAL_TOLERANCE)
            {
                // ジンバルロック内にいる。回転を差し替える
                heading += bank;
                bank = 0.0f;
            }
            else
            {
                bank = LDMathUtil.wrapPi(bank);
            }

            heading = LDMathUtil.wrapPi(heading);
        }
 public NumericDialog(Single currentValue)
     : this()
 {
     this.numericUpDown1.Maximum = decimal.MaxValue;
     this.numericUpDown1.Minimum = decimal.MinValue;
     this.numericUpDown1.Value = Convert.ToDecimal(currentValue);
 }
Esempio n. 14
0
 public StandingsItem()
 {
     driver = new DriverInfo();
     laps = new List<LapInfo>();
     fastestlap = 0;
     lapsled = 0;
     classlapsled = 0;
     currentTrackSurface = prevTrackSurface = SurfaceTypes.NotInWorld;
     trackpct = 0;
     prevtrackpct = 0;
     prevtrackpctupdate = 0;
     speed = 0;
     prevspeed = 0;
     position = 0;
     currentlap = new LapInfo();
     sector = 0;
     sectorbegin = 0;
     pitstops = 0;
     pitstoptime = 0;
     pitstorbegin = DateTime.MinValue;
     begin = 0;
     finished = false;
     offtracksince = 0;
     positionlive = 0;
 }
Esempio n. 15
0
 public PanelDragEvent(Single positionX, Single positionY, Single deltaX, Single deltaY)
 {
     this.PositionX = positionX;
     this.PositionY = positionY;
     this.DeltaX = deltaX;
     this.DeltaY = deltaY;
 }
Esempio n. 16
0
        protected override void OnInitializing(Object initializationData)
        {
            base.OnInitializing(initializationData);

            _resource = (IRotatingArrowWorldObject)initializationData;
            this._animationSpeed = 1.0f;

            switch (ArrowDirection)
            {
                case ArrowDirection.Up:
                    SetSprite(_resource.UpSprite);
                    break;

                case ArrowDirection.Down:
                    SetSprite(_resource.DownSprite);
                    break;

                case ArrowDirection.Left:
                    SetSprite(_resource.LeftSprite);
                    break;

                case ArrowDirection.Right:
                    SetSprite(_resource.RightSprite);
                    break;

                default:
                    break;
            }
        }
 public DrawVWall(Single newPosX, Single newPosY, Single newWidth, Single newHeight)
 {
     posX = newPosX;
     posY = newPosY;
     width = newWidth;
     height = newHeight;
 }
        private static void RenderVerticalRanges(this Graphics Graphics, Rectangle ClientRectangle, Point Start, Int32 Length, Single MinimumValue, Single MaximumValue, LinearVerticalRangeDef Range)
        {
            if (!Range.Enabled)
                return;

            var valueAbsolute = Math.Abs(MaximumValue - MinimumValue);
            var scaleAdjustment = Math.Abs(Length / valueAbsolute);
            var scaleLength = (Length * scaleAdjustment);
            var rangeLength = Math.Abs((Range.End - Range.Start) * scaleAdjustment);
            var rangeStart = (Range.Start) * scaleAdjustment;
            var rangeEnd = (Range.End) * scaleAdjustment;

            Graphics.SetClip(ClientRectangle);
            Graphics.SmoothingMode = SmoothingMode.HighQuality;
            Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            var x = (Single)Start.X;
            var y = (Single)((Start.Y + ((MaximumValue - Range.End) * scaleAdjustment)));
            var width = (Single)Range.Width;
            var height = (Single)rangeLength;

            using (var solidBrush = new SolidBrush(Range.ForeColor)) {
                Graphics.FillRectangle(solidBrush, new RectangleF(x, y, width, height));
            }
        }
 public MinimumBoundingBox(Single minX, Single minY, Single maxX, Single maxY)
 {
     this.minX = minX;
     this.minY = minY;
     this.maxX = maxX;
     this.maxY = maxY;
 }
Esempio n. 20
0
 public DelayedContext(TimeSpan delay, IProcessRunner processRunner, ActionProcess actionProcess)
 {
     this._delay = delay;
     this._actionProcess = actionProcess;
     this._processRunner = processRunner;
     this._ellapsedMilliseconds = 0;
 }
Esempio n. 21
0
 internal RotateTransform(Single x, Single y, Single z, Single angle)
 {
     _x = x;
     _y = y;
     _z = z;
     _angle = angle;
 }
 public static extern NppStatus nppiAbsDiffC_32f_C1R(
     IntPtr pSrc1,
     int nSrc1Step,
     IntPtr pDst,
     int nDstStep,
     NppiSize oSizeROI,
     Npp32f nConstant);
Esempio n. 23
0
 public ColourChanger()
 {
     _current = RandomGenerator.Default.GetRandomColour();
     _target = RandomGenerator.Default.GetRandomColour();
     _colourChangeTime = RandomGenerator.Default.GetRandomSingle(3f, 10f);
     _timer = _colourChangeTime;
 }
Esempio n. 24
0
 public RectangleF(Single x, Single y, Single width, Single height)
 {
     this.X = x;
     this.Y = y;
     this.Width = width;
     this.Height = height;
 }
Esempio n. 25
0
 public RectangleF(Vector2 position, Vector2 size)
 {
     this.X = position.X;
     this.Y = position.Y;
     this.Width = size.X;
     this.Height = size.Y;
 }
Esempio n. 26
0
 /// <summary>
 /// Asserts that this vector should have the specified components.
 /// </summary>
 /// <param name="x">The expected x-component.</param>
 /// <param name="y">The expected y-component.</param>
 /// <param name="z">The expected z-component.</param>
 /// <returns>The result object.</returns>
 public Vector3Result ShouldBe(Single x, Single y, Single z)
 {
     Assert.AreEqual(x, Value.X, delta);
     Assert.AreEqual(y, Value.Y, delta);
     Assert.AreEqual(z, Value.Z, delta);
     return this;
 }
 public QuaternionReading(Single w, Single x, Single y, Single z)
 {
     W = w;
     X = x;
     Y = y;
     Z = z;
 }
Esempio n. 28
0
        Ode.Vector3 _side; // 辺

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="worldID"></param>
        /// <param name="spaceID"></param>
        /// <param name="posX"></param>
        /// <param name="posY"></param>
        /// <param name="posZ"></param>
        /// <param name="rotAxisX"></param>
        /// <param name="rotAxisY"></param>
        /// <param name="rotAxisZ"></param>
        /// <param name="rotAngle"></param>
        /// <param name="jointRotX"></param>
        /// <param name="jointRotY"></param>
        /// <param name="jointRotZ"></param>
        /// <param name="jointAxisX"></param>
        /// <param name="jointAxisY"></param>
        /// <param name="jointAxisZ"></param>
        /// <param name="mass"></param>
        /// <param name="sideX"></param>
        /// <param name="sideY"></param>
        /// <param name="sideZ"></param>
        public Box(
			WorldID worldID, SpaceID spaceID,
			Real posX, Real posY, Real posZ,
			Real rotAxisX, Real rotAxisY, Real rotAxisZ,
			Real rotAngle,
			Real jointRotX, Real jointRotY, Real jointRotZ,
			Real jointAxisX, Real jointAxisY, Real jointAxisZ,
			Real mass,
			Real sideX, Real sideY, Real sideZ
		)
        {
            Ode.Mass m;

            _worldID = worldID; _spaceID = spaceID;
            _pos.X = posX; _pos.Y = posY; _pos.Z = posZ;
            _rotAxis.X = rotAxisX; _rotAxis.Y = rotAxisY; _rotAxis.Z = rotAxisZ;
            _rotAngle = rotAngle;
            _jointRotCenter.X = jointRotX; _jointRotCenter.Y = jointRotY; _jointRotCenter.Z = jointRotZ;
            _jointRotAxis.X = jointAxisX; _jointRotAxis.Y = jointAxisY; _jointRotAxis.Z = jointAxisZ;
            _mass = mass;
            _side.X = sideX; _side.Y = sideY; _side.Z = sideZ;

            _body = Ode.BodyCreate(_worldID);

            Ode.MassSetZero(out m);											// 質量パラメータの初期化
            Ode.MassSetBoxTotal(out m, _mass, _side.X, _side.Y, _side.Z);	// 質量計算
            Ode.BodySetMass(_body, ref m);									// 質量の設定
            Ode.BodySetPosition(_body, _pos.X, _pos.Y, _pos.Z);				// 位置の設定

            Ode.Matrix3 R;
            Ode.RFromAxisAndAngle(out R, _rotAxis.X, _rotAxis.Y, _rotAxis.Z, _rotAngle);	// 回転軸・回転角から回転行列を計算
            Ode.BodySetRotation(_body, ref R);							// 回転行列を設定
            _geom = Ode.CreateBox(_spaceID, _side.X, _side.Y, _side.Z);	// ジオオメトリの生成
            Ode.GeomSetBody(_geom, _body);								// ボディとジオメトリの関連付け
        }
Esempio n. 29
0
        protected internal override void Process(Single deltaSeconds, ref ParticleIterator iterator)
#endif
        {
            Single deltaStrength = this.Strength * deltaSeconds;

            Single deltaGravityX = this.GravityVector.X * deltaStrength;
            Single deltaGravityY = this.GravityVector.Y * deltaStrength;
            Single deltaGravityZ = this.GravityVector.Z * deltaStrength;

            var particle = iterator.First;

            do
            {
#if UNSAFE
                particle->Velocity.X += deltaGravityX;
                particle->Velocity.Y += deltaGravityY;
                particle->Velocity.Z += deltaGravityZ;
#else
                particle.Velocity.X += deltaGravityX;
                particle.Velocity.Y += deltaGravityY;
                particle.Velocity.Z += deltaGravityZ;
#endif
            }
#if UNSAFE
            while (iterator.MoveNext(&particle));
#else
            while (iterator.MoveNext(ref particle));
#endif
        }
		internal static object DBSpecific(string key, Single single)
		{
			object retVal = null;
			DatabaseSpecific dext = new DatabaseSpecific();

			if (key == DatabaseSpecific.EXTENDED_PROPERTIES) 
			{
				if (single is IColumn) 
				{
					retVal = dext.ExtendedProperties(single as IColumn);
				}
				else if (single is ITable) 
				{
					retVal = dext.ExtendedProperties(single as ITable);
				}
				else if (single is IProcedure) 
				{
					retVal = dext.ExtendedProperties(single as IProcedure);
				}
				else if (single is IView) 
				{
					retVal = dext.ExtendedProperties(single as IView);
				}
			}
			
			return retVal;
		}
Esempio n. 31
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AbsorbedDose(decimal amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 32
0
        static StackObject *TryParse_18(ILIntepreter __intp, StackObject *__esp, List <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 4);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
            System.Single result = *(float *)&ptr_of_this_method->Value;
            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.IFormatProvider provider = (System.IFormatProvider) typeof(System.IFormatProvider).CheckCLRTypes(__domain, StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);
            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Globalization.NumberStyles style = (System.Globalization.NumberStyles) typeof(System.Globalization.NumberStyles).CheckCLRTypes(__domain, StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);
            ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
            System.String s = (System.String) typeof(System.String).CheckCLRTypes(__domain, StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = System.Single.TryParse(s, style, provider, out result);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            switch (ptr_of_this_method->ObjectType)
            {
            case ObjectTypes.StackObjectReference:
            {
                var dst = *(StackObject **)&ptr_of_this_method->Value;
                dst->ObjectType       = ObjectTypes.Float;
                *(float *)&dst->Value = result;
            }
            break;

            case ObjectTypes.FieldReference:
            {
                var ___obj = __mStack[ptr_of_this_method->Value];
                if (___obj is ILTypeInstance)
                {
                    ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = result;
                }
                else
                {
                    var t = __domain.GetType(___obj.GetType()) as CLRType;
                    t.GetField(ptr_of_this_method->ValueLow).SetValue(___obj, result);
                }
            }
            break;

            case ObjectTypes.StaticFieldReference:
            {
                var t = __domain.GetType(ptr_of_this_method->Value);
                if (t is ILType)
                {
                    ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = result;
                }
                else
                {
                    ((CLRType)t).GetField(ptr_of_this_method->ValueLow).SetValue(null, result);
                }
            }
            break;

            case ObjectTypes.ArrayReference:
            {
                var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Single[];
                instance_of_arrayReference[ptr_of_this_method->ValueLow] = result;
            }
            break;
            }

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Esempio n. 33
0
 public static unit getOnscreenY(unit y)
 {
     return(y - p.getCameraY() + Graphics.HEIGHT / 2 - TILE_SIZE / 2);
 }
Esempio n. 34
0
 public static unit getOnscreenX(unit x)
 {
     return(x - p.getCameraX() + Graphics.WIDTH / 2 - TILE_SIZE / 2);
 }
Esempio n. 35
0
 public static bool rectCollides(unit x1, unit y1, float width1, float height1, unit x2, unit y2, float width2, float height2)
 {
     return(!(x1 >= x2 + width2 || x1 + width1 <= x2 || y1 >= y2 + height2 || y1 + height1 <= y2));
 }
Esempio n. 36
0
 public static bool frustrumCull(unit x, unit y)
 {
     return(x < -Graphics.WIDTH / 2 || x > 3 * Graphics.WIDTH / 2 || y < -Graphics.HEIGHT / 2 || y > 3 * Graphics.HEIGHT / 2);
 }
Esempio n. 37
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AbsorbedDose(double amount)
 {
     this.amount = (AmountType)amount;
 }
        /// <inheritdoc/>
        private protected override void TrainWithoutLock(IProgressChannelProvider progress, FloatLabelCursor.Factory cursorFactory, Random rand,
                                                         IdToIdxLookup idToIdx, int numThreads, DualsTableBase duals, Float[] biasReg, Float[] invariants, Float lambdaNInv,
                                                         VBuffer <Float>[] weights, Float[] biasUnreg, VBuffer <Float>[] l1IntermediateWeights, Float[] l1IntermediateBias, Float[] featureNormSquared)
        {
            Contracts.AssertValueOrNull(progress);
            Contracts.Assert(Args.L1Threshold.HasValue);
            Contracts.AssertValueOrNull(idToIdx);
            Contracts.AssertValueOrNull(invariants);
            Contracts.AssertValueOrNull(featureNormSquared);
            int numClasses = Utils.Size(weights);

            Contracts.Assert(Utils.Size(biasReg) == numClasses);
            Contracts.Assert(Utils.Size(biasUnreg) == numClasses);

            int  maxUpdateTrials = 2 * numThreads;
            var  l1Threshold     = Args.L1Threshold.Value;
            bool l1ThresholdZero = l1Threshold == 0;
            var  lr = Args.BiasLearningRate * Args.L2Const.Value;

            var pch = progress != null?progress.StartProgressChannel("Dual update") : null;

            using (pch)
                using (var cursor = Args.Shuffle ? cursorFactory.Create(rand) : cursorFactory.Create())
                {
                    long rowCount = 0;
                    if (pch != null)
                    {
                        pch.SetHeader(new ProgressHeader("examples"), e => e.SetProgress(0, rowCount));
                    }

                    Func <RowId, long> getIndexFromId = GetIndexFromIdGetter(idToIdx, biasReg.Length);
                    while (cursor.MoveNext())
                    {
                        long  idx = getIndexFromId(cursor.Id);
                        long  dualIndexInitPos = idx * numClasses;
                        var   features         = cursor.Features;
                        var   label            = (int)cursor.Label;
                        Float invariant;
                        Float normSquared;
                        if (invariants != null)
                        {
                            invariant = invariants[idx];
                            Contracts.AssertValue(featureNormSquared);
                            normSquared = featureNormSquared[idx];
                        }
                        else
                        {
                            normSquared = VectorUtils.NormSquared(in features);
                            if (Args.BiasLearningRate == 0)
                            {
                                normSquared += 1;
                            }

                            invariant = _loss.ComputeDualUpdateInvariant(2 * normSquared * lambdaNInv * GetInstanceWeight(cursor));
                        }

                        // The output for the label class using current weights and bias.
                        var labelOutput    = WDot(in features, in weights[label], biasReg[label] + biasUnreg[label]);
                        var instanceWeight = GetInstanceWeight(cursor);

                        // This will be the new dual variable corresponding to the label class.
                        Float labelDual = 0;

                        // This will be used to update the weights and regularized bias corresponding to the label class.
                        Float labelPrimalUpdate = 0;

                        // This will be used to update the unregularized bias corresponding to the label class.
                        Float labelAdjustment = 0;

                        // Iterates through all classes.
                        for (int iClass = 0; iClass < numClasses; iClass++)
                        {
                            // Skip the dual/weights/bias update for label class. Will be taken care of at the end.
                            if (iClass == label)
                            {
                                continue;
                            }

                            var weightsEditor = VBufferEditor.CreateFromBuffer(ref weights[iClass]);
                            var l1IntermediateWeightsEditor =
                                !l1ThresholdZero?VBufferEditor.CreateFromBuffer(ref l1IntermediateWeights[iClass]) :
                                    default;

                            // Loop trials for compare-and-swap updates of duals.
                            // In general, concurrent update conflict to the same dual variable is rare
                            // if data is shuffled.
                            for (int numTrials = 0; numTrials < maxUpdateTrials; numTrials++)
                            {
                                long dualIndex  = iClass + dualIndexInitPos;
                                var  dual       = duals[dualIndex];
                                var  output     = labelOutput + labelPrimalUpdate * normSquared - WDot(in features, in weights[iClass], biasReg[iClass] + biasUnreg[iClass]);
                                var  dualUpdate = _loss.DualUpdate(output, 1, dual, invariant, numThreads);

                                // The successive over-relaxation apporach to adjust the sum of dual variables (biasReg) to zero.
                                // Reference to details: http://stat.rutgers.edu/home/tzhang/papers/ml02_dual.pdf, pp. 16-17.
                                var adjustment = l1ThresholdZero ? lr * biasReg[iClass] : lr * l1IntermediateBias[iClass];
                                dualUpdate -= adjustment;
                                bool success = false;
                                duals.ApplyAt(dualIndex, (long index, ref Float value) =>
                                              success = Interlocked.CompareExchange(ref value, dual + dualUpdate, dual) == dual);

                                if (success)
                                {
                                    // Note: dualConstraint[iClass] = lambdaNInv * (sum of duals[iClass])
                                    var primalUpdate = dualUpdate * lambdaNInv * instanceWeight;
                                    labelDual         -= dual + dualUpdate;
                                    labelPrimalUpdate += primalUpdate;
                                    biasUnreg[iClass] += adjustment * lambdaNInv * instanceWeight;
                                    labelAdjustment   -= adjustment;

                                    if (l1ThresholdZero)
                                    {
                                        VectorUtils.AddMult(in features, weightsEditor.Values, -primalUpdate);
                                        biasReg[iClass] -= primalUpdate;
                                    }
                                    else
                                    {
                                        //Iterative shrinkage-thresholding (aka. soft-thresholding)
                                        //Update v=denseWeights as if there's no L1
                                        //Thresholding: if |v[j]| < threshold, turn off weights[j]
                                        //If not, shrink: w[j] = v[i] - sign(v[j]) * threshold
                                        l1IntermediateBias[iClass] -= primalUpdate;
                                        if (Args.BiasLearningRate == 0)
                                        {
                                            biasReg[iClass] = Math.Abs(l1IntermediateBias[iClass]) - l1Threshold > 0.0
                                        ? l1IntermediateBias[iClass] - Math.Sign(l1IntermediateBias[iClass]) * l1Threshold
                                        : 0;
                                        }

                                        var featureValues = features.GetValues();
                                        if (features.IsDense)
                                        {
                                            CpuMathUtils.SdcaL1UpdateDense(-primalUpdate, featureValues.Length, featureValues, l1Threshold, l1IntermediateWeightsEditor.Values, weightsEditor.Values);
                                        }
                                        else if (featureValues.Length > 0)
                                        {
                                            CpuMathUtils.SdcaL1UpdateSparse(-primalUpdate, featureValues.Length, featureValues, features.GetIndices(), l1Threshold, l1IntermediateWeightsEditor.Values, weightsEditor.Values);
                                        }
                                    }

                                    break;
                                }
                            }
                        }

                        // Updating with label class weights and dual variable.
                        duals[label + dualIndexInitPos] = labelDual;
                        biasUnreg[label] += labelAdjustment * lambdaNInv * instanceWeight;
                        if (l1ThresholdZero)
                        {
                            var weightsEditor = VBufferEditor.CreateFromBuffer(ref weights[label]);
                            VectorUtils.AddMult(in features, weightsEditor.Values, labelPrimalUpdate);
                            biasReg[label] += labelPrimalUpdate;
                        }
                        else
                        {
                            l1IntermediateBias[label] += labelPrimalUpdate;
                            var intermediateBias = l1IntermediateBias[label];
                            biasReg[label] = Math.Abs(intermediateBias) - l1Threshold > 0.0
                            ? intermediateBias - Math.Sign(intermediateBias) * l1Threshold
                            : 0;

                            var weightsEditor = VBufferEditor.CreateFromBuffer(ref weights[label]);
                            var l1IntermediateWeightsEditor = VBufferEditor.CreateFromBuffer(ref l1IntermediateWeights[label]);
                            var featureValues = features.GetValues();
                            if (features.IsDense)
                            {
                                CpuMathUtils.SdcaL1UpdateDense(labelPrimalUpdate, featureValues.Length, featureValues, l1Threshold, l1IntermediateWeightsEditor.Values, weightsEditor.Values);
                            }
                            else if (featureValues.Length > 0)
                            {
                                CpuMathUtils.SdcaL1UpdateSparse(labelPrimalUpdate, featureValues.Length, featureValues, features.GetIndices(), l1Threshold, l1IntermediateWeightsEditor.Values, weightsEditor.Values);
                            }
                        }

                        rowCount++;
                    }
                }
        }
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AmountOfSubstance(decimal amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 40
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AbsorbedDose(float amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 41
0
        private void TrainCore(IChannel ch, RoleMappedData data)
        {
            Host.AssertValue(ch);
            ch.AssertValue(data);

            if (_rank > _dimension)
            {
                throw ch.Except("Rank ({0}) cannot be larger than the original dimension ({1})", _rank, _dimension);
            }
            int oversampledRank = Math.Min(_rank + _oversampling, _dimension);

            //exact: (size of the 2 big matrices + other minor allocations) / (2^30)
            Double memoryUsageEstimate = 2.0 * _dimension * oversampledRank * sizeof(Float) / 1e9;

            if (memoryUsageEstimate > 2)
            {
                ch.Info("Estimate memory usage: {0:G2} GB. If running out of memory, reduce rank and oversampling factor.", memoryUsageEstimate);
            }

            var y = Zeros(oversampledRank, _dimension);

            _mean = _center ? VBufferUtils.CreateDense <Float>(_dimension) : VBufferUtils.CreateEmpty <Float>(_dimension);

            var omega = GaussianMatrix(oversampledRank, _dimension, _seed);

            var  cursorFactory = new FeatureFloatVectorCursor.Factory(data, CursOpt.Features | CursOpt.Weight);
            long numBad;

            Project(Host, cursorFactory, ref _mean, omega, y, out numBad);
            if (numBad > 0)
            {
                ch.Warning("Skipped {0} instances with missing features/weights during training", numBad);
            }

            //Orthonormalize Y in-place using stabilized Gram Schmidt algorithm.
            //Ref: http://en.wikipedia.org/wiki/Gram-Schmidt#Algorithm
            for (var i = 0; i < oversampledRank; ++i)
            {
                var v = y[i];
                VectorUtils.ScaleBy(ref v, 1 / VectorUtils.Norm(y[i]));

                // Make the next vectors in the queue orthogonal to the orthonormalized vectors.
                for (var j = i + 1; j < oversampledRank; ++j) //subtract the projection of y[j] on v.
                {
                    VectorUtils.AddMult(ref v, -VectorUtils.DotProduct(ref v, ref y[j]), ref y[j]);
                }
            }
            var q = y;     // q in QR decomposition.

            var b = omega; // reuse the memory allocated by Omega.

            Project(Host, cursorFactory, ref _mean, q, b, out numBad);

            //Compute B2 = B' * B
            var b2 = new Float[oversampledRank * oversampledRank];

            for (var i = 0; i < oversampledRank; ++i)
            {
                for (var j = i; j < oversampledRank; ++j)
                {
                    b2[i * oversampledRank + j] = b2[j * oversampledRank + i] = VectorUtils.DotProduct(ref b[i], ref b[j]);
                }
            }

            Float[] smallEigenvalues;// eigenvectors and eigenvalues of the small matrix B2.
            Float[] smallEigenvectors;
            EigenUtils.EigenDecomposition(b2, out smallEigenvalues, out smallEigenvectors);
            PostProcess(b, smallEigenvalues, smallEigenvectors, _dimension, oversampledRank);
            _eigenvectors = b;
        }
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AmountOfSubstance(double amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 43
0
        /// <summary>
        /// Draw rich text at specified area.
        /// </summary>
        /// <param name="g">Graphics context.</param>
        /// <param name="bounds">Target area to draw rich text.</param>
        internal void Draw(IGraphics g, Rectangle bounds)
        {
            RGFloat x = bounds.Left + 2;
            RGFloat y = bounds.Top + 2;

            if (!this.Overflow)
            {
                g.PushClip(bounds);
            }

            switch (this.VerticalAlignment)
            {
            default:
            case ReoGridVerAlign.General:
            case ReoGridVerAlign.Bottom:
                y += (bounds.Height - this.measuredSize.Height) - 6;
                break;

            case ReoGridVerAlign.Middle:
                y += (bounds.Height - this.measuredSize.Height) / 2 - 2;
                break;

            case ReoGridVerAlign.Top:
                y++;
                break;
            }

            Run lastRun = null;

            RGBrush    lastBrush = null;
            SolidColor lastColor = SolidColor.Transparent;

#if DEBUG1
            g.DrawRectangle(System.Drawing.Pens.DarkRed, x, y, x + measuredSize.Width, y + measuredSize.Height);
#endif // DEBUG

            foreach (var p in this.paragraphs)
            {
                foreach (var l in p.lines)
                {
#if DEBUG
                    //g.DrawRectangle(System.Drawing.Pens.Blue, x, y + l.leftTop.Y, l.Width, l.Height);
#endif // DEBUG

                    foreach (var b in l.boxes)
                    {
                        var r = b.Run;

                        if (lastRun != r)
                        {
                            SolidColor textColor = r.TextColor;

                            if (textColor.IsTransparent)
                            {
                                textColor = this.DefaultTextColor;
                            }

                            if (textColor != lastColor || lastBrush == null)
                            {
                                lastColor = textColor;

#if WINFORM || ANDROID
                                if (lastBrush != null)
                                {
                                    lastBrush.Dispose();
                                }
#endif // WINFORM
                                lastBrush = new RGBrush(lastColor);
                            }

                            lastRun = r;
                        }

#if DEBUG
                        //RGFloat baseLine = l.Top + l.Ascent;
                        //g.DrawLine(System.Drawing.Pens.Blue, b.Left + 1, baseLine, b.Right - 1, baseLine);
#endif // DEBUG

                        if ((r.FontStyles & FontStyles.Underline) == FontStyles.Underline)
                        {
#if WINFORM
                            using (var underlinePen = new RGPen(lastBrush.Color))
#elif WPF
                            var underlinePen = new RGPen(new RGBrush(lastBrush.Color), 1);
#endif // WPF
                            {
                                RGFloat underlineY = l.Height + y + 1;
                                g.PlatformGraphics.DrawLine(underlinePen, new Point(b.leftTop.X + x, underlineY), new Point(b.rightTop.X + x, underlineY));
                            }
                        }

                        var tx = b.leftTop.X + x;
                        var ty = b.leftTop.Y + y;

#if WINFORM || ANDROID
                        g.PlatformGraphics.DrawString(b.Str, b.FontInfo.Font, lastBrush, tx, ty, this.sf);
#elif WPF
                        var gr = new System.Windows.Media.GlyphRun(b.FontInfo.GlyphTypeface, 0, false, r.FontSize * 1.33d,
                                                                   new ushort[] { b.GlyphIndex },
                                                                   new System.Windows.Point(tx, ty),
                                                                   new double[] { b.Width }, null, null, null, null,
                                                                   null, null);

                        g.PlatformGraphics.DrawGlyphRun(lastBrush, gr);
#endif // WPF
                    }
                }

                //y += p.TextSize.Height + this.paragraphSpacing;
            }

            if (!this.Overflow)
            {
                g.PopClip();
            }
        }
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public AmountOfSubstance(float amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 45
0
 internal void ParagraphReset()
 {
     this.currentLoc  = this.startLoc;
     this.maxBaseline = 0;
     this.maxHeight   = 0;
 }
Esempio n. 46
0
        private void CommitLine(RelayoutSession rs, Line line)
        {
            var angle = this.rt.RotationAngle;

            #region Last Line Spacing
            // if there is last line, plus the line spacing height
            if (lastLine != null)
            {
                RGFloat lineSpacing = lastLine.Height * (this.LineHeight - 1);

                if (angle == 0)
                {
                    rs.startLoc.Y += lineSpacing;
                    //line.leftTop.Y += lineSpacing;
                }
                else
                {
                    foreach (var box in line.boxes)
                    {
                        var a = (lineSpacing) * rs.s;
                        var b = (lineSpacing) * rs.c / Math.Tan(rs.d);

                        box.leftTop.X -= (float)(a + b);
                    }
                }
            }
            #endregion             // Last Line Spacing

            this.lines.Add(line);

            #region Horizontal Relayout Boxes
            var lineWidth = line.Width;

            RGFloat horAlignOffset = 0;

            var halign = this.HorizontalAlign;

            if (halign == ReoGridHorAlign.General)
            {
                halign = this.rt.DefaultHorizontalAlignment;
            }

            switch (halign)
            {
            default:
            case ReoGridHorAlign.Left:
                horAlignOffset = 0;
                break;

            case ReoGridHorAlign.Center:
                horAlignOffset = (rs.bounds.Width - lineWidth) / 2 - 3;
                break;

            case ReoGridHorAlign.Right:
                horAlignOffset = (rs.bounds.Width - lineWidth) - 4;
                break;
            }

            foreach (var b in line.boxes)
            {
                var r = b.Run;

                if (this.rt.RotationAngle == 0)
                {
                    if ((r.FontStyles & FontStyles.Superscrit) == FontStyles.Superscrit)
                    {
                        b.leftTop.Y = line.Top - b.FontInfo.LineHeight / 2;
                    }
                    else if ((r.FontStyles & FontStyles.Subscript) == FontStyles.Subscript)
                    {
                        b.leftTop.Y = line.Top + line.Height - b.FontInfo.LineHeight / 2;
                    }
                    else
                    {
                        b.leftTop.Y = line.Top - b.FontInfo.LineHeight + line.Ascent;
                    }
                }
                else
                {
                    // TODO
                    //b.leftTop.X = line.leftTop.Y - b.FontInfo.LineHeight + line.Ascent;
                }

                b.leftTop.X += horAlignOffset;
            }
            #endregion             // Horizontal Relayout Boxes

            var lineHeight = line.Height;

            if (angle == 0)
            {
                rs.startLoc.Y += lineHeight;

                if (rs.measuredSize.Width < line.Width)
                {
                    rs.measuredSize.Width = line.Width;
                }

                rs.measuredSize.Height = rs.startLoc.Y;
            }
            else
            {
                var a = (lineHeight) * rs.s;
                var b = (lineHeight) * rs.c / Math.Tan(rs.d);

                rs.startLoc.X -= (float)(a + b);

                rs.measuredSize.Width  = 200;
                rs.measuredSize.Height = 200;
            }

            rs.currentLoc = rs.startLoc;

            lastLine = line;
        }
Esempio n. 47
0
 public FloatField(string mfieldname) : base(mfieldname)
 {
     this._value   = 0;
     this.OldValue = 0;
 }
Esempio n. 48
0
 public Line(RGFloat top)
 {
     this.Top = top;
 }
Esempio n. 49
0
 public void AppendLine(System.Single value, StandardFormat format)
 {
     Append(value, format);
     AppendLine();
 }
Esempio n. 50
0
 public FloatField()
 {
     this._value   = 0;
     this.OldValue = 0;
     this.SetValue = 0;
 }
Esempio n. 51
0
        static StackObject *TryParse_14(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
            System.Single result = *(float *)&ptr_of_this_method->Value;
            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String s = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = System.Single.TryParse(s, out result);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            switch (ptr_of_this_method->ObjectType)
            {
            case ObjectTypes.StackObjectReference:
            {
                var ___dst = *(StackObject **)&ptr_of_this_method->Value;
                ___dst->ObjectType       = ObjectTypes.Float;
                *(float *)&___dst->Value = result;
            }
            break;

            case ObjectTypes.FieldReference:
            {
                var ___obj = __mStack[ptr_of_this_method->Value];
                if (___obj is ILTypeInstance)
                {
                    ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = result;
                }
                else
                {
                    var ___type = __domain.GetType(___obj.GetType()) as CLRType;
                    ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, result);
                }
            }
            break;

            case ObjectTypes.StaticFieldReference:
            {
                var ___type = __domain.GetType(ptr_of_this_method->Value);
                if (___type is ILType)
                {
                    ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = result;
                }
                else
                {
                    ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, result);
                }
            }
            break;

            case ObjectTypes.ArrayReference:
            {
                var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Single[];
                instance_of_arrayReference[ptr_of_this_method->ValueLow] = result;
            }
            break;
            }

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Esempio n. 52
0
 public FloatField(string mfieldname, string fieldDesc) : base(mfieldname, fieldDesc)
 {
     this._value   = 0;
     this.OldValue = 0;
 }
Esempio n. 53
0
 public static extern void Gemv(Layout layout, Transpose trans, int m, int n, Float alpha,
                                Float[] a, int lda, Float[] x, int incx, Float beta, Float[] y, int incy);
Esempio n. 54
0
 public void AppendLine(System.Single value)
 {
     Append(value);
     AppendLine();
 }
Esempio n. 55
0
        private Float[][] LoadDataAsDense(IChannel ch, out int[] actualRowCounts)
        {
            long crowData = GetRowCount();

            var columnData = new Float[Infos.Length][];

            actualRowCounts = new int[Infos.Length];
            int maxActualRowCount = 0;

            for (int i = 0; i < Infos.Length; i++)
            {
                var type = Infos[i].TypeSrc;
                ch.Assert(type.IsVector && type.IsKnownSizeVector);
                // Use not more than MaxRow number of rows.
                var ex = _exes[i];
                if (crowData <= ex.MaxRow)
                {
                    actualRowCounts[i] = (int)crowData;
                }
                else
                {
                    ch.Info(MessageSensitivity.Schema, "Only {0:N0} rows of column '{1}' will be used for whitening transform.", ex.MaxRow, Infos[i].Name);
                    actualRowCounts[i] = ex.MaxRow;
                }

                int cslot = type.ValueCount;
                // Check that total number of values in matrix does not exceed int.MaxValue and adjust row count if necessary.
                if ((long)cslot * actualRowCounts[i] > int.MaxValue)
                {
                    actualRowCounts[i] = int.MaxValue / cslot;
                    ch.Info(MessageSensitivity.Schema, "Only {0:N0} rows of column '{1}' will be used for whitening transform.", actualRowCounts[i], Infos[i].Name);
                }
                columnData[i] = new Float[cslot * actualRowCounts[i]];
                if (actualRowCounts[i] > maxActualRowCount)
                {
                    maxActualRowCount = actualRowCounts[i];
                }
            }
            var idxDst = new int[Infos.Length];

            var cols = new HashSet <int>(Infos.Select(info => info.Source));

            using (var cursor = Source.GetRowCursor(cols.Contains))
            {
                var getters = new ValueGetter <VBuffer <Float> > [Infos.Length];
                for (int i = 0; i < Infos.Length; i++)
                {
                    getters[i] = cursor.GetGetter <VBuffer <Float> >(Infos[i].Source);
                }
                var val  = default(VBuffer <Float>);
                int irow = 0;
                while (irow < maxActualRowCount && cursor.MoveNext())
                {
                    for (int i = 0; i < Infos.Length; i++)
                    {
                        if (irow >= actualRowCounts[i] || columnData[i].Length == 0)
                        {
                            continue;
                        }

                        getters[i](ref val);
                        val.CopyTo(columnData[i], idxDst[i]);
                        idxDst[i] += Infos[i].TypeSrc.ValueCount;
                    }
                    irow++;
                }
#if DEBUG
                for (int i = 0; i < Infos.Length; i++)
                {
                    ch.Assert(idxDst[i] == columnData[i].Length);
                }
#endif
            }

            return(columnData);
        }
Esempio n. 56
0
 public static extern void Gemm(Layout layout, Transpose transA, Transpose transB, int m, int n, int k, Float alpha,
                                Float[] a, int lda, Float[] b, int ldb, Float beta, Float[] c, int ldc);
Esempio n. 57
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public Time(decimal amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 58
0
        private void TrainModels(Float[][] columnData, int[] rowCounts, IChannel ch)
        {
            Host.AssertValue(ch);
            ch.Assert(columnData.Length == rowCounts.Length);

            for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
            {
                var ex   = _exes[iinfo];
                var data = columnData[iinfo];
                int crow = rowCounts[iinfo];
                int ccol = Infos[iinfo].TypeSrc.ValueCount;

                // Compute covariance matrix (sigma).
                var u = new Float[ccol * ccol];
                ch.Info("Computing covariance matrix...");
                Mkl.Gemm(Layout, Mkl.Transpose.Trans, Mkl.Transpose.NoTrans,
                         ccol, ccol, crow, 1 / (Float)crow, data, ccol, data, ccol, 0, u, ccol);

                ch.Info("Computing SVD...");
                var eigValues = new Float[ccol]; // Eigenvalues.
                var unconv    = new Float[ccol]; // Superdiagonal unconverged values (if any). Not used but seems to be required by MKL.
                // After the next call, values in U will be ovewritten by left eigenvectors.
                // Each column in U will be an eigenvector.
                int r = Mkl.Svd(Layout, Mkl.SvdJob.MinOvr, Mkl.SvdJob.None,
                                ccol, ccol, u, ccol, eigValues, null, ccol, null, ccol, unconv);
                ch.Assert(r == 0);
                if (r > 0)
                {
                    throw ch.Except("SVD did not converge.");
                }
                if (r < 0)
                {
                    throw ch.Except("Invalid arguments to LAPACK gesvd, error: {0}", r);
                }

                ch.Info("Scaling eigenvectors...");
                // Scale eigenvalues first so we don't have to compute sqrt for every matrix element.
                // Scaled eigenvalues are used to compute inverse transformation matrix
                // while reciprocal (eigValuesRcp) values are used to compute whitening matrix.
                for (int i = 0; i < eigValues.Length; i++)
                {
                    eigValues[i] = MathUtils.Sqrt(Math.Max(0, eigValues[i]) + ex.Epsilon);
                }
                var eigValuesRcp = new Float[eigValues.Length];
                for (int i = 0; i < eigValuesRcp.Length; i++)
                {
                    eigValuesRcp[i] = 1 / eigValues[i];
                }

                // Scale eigenvectors. Note that resulting matrix is transposed, so the scaled
                // eigenvectors are stored row-wise.
                var uScaled    = new Float[u.Length];
                var uInvScaled = new Float[u.Length];
                int isrc       = 0;
                for (int irowSrc = 0; irowSrc < ccol; irowSrc++)
                {
                    int idst = irowSrc;
                    for (int icolSrc = 0; icolSrc < ccol; icolSrc++)
                    {
                        uScaled[idst]    = u[isrc] * eigValuesRcp[icolSrc];
                        uInvScaled[idst] = u[isrc] * eigValues[icolSrc];
                        isrc++;
                        idst += ccol;
                    }
                }

                // For ZCA need to do additional multiply by U.
                if (ex.Kind == WhiteningKind.Pca)
                {
                    // Save all components for PCA. Retained components will be selected during evaluation.
                    _models[iinfo] = uScaled;
                    if (ex.SaveInv)
                    {
                        InvModels[iinfo] = uInvScaled;
                    }
                }
                else if (ex.Kind == WhiteningKind.Zca)
                {
                    _models[iinfo] = new Float[u.Length];
                    Mkl.Gemm(Layout, Mkl.Transpose.NoTrans, Mkl.Transpose.NoTrans,
                             ccol, ccol, ccol, 1, u, ccol, uScaled, ccol, 0, _models[iinfo], ccol);

                    if (ex.SaveInv)
                    {
                        InvModels[iinfo] = new Float[u.Length];
                        Mkl.Gemm(Layout, Mkl.Transpose.NoTrans, Mkl.Transpose.NoTrans,
                                 ccol, ccol, ccol, 1, u, ccol, uInvScaled, ccol, 0, InvModels[iinfo], ccol);
                    }
                }
                else
                {
                    ch.Assert(false);
                }
            }
        }
Esempio n. 59
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public Time(float amount)
 {
     this.amount = (AmountType)amount;
 }
Esempio n. 60
0
 /// <summary>
 /// Initializes a measure to the specified amount and standard unit of the measured quantity
 /// </summary>
 /// <param name="amount">Measured amount in standard unit of the specified quantity</param>
 public Time(double amount)
 {
     this.amount = (AmountType)amount;
 }