Ejemplo n.º 1
0
        public void Initialize_Clusters()
        {
            var x = new double[10][];

            for (int i = 0; i < x.Length; i++)
            {
                x[i] = new double[5];
            }
            ClusterData             d       = new ClusterData(x, new string[] { "a1", "a2", "a3", "a4", "a5" });
            ClusterAlgorithmOptions options = new ClusterAlgorithmOptions(3, 123, true, 10);
            //should provide initialized mean values and assignment

            ClusterResult r = KmeansClusterAlgorithm.InitializeClusters(d, options);

            int[] count = new int[3];
            for (int i = 0; i < d.RawData.Length; i++)
            {
                int idx = r.ClusterAssignment[i];
                count[idx] += 1;
            }
            for (int i = 0; i < options.NumberOfClusters; i++)
            {
                //check if every cluster received at least one data point
                Assert.IsTrue(count[i] > 0);
                //check if the column mean values are initialized
                Assert.IsTrue(r.ClusterMeanValues[i].Length == d.RawData[0].Length);
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Helper method to convert a <see cref="ClusterData"/> instance
 /// to a <see cref="ClusterInfo"/> instance.
 /// </summary>
 /// <param name="data">The data instance.</param>
 /// <returns>The converted data.</returns>
 public static ClusterInfo ToClusterInfo(this ClusterData data)
 {
     return(new ClusterInfo()
     {
         /* TODO: Finish ToClusterinfo?. [peter, 14.08.2018] */
     });
 }
Ejemplo n.º 3
0
    static int set_Complete(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData obj = (ClusterData)o;
            System.Action <UnityEngine.GameObject> arg0 = null;
            LuaTypes funcType2 = LuaDLL.lua_type(L, 2);

            if (funcType2 != LuaTypes.LUA_TFUNCTION)
            {
                arg0 = (System.Action <UnityEngine.GameObject>)ToLua.CheckObject(L, 2, typeof(System.Action <UnityEngine.GameObject>));
            }
            else
            {
                LuaFunction func = ToLua.ToLuaFunction(L, 2);
                arg0 = DelegateFactory.CreateDelegate(typeof(System.Action <UnityEngine.GameObject>), func) as System.Action <UnityEngine.GameObject>;
            }

            obj.Complete = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Complete on a nil value" : e.Message));
        }
    }
Ejemplo n.º 4
0
        public void Assign_Clusters()
        {
            var o = new ClusterAlgorithmOptions(2);

            ClusterData cd = new ClusterData(new double[3][] { new double[2], new double[2], new double[2] }, new string[2]);

            ClusterResult cr = new ClusterResult();

            cr.ClusterAssignment = new int[3] {
                0, 1, 0
            };
            cr.ClusterMeanValues    = new double[2][];
            cr.ClusterMeanValues[0] = new double[2] {
                100, 1000
            };
            cr.ClusterMeanValues[1] = new double[2] {
                5, 10
            };
            cr.NormalizedData    = new double[3][];
            cr.NormalizedData[0] = new double[2] {
                80, 900
            };
            cr.NormalizedData[1] = new double[2] {
                200, 2000
            };
            cr.NormalizedData[2] = new double[2] {
                7, 20
            };
            KmeansClusterAlgorithm.UpdateClusterAssignment(cr, cd, o);
            Assert.AreEqual(cr.ClusterAssignment[0], 0);
            Assert.AreEqual(cr.ClusterAssignment[1], 0);
            Assert.AreEqual(cr.ClusterAssignment[2], 1);
        }
Ejemplo n.º 5
0
        public ClusterDataReader(string fileName, ClusterData clusterData)
        {
            this.FileName    = fileName;
            this.clusterData = clusterData;

            ReadData();
        }
Ejemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ClusterData cd = new ClusterData();

            this.nodes = JsonConvert.SerializeObject(cd.GenerateNodes());
            this.edges = JsonConvert.SerializeObject(cd.GenerateEdges());
        }
