//get existing pooled object public GameObject Get(PoolType type) { GameObject returnObj = null; for (int i = 0; i < pool.Length; i++) { PooledObject po = pool [i]; if (po.poolType == type) { for (int j = 0; j < po.objectPool.Count; j++) { if (po.objectPool[j] != null && !po.objectPool [j].activeSelf) { returnObj = po.objectPool [j]; break; } } } } if (returnObj != null) { return(returnObj); } else { return(AddNew(type)); } }
public static PoolObject GetInstance(PoolType type, int no) { var obj = instance.pool .FirstOrDefault(p => p.Prop.type == type && p.Prop.no == no && !p.IsActive ); if (obj == null) { var entity = instance.prefabs.FirstOrDefault(p => p.prop.type == type && p.prop.no == no ); if (entity == null) { Debug.LogWarning("No object: " + type + ", " + no); } var prefab = entity.obj; var prop = entity.prop; obj = Instantiate(prefab, instance.transform) .AddComponent <PoolObject> (); obj.name = prefab.name + "_" + instance.pool.Count; obj.Initialize(prop); instance.pool.Add(obj); } return(obj); }
public BestTime(PoolType poolType, EventDistance eventDistance, Stroke stroke, TimeSpan recordTime) { PoolType = poolType; EventDistance = eventDistance; Stroke = stroke; RecordTime = recordTime; }
public PoolServer(string poolName, PoolType type, int speed, int delaySec, double rejectPercent, GetTargetShareHandler handler) { _rnd = new MersenneTwister((uint)DateTime.Now.Ticks); Round = 1; PoolName = poolName; Type = type; GHashSpeed = speed; DelaySec = delaySec; GetNextShare = handler; RejectPercentile = rejectPercent; CurrentRealShare = 0; MyValidShare = 0; MyLostShare = 0; TotalScore = 0; MyScore = 0; MyTotalProfit = 0; MyTotalValidShare = 0; MyTotalShare = 0; BaseProgress = 0; PenaltyFactor = 1.0f; // Initialize(initialProgress); }
/// <summary> /// Throws an exception if the passed key is not in the pool /// </summary> private void ThrowIfKeyNotExist(PoolType type) { if (!_pool.ContainsKey(type)) { throw new ArgumentException($"Type {type} not exist in objects pool"); } }
public TimeSpan GetBestTime(PoolType aPoolType, Stroke aStroke, EventDistance aEventDistance) { int indexOfSwimmerInCollection = 0; for (int i = 0; i < (CollOfEvents.Find((Event aEvent) => (aEvent.Distance == aEventDistance && aEvent.Stroke == aStroke && aEvent.PoolTypeOfEvent == aPoolType ) ).NumOfRegisterant); i++) { if (CollOfEvents.Find((Event aEvent) => (aEvent.Distance == aEventDistance && aEvent.Stroke == aStroke && aEvent.PoolTypeOfEvent == aPoolType ) ).CollOfRegisterants[i] == this) { indexOfSwimmerInCollection = i; } } return(CollOfEvents.Find((Event aEvent) => (aEvent.Distance == aEventDistance && aEvent.Stroke == aStroke && aEvent.PoolTypeOfEvent == aPoolType ) ).CollOfSwims[indexOfSwimmerInCollection].bestTime); }
public static GameObject GetPoolTrans(PoolType type) { if (IsInitialed == false) { Debug.LogError("BaseObject Pool Not Initialed"); return(null); } GameObject result = null; m_AllPoolView.TryGetValue(type, out result); if (result != null) { return(result); } switch (type) { case PoolType.MsgBox: result = GenerationObjUtility.CreateObjectByName("MseeageBoxPool", ObjectPoolTrans, true); // result = CommonOperate.CreateObjWhithName("MseeageBoxPool", ObjectPoolTrans); break; case PoolType.MeshLine: result = GenerationObjUtility.CreateObjectByName("MseeageBoxPool", ObjectPoolTrans, true); // result = CommonOperate.CreateObjWhithName("MeshLinePool", ObjectPoolTrans); break; } result.transform.SetTransLocalState(Vector3.one, Vector3.one * 100000, Vector3.zero, false); m_AllPoolView[type] = result; return(result); }
public ConsoleMessage GetNewMessage(PoolType type) { GameObject messageObj = null; ConsoleMessage message = null; CheckPoolAvailability(type); switch (type) { case PoolType.Log: messageObj = logPool.Dequeue(); ConsoleLogMessage temp = messageObj.GetComponent <ConsoleLogMessage>(); if (temp) { message = temp; } break; case PoolType.Command: messageObj = commandPool.Dequeue(); ConsoleCommandMessage temp2 = messageObj.GetComponent <ConsoleCommandMessage>(); if (temp2) { message = temp2; } break; } messageObj.transform.SetParent(contentParent); messageObj.SetActive(true); return(message); }
public void Spawn(PoolType type, Vector3 instantiateVector) { if (Instance.objectsPool.Any()) { ObjectPoolManager.Instance.GetPool(type).Spawn(instantiateVector, Quaternion.identity); } }
// public void /// <summary> /// добавить объект к уже существующему пулу /// </summary> /// <param name="id"></param> /// <param name=""></param> public void AddObject(PoolType id, GameObject prefab, int count) { Pool pool = null; if (_pools.TryGetValue((int)id, out pool)) { for (int i = 0; i < count; i++) { var obj = Instantiate(prefab, transform); obj.SetActive(false); IPoollable ipoolable = obj.GetComponent <IPoollable>(); if (ipoolable != null) { ipoolable.Init(); } pool.AddObject(obj, true); } } else { Debug.Log("Pool is not find"); } }
public GameObject GetPooledObject(PoolType poolType, Vector3 pos, Quaternion rot) { if (poolDictionary.ContainsKey(poolType)) { // Dequeue object and activates it if (poolDictionary[poolType].pooledGameObjects.Count != 0) { GameObject pooledObject = poolDictionary[poolType].pooledGameObjects.Dequeue(); pooledObject.transform.position = pos; pooledObject.transform.rotation = rot; pooledObject.SetActive(true); return(pooledObject); } // Creates a new object and instantly returns it else { GenerateNewObject(poolType); GameObject pooledObject = poolDictionary[poolType].pooledGameObjects.Dequeue(); pooledObject.transform.position = pos; pooledObject.transform.rotation = rot; pooledObject.SetActive(true); return(pooledObject); } } else { Debug.LogWarning($"Requested Object from a non existing pool! {poolType.ToString()}"); return(null); } }
public GameObject GetObject(PoolType id) { var obj = _pools[(int)id].GetObject(); if (obj == null) { Debug.LogFormat("Pool {0} is empty.", id); if (DynamicPool) { obj = Instantiate(_pools[(int)id].OriginalPrefabe()); IPoollable IPoollabl = obj.GetComponent <IPoollable>(); if (IPoollabl != null) { IPoollabl.Init(); } Debug.LogFormat("Add one object to {0} pool.", id); } } IPoollable iPoollable = obj.GetComponent <IPoollable>(); if (iPoollable != null) { iPoollable.ReSpawn(); } return(obj); }
public TimeSpan GetBestTime(PoolType course, Stroke stroke, EventDistance distance) { BestTimes = new List <TimeSpan>(); TimeSpan result = new TimeSpan(); for (int i = 0; i < SwimMeetInfo.Count; i++) { if (SwimMeetInfo[i][0] == (int)course && SwimMeetInfo[i][1] == (int)stroke && SwimMeetInfo[i][2] == (int)distance) { BestTimes.Add(SwimTimeSpan[i]); } } if (BestTimes.Count > 0) { result = BestTimes[0]; for (int i = 0; i < BestTimes.Count; i++) { if (TimeSpan.Compare(result, BestTimes[i]) == 1) { result = BestTimes[i]; } } } return(result); }
public void BackToPool(PoolType tag, GameObject obj) { obj.SetActive(false); Queue <GameObject> objPool = poolDictionary[tag]; objPool.Enqueue(obj); }
public T Spawn <T>(PoolType id, GameObject prefab, Vector3 position = default(Vector3), Transform parent = null, Quaternion rotation = default(Quaternion)) where T : class { var val = pools[(int)id].Spawn(prefab, position, rotation, parent); return(val.GetComponent <T>()); }
public void Destroy(PoolType type, GameObject target) { if (ObjectPoolManager.Instance.objectsPool.Any()) { ObjectPoolManager.Instance.GetPool(type).Destroy(target); } }
public StatisticsPool(string sceneName, PoolType poolType) { this.sceneName = sceneName; this.poolType = poolType; this.isExpanded = new AnimBool(false); this.categories = new List <StatisticsPoolCategory>(); }
private static GameObject GetNewBorrowed(PoolType type) { Ensure(type); List <GameObject> objs = objects[type]; if (objs.Count == 0) { return(null); } GameObject o = objs[0]; objs.RemoveAt(0); while (o == null && objs.Count > 0) { Debug.LogError("Idle pooled object of type '" + type + "' was destroyed! Why?"); objs.RemoveAt(0); o = objs[0]; } MakeBorrowed(o); o.SendMessage("Start", null, SendMessageOptions.DontRequireReceiver); return(o); }
public static object GetPoolByType(PoolType type, string sourcesPath, uint maxCount = 0) { if (IsInitialed == false) { Debug.LogError("BaseObject Pool Not Initialed"); return(null); } if (ObjectPoolTrans == null) { GenerationObjUtility.CreateObjectByName("BaseObjectPool", null, true); } object result = null; if (m_AllPoolDataBase.TryGetValue(type, out result)) { return(result); } switch (type) { case PoolType.MsgBox: result = new MseeageBoxPool(sourcesPath, maxCount); m_AllPoolDataBase[type] = result; GetPoolTrans(type); break; //case PoolType.MeshLine: // result = new MeshLinePool(sourcesPath, maxCount); // m_AllPoolDataBase[type] = result; // GetPoolTrans(type); // break; } return(result); }
/// <summary> /// Add new object to pool /// </summary> private void AddOne(PoolType type, PoolBehavior prefab) { var obj = Instantiate(prefab, transform); obj.Disable(); _pool[type].Add(obj); }
public void Init(PoolType poolType, int key) { PoolType = poolType; Key = key; _spawnables = GetComponentsInChildren <ISpawnable>(); _despawnables = GetComponentsInChildren <IDespawnable>(); }
public void CallEvent(PoolType type, string funcName) { if (_poolDic.ContainsKey(type)) { _poolDic[type].SendMessage(funcName, SendMessageOptions.DontRequireReceiver); } }
public static Int32 GetResourceCountInPool <PoolType>() where PoolType : IPoolObtainable <Pool>, new() { PoolType pool = new PoolType(); return(pool.GetPool().GetResourceCount()); }
public Pool(CharacterType ctype, PoolType ptype) { switch (ptype) { case PoolType.AttackEffectPool: switch (ctype) { case CharacterType.PikeMan: m_pref = (GameObject)Resources.Load("Prefab/AttackEffect/pike_effect"); break; case CharacterType.GunGirl: m_pref = (GameObject)Resources.Load("Prefab/AttackEffect/gungirl_effect"); break; case CharacterType.SpiderQueen: m_pref = (GameObject)Resources.Load("Prefab/AttackEffect/SpiderQueen_effect"); break; case CharacterType.Zako: m_pref = (GameObject)Resources.Load("Prefab/AttackEffect/Zako_effect"); break; case CharacterType.ZakoFar: m_pref = (GameObject)Resources.Load("Prefab/AttackEffect/syuriken"); break; } break; case PoolType.HitEffectPool: break; } }
private void btnAdd_Click(object sender, EventArgs e) { DialogResult = DialogResult.None; try { string name = txtName.Text; DateTime start = dateTimePickerStart.Value.Date; DateTime end = dateTimePickerEnd.Value.Date; PoolType poolType = (PoolType)cmbPoolType.SelectedValue; if (txtName.Text == "") { throw new Exception("Please write a name"); } int lanes = Convert.ToInt32(txtLanes.Text); swimMeet = new SwimMeet(name, start, end, poolType, lanes); DialogResult = DialogResult.OK; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (DialogResult == DialogResult.OK) { ((Form1)Owner).SwimMeetManager.Add(swimMeet); Close(); } }
/// <summary> /// 初始化 /// </summary> /// <param name="poolType">对象池类型</param> /// <param name="gameObject">Obj</param> /// <param name="cont">初始化大小</param> public void InitPool(PoolType poolType, GameObject prefab, int count = 20) { //创建个MgrPool节点 把所有池子都归到这个节点下 方便管理 if (_poolTotal == null) { _poolTotal = new GameObject("TamToastPool").transform; } if (!_poolDic.ContainsKey(poolType)) { if (_unifiedMgr) { //如果是新池子 创建一个节点 Transform parent = new GameObject("Pool_" + poolType.ToString()).transform; parent.SetParent(_poolTotal); _pathDic.Add(poolType, parent); } _poolDic.Add(poolType, new Queue <GameObject>()); CreatorItem(poolType, prefab, count); } else { //throw new Exception(string.Format("该池子:'{0}'已存在,请勿重复初始化!", poolType)); } }
// 从池中获取一个能用的对象 public GameObject getObjFromPool(PoolType type) { if (!hashTable.ContainsKey(type)) { throw new Exception("Have not create " + type.ToString() + " Pool"); } PoolObj poolObj = hashTable[type] as PoolObj; GameObject t; for (int i = 0; i < poolObj.objList.Count; i++) { t = poolObj.objList[(poolObj.index + i) % poolObj.objList.Count]; // Active 为False 即为可以拿出来使用的对象,否则寻找下一个 if (!t.activeSelf) { poolObj.index = (poolObj.index + i) % poolObj.objList.Count; t.SetActive(true); return(t); } } // 所有的都正在使用……只能添加新的了 t = addToPool(poolObj); t.SetActive(true); return(t); }
private static void Ensure(PoolType type) { if (!objects.ContainsKey(type)) { objects.Add(type, new List <GameObject>()); } }
/// <summary> /// 从池子里取出 /// </summary> /// <param name="poolType">池子类型</param> /// <returns></returns> public GameObject Get(PoolType poolType) { if (_poolDic.ContainsKey(poolType) && _poolDic[poolType].Count > 0) { Queue <GameObject> goQueue = _poolDic[poolType]; GameObject prefab = null; //这里留一个扩充池子用 if (goQueue.Count > 1) { prefab = goQueue.Dequeue(); prefab.SetActive(true); } //这里如果池子空间只剩下一个 就扩容池子 if (prefab == null && goQueue.Count <= 1) { CreatorItem(poolType, goQueue.Peek(), _expansion); return(Get(poolType)); } return(prefab); } else { throw new Exception(string.Format("该池子:'{0}'不存在或已被清理,请先初始化!", poolType)); } }
public void ZombieBoostCreator(PoolType id, Vector3 pos, Quaternion rot) { switch (id) { case PoolType.Medpack: for (int i = 0; i < medpacks.Count; i++) { if (!medpacks[i].gameObject.activeSelf) { medpacks[i].Spawn(PoolType.Medpack, medpackPrefab, pos, rot); break; } } break; case PoolType.SpeedBoost: for (int i = 0; i < medpacks.Count; i++) { if (!speedBoosts[i].gameObject.activeSelf) { speedBoosts[i].Spawn(PoolType.SpeedBoost, speedBoostPrefab, pos, rot); break; } } break; default: break; } }
public void RemoveGameObject(PoolType poolName, GameObject go) { if (m_PoolDic.ContainsKey(poolName)) { m_PoolDic[poolName].Remove(go); } }
public WeaponFeature(PoolType projectile, int projectileVelocity, float fireRate, int damageAmount) { this.projectile = projectile; this.projectileVelocity = projectileVelocity; this.fireRate = fireRate; this.damageAmount = damageAmount; }
public PutPoolPartitionSpectraS3Request(string name, PoolType type) { this.Name = name; this.Type = type; this.QueryParams.Add("name", name); this.QueryParams.Add("type", type.ToString()); }
public GameObject FakeInstantiate(PoolType type) { for (int i = 0; i < Agents.Count; ++i) { if (type == Agents[i].Type) { return Agents[i].GetPoolObject(); } } return null; }
public void FakeDestroy(GameObject go, PoolType type) { for (int i = 0; i < Agents.Count; ++i) { if (type == Agents[i].Type) { Agents[i].PutObject(go); return; } } }
//================================================================================================== /// <summary> /// 从Pool读取指定类型数据到DataTable /// </summary> /// <param name="poolType">数据类型</param> /// <returns>DataTable</returns> public DataTable ReadPool(PoolType poolType) { try { DataTable tmpDt = new DataTable(); switch (poolType) { case PoolType.Users: tmpDt = APPool.poolAll.Tables["poolAuthUsers"].Copy(); break; case PoolType.Us2Gr: tmpDt = APPool.poolAll.Tables["poolAuthUs2Gr"].Copy(); break; case PoolType.Groups: tmpDt = APPool.poolAll.Tables["poolAuthGroups"].Copy(); break; case PoolType.Gr2Ca: tmpDt = APPool.poolAll.Tables["poolAuthGr2Ca"].Copy(); break; case PoolType.Gr2Ru: tmpDt = APPool.poolAll.Tables["poolAuthGr2Ru"].Copy(); break; case PoolType.Rules: tmpDt = APPool.poolAll.Tables["poolAuthRules"].Copy(); break; case PoolType.Ru2It: tmpDt = APPool.poolAll.Tables["poolAuthRu2It"].Copy(); break; case PoolType.CangKu: tmpDt = APPool.poolAll.Tables["poolAuthCangKu"].Copy(); break; case PoolType.Items: tmpDt = APPool.poolAll.Tables["poolAuthItems"].Copy(); break; case PoolType.ItemsNo: tmpDt = APPool.poolAll.Tables["poolAuthItemsNo"].Copy(); break; case PoolType.GroupsRules: tmpDt = APPool.poolAll.Tables["pvGroupsRules"].Copy(); break; case PoolType.GroupsItems: tmpDt = APPool.poolAll.Tables["pvGroupsItems"].Copy(); break; default: break; } return tmpDt; } catch (Exception) { throw; } }
public static CustomThreadPool CreatePool(PoolType type,ThreadPoolSettings config, CancellationToken tk) { switch (type) { case PoolType.Custom1: return new CustomThreadPool1(config, tk); case PoolType.Custom2: return new CustomThreadPool2(config, tk); case PoolType.Custom3: return new CustomThreadPool3(config, tk); default: return new DefaultThreadPool(config, tk); } }
public RoundResult(string poolName, PoolType type, int finalShare, int validShare, int lostShare, int roundTime) { PoolName = poolName; Type = type; FinalShare = finalShare; ValidShare = validShare; LostShare = lostShare; RoundTime = roundTime; switch (type) { case PoolType.Prop: case PoolType.PropEarlyHop: Profit = validShare * 50.0f / FinalShare; break; case PoolType.Pplns: var f = (int) (FinalShare/2); Profit = f > 0 ? ValidShare*50.0f/f : 0; break; case PoolType.Score: Profit = ValidShare * 50.0f / FinalShare; break; } }
public GetPoolPartitionsSpectraS3Request WithType(PoolType? type) { this._type = type; if (type != null) { this.QueryParams.Add("type", type.ToString()); } else { this.QueryParams.Remove("type"); } return this; }
/// <summary> /// Creates a pool partition with the specified name and pool type /// </summary> /// <param name="poolPartitionName"></param> /// <param name="poolType"></param> /// <param name="client"></param> /// <returns></returns> public static PutPoolPartitionSpectraS3Response CreatePoolPartition(string poolPartitionName, PoolType poolType, IDs3Client client) { return client.PutPoolPartitionSpectraS3(new PutPoolPartitionSpectraS3Request(poolPartitionName, poolType)); }
//================================================================================================== /// <summary> /// 从数据池读取数据,指定类型与列名称 /// </summary> /// <param name="poolType">数据类型</param> /// <param name="ColumnsName">列名称</param> /// <returns>List.String</returns> public List<string> ReadPoolSigItems(PoolType poolType, string ColumnsName) { try { List<string> tmpData = new List<string>();//缓存数据 DataTable tmpDt = ReadPool(poolType); var requ = from tmp in tmpDt.AsEnumerable() select tmp.Field<string>(ColumnsName); foreach (string x in requ) { tmpData.Add(x); } return tmpData; } catch (Exception) { throw; } }
public void SavePool(PoolType poolType, DataTable dataTable) { try { switch (poolType) { case PoolType.Users: APPool.poolAll.Tables["poolAuthUsers"].Clear(); APPool.poolAll.Tables["poolAuthUsers"].Merge(dataTable, true); break; case PoolType.Us2Gr: APPool.poolAll.Tables["poolAuthUs2Gr"].Clear(); APPool.poolAll.Tables["poolAuthUs2Gr"].Merge(dataTable, true); break; case PoolType.Groups: APPool.poolAll.Tables["poolAuthGroups"].Clear(); APPool.poolAll.Tables["poolAuthGroups"].Merge(dataTable, true); break; case PoolType.Gr2Ca: APPool.poolAll.Tables["poolAuthGr2Ca"].Clear(); APPool.poolAll.Tables["poolAuthGr2Ca"].Merge(dataTable, true); break; case PoolType.Gr2Ru: APPool.poolAll.Tables["poolAuthGr2Ru"].Clear(); APPool.poolAll.Tables["poolAuthGr2Ru"].Merge(dataTable, true); break; case PoolType.Rules: APPool.poolAll.Tables["poolAuthRules"].Clear(); APPool.poolAll.Tables["poolAuthRules"].Merge(dataTable, true); break; case PoolType.Ru2It: APPool.poolAll.Tables["poolAuthRu2It"].Clear(); APPool.poolAll.Tables["poolAuthRu2It"].Merge(dataTable, true); break; case PoolType.CangKu: APPool.poolAll.Tables["poolAuthCangKu"].Clear(); APPool.poolAll.Tables["poolAuthCangKu"].Merge(dataTable, true); break; case PoolType.Items: APPool.poolAll.Tables["poolAuthItems"].Clear(); APPool.poolAll.Tables["poolAuthItems"].Merge(dataTable, true); break; case PoolType.ItemsNo: APPool.poolAll.Tables["poolAuthItemsNo"].Clear(); APPool.poolAll.Tables["poolAuthItemsNo"].Merge(dataTable, true); break; case PoolType.GroupsRules: APPool.poolAll.Tables["pvGroupsRules"].Clear(); APPool.poolAll.Tables["pvGroupsRules"].Merge(dataTable, true); break; case PoolType.GroupsItems: APPool.poolAll.Tables["pvGroupsItems"].Clear(); APPool.poolAll.Tables["pvGroupsItems"].Merge(dataTable, true); break; default: break; } } catch (Exception) { throw; } }
//================================================================================================== /// <summary> /// 把指定的数据池的数据上传到数据库 /// </summary> /// <param name="poolType">要上传的数据池类型</param> public string UpdatePool(PoolType poolType) { try { switch (poolType) { case PoolType.Users: UpdateAuthUsers(); break; case PoolType.Us2Gr: UpdateAuthUs2Gr(); break; case PoolType.Groups: UpdateAuthGroups(); break; case PoolType.Gr2Ca: UpdateAuthGr2Ca(); break; case PoolType.Gr2Ru: UpdateAuthGr2Ru(); break; case PoolType.Rules: UpdateAuthRules(); break; case PoolType.Ru2It: UpdateAuthRu2It(); break; case PoolType.CangKu: UpdateAuthCangKu(); break; case PoolType.Items: UpdateAuthItems(); break; case PoolType.ItemsNo: UpdateAuthItemsNo(); break; case PoolType.GroupsRules: UpdateAuthGroupsRules(); break; case PoolType.GroupsItems: UpdateAuthGroupsItems(); break; default: break; } return "true"; } catch (Exception x) { return "UpdatePool:" + x.Message; throw; } }
// Uses the per-pixel classes from PredictGPU to pool the location of // gestures. Supports multiple types of pooling algorithms. Each // algorithm is described before each section. private static List<Pooled> Pool(PoolType type, ProcessorState state) { List<Pooled> gestures = new List<Pooled>(); System.Drawing.Point center; int[] label_counts; Tuple<int, int> max; switch (type) { #region KMeans case PoolType.KMeans: Random rand = new Random(); Point3 p = new Point3(0, 0, 0); int K = 7, num_changes = 10, iterations = 0; List<Point3> centroids = new List<Point3>(K); for (int i = 0; i < K; i++) centroids.Insert(i, new Point3( rand.Next(width), rand.Next(height), rand.Next(400, 1500) )); List<HashSet<int>> clusters = new List<HashSet<int>>(K); for (int i = 0; i < K; i++) clusters.Insert(i, new HashSet<int>()); Dictionary<int, int> assignments = new Dictionary<int,int>(); for (int i = 0; i < state.depth.Length; i++) if (state.predict_labels_[i] != (int)HandGestureFormat.Background) { int cluster = rand.Next(K); assignments.Add(i, cluster); clusters[cluster].Add(i); } List<int> points = new List<int>(assignments.Keys); // If there have been no changes, the centroids wont // change either so KMeans has found a minimum. This may // be a local minimum. #region KMeans, can be factored out while (num_changes > 0) { num_changes = 0; iterations++; if (iterations % 10 == 0) Console.WriteLine("Iteration {0}", iterations); // Update centroids for (int i = 0; i < K; i++) { int x = (int)clusters[i].Average(point => Util.toXY(point, width, height, kDepthStride).X); int y = (int)clusters[i].Average(point => Util.toXY(point, width, height, kDepthStride).Y); int depth = (int)clusters[i].Average(point => state.depth[point]); centroids[i].update(x, y, depth); } // Update classifications foreach (int point in points) { System.Drawing.Point xy = Util.toXY(point, width, height, kDepthStride); p.update(xy.X, xy.Y, state.depth[point]); int nearest = 0; double nearest_distance = Util.EuclideanDistance(centroids[nearest], p); for (int i = 1; i < K; i++) { double distance = Util.EuclideanDistance(centroids[i], p); if (distance < nearest_distance) { nearest = i; nearest_distance = distance; } } if (assignments[point] != nearest && clusters[assignments[point]].Count != 1) { num_changes++; clusters[assignments[point]].Remove(point); clusters[nearest].Add(point); assignments[point] = nearest; } } } #endregion // Fit a Gaussian distribution on all the cluster sizes // and look for outliers that are at least two standard // deviations away from the mean. #region Gaussian outlier detection // Print the distribution of sizes within clusters var sizes = clusters.Select(cluster => cluster.Count). OrderByDescending(val => val).ToArray(); // Fit normal distribution and look for outliers double average = sizes.Average(); double stddev = Math.Sqrt(sizes.Select(val => Math.Pow(val, 2)).Sum()/sizes.Length - Math.Pow(average, 2)); Tuple<double, double> range = new Tuple<double, double>(average - 2*stddev, average + 2*stddev); List<int> outliers = new List<int>(); for (int i = 0; i < clusters.Count; i++) { Console.WriteLine("{0} - {1} ({2})", i, clusters[i].Count, clusters[i].Count > range.Item2); if (clusters[i].Count > range.Item2) outliers.Add(i); } #endregion // Draw outlier-ly large clusters List<Tuple<byte, byte, byte>> label_colors = Util.GiveMeNColors(K); ResetOverlay(state); //foreach (int outlier in outliers) for (int outlier = 0; outlier < K; outlier++) { foreach (int point in clusters[outlier]) { int bitmap_index = point * 4; state.overlay_bitmap_bits_[bitmap_index + 2] = (int)label_colors[outlier].Item1; state.overlay_bitmap_bits_[bitmap_index + 1] = (int)label_colors[outlier].Item2; state.overlay_bitmap_bits_[bitmap_index + 0] = (int)label_colors[outlier].Item3; } // Get majority label within this cluster label_counts = new int[state.feature.num_classes_]; Array.Clear(label_counts, 0, label_counts.Length); foreach (int point in clusters[outlier]) label_counts[state.predict_labels_[point]]++; max = Util.MaxNonBackground(label_counts); center = new System.Drawing.Point(centroids[outlier].x(), centroids[outlier].y()); gestures.Add(new Pooled(center, centroids[outlier].depth(), (HandGestureFormat)max.Item1)); Console.WriteLine("Center: ({0}px, {1}px, {2}mm)", center.X, center.Y, centroids[outlier].depth()); } state.overlay_start_.Value = true; break; #endregion #region DBSCAN case PoolType.DBSCAN: //List<DBScanPoint> dbpoints = new List<DBScanPoint>(); /* int count_label = 0; for (int i = 0; i < state.depth.Length; i++) if (state.predict_labels_[i] != (int)HandGestureFormat.Background) { count_label++; System.Drawing.Point xy = Util.toXY(i, width, height, kDepthStride); dbpoints.Add(new DBScanPoint(xy.X, xy.Y)); } Debug.WriteLine("{0} points are dbscanned", count_label); */ // The minPts setting automatically filters out noise. So // the clusters returned here can be safely assumed to be // hands. No need for outlier detection! //double eps = 20; //int minPts = 500; double eps = 10; int minPts = 300; DateTime ExecutionStartTime; DateTime ExecutionStopTime; TimeSpan ExecutionTime; ExecutionStartTime = DateTime.Now; List<List<int>> dbclusters = DBSCAN.GetClusters( eps, minPts, state.predict_labels_, (int)HandGestureFormat.Background, state.pool_); ExecutionStopTime = DateTime.Now; ExecutionTime = ExecutionStopTime - ExecutionStartTime; Console.WriteLine("Use {0} ms for DBSCAN.GetClusters", ExecutionTime.TotalMilliseconds.ToString()); label_colors = Util.GiveMeNColors(dbclusters.Count); Console.WriteLine("Detected {0} clusters.", dbclusters.Count); ResetOverlay(state); // The following is to get the center, and depth for each cluster. Seems unnecessary to do it as this can be done in DBScan. for (int cluster = 0; cluster < dbclusters.Count; cluster++) if (dbclusters[cluster].Count>0) { int center_x = 0, center_y = 0, average_depth= 0 ; foreach (int bitmap_index in dbclusters[cluster]) { //int bitmap_index = Util.toID(point.X, point.Y, width, height, kColorStride); state.overlay_bitmap_bits_[bitmap_index + 2] = (int)label_colors[cluster].Item1; state.overlay_bitmap_bits_[bitmap_index + 1] = (int)label_colors[cluster].Item2; state.overlay_bitmap_bits_[bitmap_index + 0] = (int)label_colors[cluster].Item3; System.Drawing.Point point = Util.toXY( bitmap_index, 640, 480, 1); center_x += point.X; center_y += point.Y; average_depth += state.depth[bitmap_index]; } // Get majority label within this cluster label_counts = new int[state.feature.num_classes_]; Array.Clear(label_counts, 0, label_counts.Length); foreach (int point_index in dbclusters[cluster]) label_counts[state.predict_labels_[point_index]]++; max = Util.MaxNonBackground(label_counts); Debug.Assert(dbclusters[cluster].Count>0); center = new System.Drawing.Point( (int)( center_x/ dbclusters[cluster].Count), (int)(center_y/ dbclusters[cluster].Count) ); // use average to get the depth int depth = (int)(average_depth / dbclusters[cluster].Count); //center = new System.Drawing.Point(centroids[outlier].x(), centroids[outlier].y()); gestures.Add(new Pooled(center, depth, (HandGestureFormat)max.Item1)); Console.WriteLine("Center: ({0}px, {1}px, {2}mm), Gesture: {3}", center.X, center.Y, depth, (HandGestureFormat)max.Item1); } state.overlay_start_.Value = true; break; #endregion #region Majority centroid case PoolType.MedianMajority: case PoolType.MeanMajority: // Median and mean pooling for the majority class. // // The majority class may have a lot of noise. The noise may // itself cause a false majority class. An improvement can be // a density based clustering method. label_counts = new int[state.feature.num_classes_]; Array.Clear(label_counts, 0, label_counts.Length); List<int>[] label_sorted_x = new List<int>[state.feature.num_classes_]; List<int>[] label_sorted_y = new List<int>[state.feature.num_classes_]; List<int>[] label_sorted_depth = new List<int>[state.feature.num_classes_]; for (int i = 1; i < state.feature.num_classes_; i++) { label_sorted_x[i] = new List<int>(); label_sorted_y[i] = new List<int>(); label_sorted_depth[i] = new List<int>(); } for (int y = state.crop.Value.Y; y <= state.crop.Value.Y + state.crop.Value.Height; y++) { for (int x = state.crop.Value.X; x <= state.crop.Value.X + state.crop.Value.Width; x++) { int depth_index = Util.toID(x, y, width, height, kDepthStride); int predict_label = state.predict_labels_[depth_index]; label_counts[predict_label]++; if (predict_label != (int)HandGestureFormat.Background) { label_sorted_x[predict_label].Add(x); label_sorted_y[predict_label].Add(y); label_sorted_depth[predict_label].Add(state.depth[depth_index]); } } } max = Util.MaxNonBackground(label_counts); int max_index = max.Item1, max_value = max.Item2; int total_non_background = label_counts.Sum() - label_counts[0]; Console.WriteLine("Most common gesture is {0} (appears {1}/{2} times).", ((HandGestureFormat)max_index).ToString(), max_value, total_non_background); center = new System.Drawing.Point(); int center_depth = 0; if (max_value == 0) { center.X = width / 2; center.Y = height / 2; center_depth = 0; } else if (type == PoolType.MeanMajority) { center.X = (int)(label_sorted_x[max_index].Average()); center.Y = (int)(label_sorted_y[max_index].Average()); center_depth = (int)(label_sorted_depth[max_index].Average()); } else if (type == PoolType.MedianMajority) { label_sorted_x[max_index].Sort(); label_sorted_y[max_index].Sort(); label_sorted_depth[max_index].Sort(); center.X = (int)(label_sorted_x[max_index].ElementAt(max_value / 2)); center.Y = (int)(label_sorted_y[max_index].ElementAt(max_value / 2)); center_depth = (int)(label_sorted_depth[max_index].ElementAt(max_value / 2)); } gestures.Add(new Pooled(center, center_depth, (HandGestureFormat)max_index)); Console.WriteLine("Center: ({0}px, {1}px, {2}mm)", center.X, center.Y, center_depth); break; #endregion } return gestures; }
public GetBucketCapacitySummarySpectraS3Request WithPoolType(PoolType? poolType) { this._poolType = poolType; if (poolType != null) { this.QueryParams.Add("pool_type", poolType.ToString()); } else { this.QueryParams.Remove("pool_type"); } return this; }