Ejemplo n.º 7
0
        /// <summary>
        ///   This Method ensures a match is possible and if so clusters two nodes
        /// </summary>
        /// <param name="matchData"> MatchData Object </param>
        /// <returns> </returns>
        public static Cluster ClusterNodes(MatchData matchData)
        {
            INode       firstRoot  = matchData.First.Shred.Root();
            INode       secondRoot = matchData.Second.Shred.Root();
            ClusterData result     = IsMatch(matchData, firstRoot, secondRoot);

            if (result == null)
            {
                return(null);
            }

            // Mirror the smaller object if need be
            if (result.Match == Match.Inverted)
            {
                if (firstRoot.Size() < secondRoot.Size())
                {
                    firstRoot.Mirror();
                    result.FirstDirection = Enumeration.Opposite(result.FirstDirection);
                }
                else
                {
                    secondRoot.Mirror();
                    result.SecondDirection = Enumeration.Opposite(result.SecondDirection);
                }
            }

            // If the FirstNode's Edge is on the Right, it should go on the LEFT (make sense? )
            if (result.FirstDirection == Direction.FromRight && result.SecondDirection == Direction.FromLeft)
            {
                return(new Cluster(firstRoot, secondRoot, result.Match, matchData));
            }

            return(new Cluster(secondRoot, firstRoot, result.Match, matchData));
        }
Ejemplo n.º 8
0
        public KMeans(int k, IReadOnlyList <IVector> data, DistanceMetric distanceMetric = DistanceMetric.Euclidean, int?randomSeed = null)
        {
            _k = k;
            _distanceMetric = distanceMetric;
            _cluster        = new ClusterData();
            _data           = data;

            // use kmeans++ to find best initial positions
            // https://normaldeviate.wordpress.com/2012/09/30/the-remarkable-k-means/
            var rand  = randomSeed.HasValue ? new Random(randomSeed.Value) : new Random();
            var data2 = data.ToList();

            // pick the first at random
            var firstIndex = rand.Next(0, data2.Count);

            _cluster.Add(data2[firstIndex]);
            data2.RemoveAt(firstIndex);

            // create a categorical distribution for each subsequent pick
            for (var i = 1; i < _k && data2.Count > 0; i++)
            {
                var probabilityList = new List <double>();
                foreach (var item in data2)
                {
                    using (var distance = _cluster.CalculateDistance(item, _distanceMetric)) {
                        var minIndex = distance.MinimumIndex();
                        probabilityList.Add(distance.AsIndexable()[minIndex]);
                    }
                }
                var distribution = new Categorical(probabilityList.ToArray());
                var nextIndex    = distribution.Sample();
                _cluster.Add(data2[nextIndex]);
                data2.RemoveAt(nextIndex);
            }
        }
Ejemplo n.º 9
0
        private void LoadFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "CSV files (*.csv)|*.csv|TXT files (*.txt)|*.txt";

            if (dlg.ShowDialog() == true)
            {
                clusterData = new ClusterData();

                ClusterDataReader dr = ClusterDataReaderFactory.GetClusterDataReader(dlg.FileName, clusterData);

                if (dr == null)
                {
                    WPFMessageBox.MsgError("Hiba történt a file betöltése során!");
                    return;
                }
                TextBlockFileName.Text        = dlg.FileName;
                GridAllStatistics.DataContext = clusterData;
                GridXStatistics.DataContext   = clusterData;
                GridYStatistics.DataContext   = clusterData;

                clusterData.NormalizePoints();

                PointChart.Data = clusterData;
                PointChart.Draw();
            }
        }
Ejemplo n.º 10
0
    /// <summary>
    /// 可移动单位移动
    /// </summary>
    /// <param name="member">单个单位</param>
    private void OneMemberMove(ClusterData member)
    {
        if (member == null)
        {
            return;
        }
        // 计算周围单位碰撞
        GetCloseMemberGrivity(member);

        if (!member.IsMoving)
        {
            return;
        }
        //// 高度控制
        //var heightDiff = member.transform.position.y - member.Height;
        //if (heightDiff != 0)
        //{
        //    member.transform.position = new Vector3(member.transform.position.x, member.Height,
        //        member.transform.position.z);
        //}

        // 单位状态切换
        ChangeMemberState(member);
        // 当前单位到目标的方向
        Vector3 targetDir = Utils.WithOutZ(member.TargetPos - member.Position);
        // 转向角度
        float rotate = 0f;
        // 标准化目标方向
        Vector3 normalizedTargetDir = targetDir.normalized;
        // 计算后最终方向
        var finalDir = GetGtivity(member);

        Debug.DrawLine(member.Position, member.Position + finalDir, Color.cyan);
        // 当前方向与目标方向夹角
        var angleForTarget = Vector3.Dot(normalizedTargetDir, Utils.WithOutZ(member.Direction));

        // 当前单位位置减去周围单位的位置的和, 与最终方向相加, 这个向量做处理, 只能指向目标方向的左右90°之内, 防止调头
        // 获取周围成员(不论敌友, 包括障碍物)的斥力引力
        // 直线移动防止抖动
        if (angleForTarget < 0.999f)
        {
            // 计算转向
            rotate = Vector3.Dot(finalDir.normalized, member.DirectionRight) * 180;
            if (rotate > 180 || rotate < -180)
            {
                rotate += ((int)rotate / 180) * 180 * (Mathf.Sign(rotate));
            }
        }
        // 转向
        member.Rotate    = Vector3.up * rotate * member.RotateSpeed * Time.deltaTime;
        member.Position += member.SpeedDirection * Time.deltaTime;
        // 前进
        Debug.DrawLine(member.Position, member.Position + member.SpeedDirection, Color.white);

#if UNITY_EDITOR
        member.Do();
#endif
    }
Ejemplo n.º 11
0
 public SSpaceMissileVisualData(
     Vector3 missileWorldPos, Vector3 missileWorldDir, Vector3 missileWorldVel,
     SSpaceMissileClusterVisualData cluster, int clusterId)
     : base(missileWorldPos, missileWorldVel, sharableData: new ClusterData(cluster))
 {
     _sharableData   = new ClusterData(cluster);
     _clusterId      = clusterId;
     visualDirection = missileWorldDir;
 }
Ejemplo n.º 12
0
        public void TestClusterAlgorithmOnExample()
        {
            ClusterData             data    = new ClusterData(GetTestData(), new string[] { "X", "Y" });
            ClusterAlgorithmOptions options = new ClusterAlgorithmOptions(5);

            var result = KmeansClusterAlgorithm.Analyze(data, options);

            Assert.IsTrue(result.ClusterAssignment.Length > 0);
            Trace.WriteLine($"Iterations: {result.Iterations}");
            Trace.WriteLine(result.PrintCsvResult());
        }
Ejemplo n.º 13
0
        public override (string json, string Output) FeatureExtraction(ClassifierResponseItem response)
        {
            var clusterData = new ClusterData
            {
                StartStringData = string.Empty,
                EndStringData   = string.Empty
            };

            clusterData.StartStringData = GetStrings(response.Data, 0, STRING_BYTE_MINIMUM);
            clusterData.EndStringData   = GetStrings(response.Data, response.Data.Length - STRING_BYTE_MINIMUM, STRING_BYTE_MINIMUM);

            return(JsonConvert.SerializeObject(clusterData), $"{(int)response.FileGroup},{clusterData.StartStringData},{clusterData.EndStringData}");
        }
Ejemplo n.º 14
0
 static int ClearTarget(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         ClusterData obj = (ClusterData)ToLua.CheckObject(L, 1, typeof(ClusterData));
         obj.ClearTarget();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 15
0
    public bool FindClusters()
    {
        for (int i = 0; i < maxIterations; i++)
        {
            bool changed = false;
            UpdateMeans();
            double[]           distances      = new double[ClusterNumber];
            List <List <int> > newClusterData = new List <List <int> >();

            for (int j = 0; j < ClusterNumber; j++)
            {
                newClusterData.Add(new List <int>());
            }

            // reassign datapoints to clusters based on lowest distance to cluster ceters

            for (int j = 0; j < ClusterNumber; j++)
            {
                foreach (var datapoint in ClusterData[j])
                {
                    for (int k = 0; k < ClusterNumber; k++)
                    {
                        distances[k] = Math.Abs(datapoint - clusterMeans[k]);
                    }
                    int newClusterIndex = Array.IndexOf(distances, distances.Min());
                    newClusterData[newClusterIndex].Add(datapoint);
                }
            }

            // check if cluster members changed - costly but convenient
            for (int j = 0; j < ClusterNumber; j++)
            {
                changed = !Enumerable.SequenceEqual(ClusterData[j].OrderBy(i => i), newClusterData[j].OrderBy(i => i));
                if (changed)
                {
                    break;
                }
            }

            // if no changes then we finish
            if (!changed)
            {
                return(true);
            }

            ClusterData.Clear();
            ClusterData.AddRange(newClusterData);
        }
        return(false);
    }
Ejemplo n.º 16
0
 static int SetDataValue(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         ClusterData obj  = (ClusterData)ToLua.CheckObject(L, 1, typeof(ClusterData));
         VOBase      arg0 = (VOBase)ToLua.CheckObject(L, 2, typeof(VOBase));
         obj.SetDataValue(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 17
0
 static int PushTarget(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         ClusterData         obj  = (ClusterData)ToLua.CheckObject(L, 1, typeof(ClusterData));
         UnityEngine.Vector3 arg0 = ToLua.ToVector3(L, 2);
         obj.PushTarget(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 18
0
 static int PushTargetList(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         ClusterData obj = (ClusterData)ToLua.CheckObject(L, 1, typeof(ClusterData));
         System.Collections.Generic.List <UnityEngine.Vector3> arg0 = (System.Collections.Generic.List <UnityEngine.Vector3>)ToLua.CheckObject(L, 2, typeof(System.Collections.Generic.List <UnityEngine.Vector3>));
         obj.PushTargetList(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 19
0
 static int PopTarget(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         ClusterData obj = (ClusterData)ToLua.CheckObject(L, 1, typeof(ClusterData));
         bool        o   = obj.PopTarget();
         LuaDLL.lua_pushboolean(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Ejemplo n.º 20
0
    /// <summary>
    /// 显示单位身上的skill与buff
    /// </summary>
    private void ShowSkillAndBuff(ClusterData clusterData)
    {
        if (clusterData == null)
        {
            return;
        }
        // 清空列表
        for (var i = SkillScrollParent.transform.childCount - 1; i >= 0; i--)
        {
            Destroy(SkillScrollParent.transform.GetChild(i).gameObject);
        }
        for (var i = BuffScrollParent.transform.childCount - 1; i >= 0; i--)
        {
            Destroy(BuffScrollParent.transform.GetChild(i).gameObject);
        }

        // 将技能加载到列表中
        foreach (var skill in clusterData.AllData.SkillInfoList)
        {
            // 将skill显示在列表中
            var copySkillButton = Instantiate(skillButton);
            var mySkill         = skill;
            copySkillButton.GetComponentInChildren <Text>().text = "SkillNum" + mySkill.Num + "," + mySkill.AddtionId;
            copySkillButton.onClick.AddListener(delegate()
            {
                // 点击事件
                selectedSkill = mySkill.AddtionId;
                Debug.Log("选中技能:" + selectedSkill);
            });
            copySkillButton.gameObject.transform.parent = SkillScrollParent.transform;
        }

        // 将buff加载到列表中
        foreach (var buff in clusterData.AllData.BuffInfoList)
        {
            // 将buff显示在列表中
            var copyBufflButton = Instantiate(buffButton);
            var myBuff          = buff;
            copyBufflButton.GetComponentInChildren <Text>().text = "BuffNum" + myBuff.Num + "," + myBuff.AddtionId;
            copyBufflButton.onClick.AddListener(delegate()
            {
                selectedBuff = myBuff.AddtionId;
                Debug.Log("选中Buff:" + selectedBuff);
            });
            copyBufflButton.gameObject.SetActive(true);
            copyBufflButton.gameObject.transform.parent = BuffScrollParent.transform;
        }
    }
Ejemplo n.º 21
0
    static int get_Complete(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData obj = (ClusterData)o;
            System.Action <UnityEngine.GameObject> ret = obj.Complete;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Complete on a nil value" : e.Message));
        }
    }
Ejemplo n.º 22
0
    static int set_State(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData     obj  = (ClusterData)o;
            SchoolItemState arg0 = (SchoolItemState)ToLua.CheckObject(L, 2, typeof(SchoolItemState));
            obj.State = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index State on a nil value" : e.Message));
        }
    }
Ejemplo n.º 23
0
    static int set_Cluster(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            MFAModelRender obj  = (MFAModelRender)o;
            ClusterData    arg0 = (ClusterData)ToLua.CheckUnityObject(L, 2, typeof(ClusterData));
            obj.Cluster = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Cluster on a nil value" : e.Message));
        }
    }
Ejemplo n.º 24
0
    static int get_Cluster(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            MFAModelRender obj = (MFAModelRender)o;
            ClusterData    ret = obj.Cluster;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Cluster on a nil value" : e.Message));
        }
    }
Ejemplo n.º 25
0
        internal override bool Reconstruct(BlamLib.Blam.CacheFile c)
        {
            bool result = true;

            // recreate the section data
            if (ClusterData.Count != 1)
            {
                structure_bsp_cluster_data_block_new cdata;
                ClusterData.Add(out cdata);

                result = cdata.Section.Value.Reconstruct(c, SectionInfo.Value, GeometryBlockInfo.Value);
            }

            GeometryBlockInfo.Value.ClearPostReconstruction();

            return(result);
        }
Ejemplo n.º 26
0
    static int set_RotateWeight(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData obj  = (ClusterData)o;
            float       arg0 = (float)LuaDLL.luaL_checknumber(L, 2);
            obj.RotateWeight = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index RotateWeight on a nil value" : e.Message));
        }
    }
Ejemplo n.º 27
0
    static int set_TargetPos(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData         obj  = (ClusterData)o;
            UnityEngine.Vector3 arg0 = ToLua.ToVector3(L, 2);
            obj.TargetPos = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index TargetPos on a nil value" : e.Message));
        }
    }
Ejemplo n.º 28
0
    static int get_RotateWeight(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData obj = (ClusterData)o;
            float       ret = obj.RotateWeight;
            LuaDLL.lua_pushnumber(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index RotateWeight on a nil value" : e.Message));
        }
    }
Ejemplo n.º 29
0
    static int get_State(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            ClusterData     obj = (ClusterData)o;
            SchoolItemState ret = obj.State;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index State on a nil value" : e.Message));
        }
    }
Ejemplo n.º 30
0
        public static ClusterDataReader GetClusterDataReader(string fileName, ClusterData clusterData)
        {
            string ext = Path.GetExtension(fileName).ToLower();

            switch (ext)
            {
            case ".csv":
                CsvReader cr = new CsvReader(fileName, clusterData);
                return(cr.ReadingCompleted ? cr : null);

            case ".txt":
                TxtReader tr = new TxtReader(fileName, clusterData);
                return(tr.ReadingCompleted ? tr : null);

            default:
                return(null);
            }
        }