Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Min() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
677 Examples
19
View Source File : CrossingAgent.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void AgentStep(float[] action)
{
float[] obstacleDistances = new float[others.Length];
float distance = Mathf.Abs(myGoal.transform.position.x - transform.position.x);
for (int i = 0; i < others.Length; i++)
{
if (!others[i].activeSelf)
{
Debug.Log("There are some unactive agents!");
obstacleDistances[i] = 10*socialZone;
reward = -0.005f;
}
else
{
obstacleDistances[i] = Mathf.Sqrt(Mathf.Pow((others[i].transform.position.x - transform.position.x), 2) + Mathf.Pow((others[i].transform.position.z - transform.position.z), 2));
if (obstacleDistances[i] <= intimateZone)
{
//reward = -0.050f;
done = true;
reward = -1f;
failures += 1;
}
else if (obstacleDistances[i] <= personalZone) { reward = -0.010f; }
else if (obstacleDistances[i] <= socialZone) { reward = -0.0075f; }
else if (distance <= prevDistance)
{
prevDistance = distance;
reward = 0.005f;
}
else {
prevDistance = distance;
reward = -0.005f;
}
}
}
MoveAgent(action);
if (transform.position.y < 0.0f
|| Mathf.Abs(transform.position.x - area.transform.position.x) > 10f
|| Mathf.Abs(transform.position.z - area.transform.position.z) > 5f
)
{
done = true;
reward = -1f;
failures += 1;
}
Monitor.Log("Reward", reward, MonitorType.slider, monitor.transform);
Monitor.Log("OtherDistance", obstacleDistances.Min(), MonitorType.slider, monitor.transform);
if (trainingText != null)
{
trainingText.text = string.Format("R:{0} [{1};{2}]", reward, solved, failures);
}
}
19
View Source File : PedestriansAgent.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void AgentStep(float[] action)
{
//GameObject target = new GameObject();
//Vector3 velocity = Vector3.zero;
switch ((int)action[0])
{
case 0: //BACKWARDS
//agentX -= directionX * step;
break;
case 1: //FORWARD
agentX += directionX * step;
//transform.GetChild(0).LookAt(target.transform);
//target.transform.position = Vector3.SmoothDamp(transform.GetChild(0).position, transform.GetChild(0).position + new Vector3(directionX * 5, 0, 0), ref velocity, 0.3f);
break;
case 2: //LEFT
agentZ -= directionZ * step;
//transform.GetChild(0).LookAt(target.transform);
//target.transform.position = Vector3.SmoothDamp(transform.GetChild(0).position, transform.GetChild(0).position + new Vector3(directionX * 5, 0, directionZ*5), ref velocity, 0.3f);
break;
case 3: //RIGHT
agentZ += directionZ * step;
//transform.GetChild(0).LookAt(target.transform);
//target.transform.position = Vector3.SmoothDamp(transform.GetChild(0).position, transform.GetChild(0).position + new Vector3(directionX * 5, 0, -directionZ*5), ref velocity, 0.3f);
break;
case 4: //BACKWARDS + LEFT
//agentX -= directionX * step / 2;
//agentZ += directionZ * step / 2;
break;
case 5: //FORWARD LEFT
agentX += directionX * step / 2;
agentZ += directionZ * step / 2;
//transform.GetChild(0).LookAt(target.transform);
//target.transform.position = Vector3.SmoothDamp(transform.GetChild(0).position, transform.GetChild(0).position + new Vector3(directionX * 5, 0, directionZ*3), ref velocity, 0.3f);
break;
case 6: //BACKWARDS RIGHT
//agentX -= directionX * step / 2;
//agentZ -= directionZ * step / 2;
break;
case 7: //FORWARD RIGHT
agentX += directionX * step / 2;
agentZ -= directionZ * step / 2;
//transform.GetChild(0).LookAt(target.transform);
//target.transform.position = Vector3.SmoothDamp(transform.GetChild(0).position, transform.GetChild(0).position + new Vector3(directionX * 5, 0, -directionZ*3), ref velocity, 0.3f);
break;
default:
return;
}
float obstacleDistance = 0;
float[] tempObstacleDistances = new float[obstacles.Length];
for(int i=0; i<obstacles.Length; i++)
{
//obstacleX += UnityEngine.Random.Range(-directionX * step, directionX * step / 2);
//obstacleZ += UnityEngine.Random.Range(-directionZ * step, directionZ * step);
//obstacles[i].transform.position = new Vector3(obstacleX, 0, obstacleZ);
if (obstacles[i].tag != "agent")
{
float speed = step;// / obstacles.Length;
obstacles[i].transform.position = new Vector3(obstacles[i].transform.position.x+(-directionX*speed), 0, obstacles[i].transform.position.z);
//obstacles[i].transform.position.x + UnityEngine.Random.Range(-directionX * speed, directionX * speed / 2),
//0,
//obstacles[i].transform.position.z + UnityEngine.Random.Range(-directionZ * speed, directionZ * speed));
}
if (goal.transform.position.x - obstacles[i].transform.position.x < goal.transform.position.x - agentX)
{
tempObstacleDistances[i] = Mathf.Sqrt(Mathf.Pow((obstacles[i].transform.position.x - agentX), 2) + Mathf.Pow((obstacles[i].transform.position.z - agentZ), 2));
}
else
{
tempObstacleDistances[i] = maxDistance;
}
//if(tempObstacleDistance < obstacleDistance)
//{
// obstacleDistance = tempObstacleDistance;
//}
//if (tempObstacleDistances[i] <= personalZone)
//{
// obstacleDistance = tempObstacleDistances[i];
//}
//else
//{
// obstacleDistance += tempObstacleDistances[i];
//}
}
obstacleDistance = tempObstacleDistances.Min();
//obstacleDistance = obstacleDistance / obstacles.Length;
agent.transform.position = new Vector3(agentX, 0, agentZ);
goal.transform.position = new Vector3(goalX, 0, goalZ);
float distance = Mathf.Sqrt(Mathf.Pow((goalX - agentX), 2) + Mathf.Pow((goalZ - agentZ), 2));
//float obstacleDistance = Mathf.Sqrt(Mathf.Pow((obstacleX - agentX), 2) + Mathf.Pow((obstacleZ - agentZ), 2));
reward = calculateReward(distance, obstacleDistance, obstacles.Length);
if (showMonitor)
{
Monitor.Log("Reward", reward, MonitorType.slider, agent.transform);
Monitor.Log("Distance", distance / maxDistance, MonitorType.slider, agent.transform);
Monitor.Log("Obstacle Distance", obstacleDistance / 3, MonitorType.slider, agent.transform);
Monitor.Log("State", state, MonitorType.text, agent.transform);
}
if (trainingText != null)
{
trainingText.text = string.Format("D:{0} / OD:{1} / R:{2} [{3};{4};{5}]", distance, obstacleDistance, reward, solved, failures, obstacleHit);
}
if(replacedulativeText != null)
{
replacedulativeText.text = string.Format("CR:{0} / S:{1}", replacedulativeReward, state);
}
if (isDone)
{
done = true;
isDone = false;
return;
}
}
19
View Source File : ObstacleCurriculumAgent.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void AgentStep(float[] action)
{
switch ((int)action[0])
{
case 0:
agentX -= directionX * step;
break;
case 1:
agentX += directionX * step;
break;
case 2:
agentZ -= directionZ * step;
break;
case 3:
agentZ += directionZ * step;
break;
case 4:
agentX -= directionX * step / 2;
agentZ += directionZ * step / 2;
break;
case 5:
agentX += directionX * step / 2;
agentZ += directionZ * step / 2;
break;
case 6:
agentX -= directionX * step / 2;
agentZ -= directionZ * step / 2;
break;
case 7:
agentX += directionX * step / 2;
agentZ -= directionZ * step / 2;
break;
default:
return;
}
float obstacleDistance = 0;
float[] tempObstacleDistances = new float[obstacles.Length];
for(int i=0; i<obstacles.Length; i++)
{
//obstacleX += UnityEngine.Random.Range(-directionX * step, directionX * step / 2);
//obstacleZ += UnityEngine.Random.Range(-directionZ * step, directionZ * step);
//obstacles[i].transform.position = new Vector3(obstacleX, 0, obstacleZ);
obstacles[i].transform.position = new Vector3(
obstacles[i].transform.position.x + UnityEngine.Random.Range(-directionX * step, directionX * step / 2),
0,
obstacles[i].transform.position.z + UnityEngine.Random.Range(-directionZ * step, directionZ * step));
tempObstacleDistances[i] = Mathf.Sqrt(Mathf.Pow((obstacles[i].transform.position.x - agentX), 2) + Mathf.Pow((obstacles[i].transform.position.z - agentZ), 2));
//if(tempObstacleDistance < obstacleDistance)
//{
// obstacleDistance = tempObstacleDistance;
//}
//if (tempObstacleDistances[i] <= personalZone)
//{
// obstacleDistance = tempObstacleDistances[i];
//}
//else
//{
// obstacleDistance += tempObstacleDistances[i];
//}
}
obstacleDistance = tempObstacleDistances.Min();
//obstacleDistance = obstacleDistance / obstacles.Length;
agent.transform.position = new Vector3(agentX, 0, agentZ);
goal.transform.position = new Vector3(goalX, 0, goalZ);
float distance = Mathf.Sqrt(Mathf.Pow((goalX - agentX), 2) + Mathf.Pow((goalZ - agentZ), 2));
//float obstacleDistance = Mathf.Sqrt(Mathf.Pow((obstacleX - agentX), 2) + Mathf.Pow((obstacleZ - agentZ), 2));
reward = calculateReward(distance, obstacleDistance);
Monitor.Log("Reward", reward, MonitorType.slider, agent.transform);
Monitor.Log("Distance", distance/maxDistance, MonitorType.slider, agent.transform);
Monitor.Log("Obstacle Distance", obstacleDistance/3, MonitorType.slider, agent.transform);
Monitor.Log("State", state, MonitorType.text, agent.transform);
if (trainingText != null)
{
trainingText.text = string.Format("D:{0} / OD:{1} / R:{2} [{3};{4};{5}]", distance, obstacleDistance, reward, solved, failures, obstacleHit);
}
if(replacedulativeText != null)
{
replacedulativeText.text = string.Format("CR:{0} / S:{1}", replacedulativeReward, state);
}
if (isDone)
{
done = true;
isDone = false;
return;
}
}
19
View Source File : NetworkSession.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private bool Retransmit(uint sequence)
{
if (cachedPackets.TryGetValue(sequence, out var cachedPacket))
{
packetLog.DebugFormat("[{0}] Retransmit {1}", session.LoggingIdentifier, sequence);
if (!cachedPacket.Header.HasFlag(PacketHeaderFlags.Retransmission))
cachedPacket.Header.Flags |= PacketHeaderFlags.Retransmission;
SendPacketRaw(cachedPacket);
return true;
}
if (cachedPackets.Count > 0)
{
// This is to catch a race condition between .Count and .Min() and .Max()
try
{
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache range {cachedPackets.Keys.Min()} - {cachedPackets.Keys.Max()}.");
}
catch
{
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache is empty. Race condition threw exception.");
}
}
else
log.Error($"Session {session.Network?.ClientId}\\{session.EndPoint} ({session.Account}:{session.Player?.Name}) retransmit requested packet {sequence} not in cache. Cache is empty.");
return false;
}
19
View Source File : AsyncHelper.Tests.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public async Task TestTaskWillFinish()
{
var tasksFactories = new List<Func<Task>>();
for (int i = 0; i < expectedCount; i++)
{
int copy = i;
tasksFactories.Add(() => SetPosition(copy, array));
}
var startTime = DateTime.UtcNow;
await AsyncHelper.InvokeTasksByQueue(tasksFactories, threads);
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime > TimeSpan.FromSeconds(expectedMinWait / 1000));
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(expectedMaxWait / 1000));
replacedert.AreEqual(array.Min(), 1);
replacedert.AreEqual(array.Max(), 1);
}
19
View Source File : AsyncHelper.Tests.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public async Task TestAllItemsChangedInPool()
{
var startTime = DateTime.UtcNow;
await books.ForEachInThreadsPool(async (book) =>
{
await Task.Delay(fakeWait);
book.Id++;
}, threads);
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime > TimeSpan.FromSeconds(expectedMinWait / 1000));
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(expectedMaxWait / 1000));
replacedert.AreEqual(books.Select(t => t.Id).Min(), 1);
replacedert.AreEqual(books.Select(t => t.Id).Max(), 1);
}
19
View Source File : AsyncHelper.Tests.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public async Task TestAllItemsChangedParallel()
{
var startTime = DateTime.UtcNow;
await books.ForEachParallel(async (book) =>
{
await Task.Delay(fakeWait);
book.Id++;
});
var endTime = DateTime.UtcNow;
var executionTime = endTime - startTime;
replacedert.IsTrue(executionTime < TimeSpan.FromSeconds(0.6));
replacedert.AreEqual(books.Select(t => t.Id).Min(), 1);
replacedert.AreEqual(books.Select(t => t.Id).Max(), 1);
}
19
View Source File : ListExtends.Test.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public void Shuffle()
{
var list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11 };
list.Shuffle();
var shuffled =
list[0] != 0 ||
list[1] != 1 ||
list[2] != 2 ||
list[3] != 3;
var countNotChanged = list.Distinct().Count() == list.Count - 1;
var inRange = list.Max() == 11 && list.Min() == 0;
replacedert.IsTrue(shuffled && countNotChanged && inRange);
}
19
View Source File : Counter.Tests.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[TestMethod]
public async Task TestCounter()
{
var counter = new Counter();
replacedert.AreEqual(counter.GetCurrent, 0);
var obj = new object();
var numbers = new int[10000];
var tasksList = new ConcurrentBag<Task>();
for (int i = 0; i < 100; i++)
{
var task = Task.Run(() =>
{
for (int k = 0; k < 100; k++)
{
var uniqueNo = counter.GetUniqueNo();
numbers[uniqueNo - 1]++;
}
});
lock (obj)
{
tasksList.Add(task);
}
}
await Task.WhenAll(tasksList);
replacedert.AreEqual(counter.GetCurrent, 10000);
replacedert.AreEqual(numbers.Max(), 1);
replacedert.AreEqual(numbers.Min(), 1);
}
19
View Source File : MathAnalyzeDataQuery.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
protected override void Execute(System.Activities.CodeActivityContext context)
{
DataTable table = this.ExecuteQuery(context);
if (table.Columns == null || table.Columns.Count == 0)
{
throw new ArgumentException("Query result must have at least one column");
}
List<decimal> inputValues = new List<decimal>();
for (int rowNumber = 0; rowNumber < table.Rows.Count; rowNumber++)
{
decimal parsedValue = 0;
if (decimal.TryParse(table.Rows[rowNumber][1].ToString(), out parsedValue))
{
inputValues.Add(parsedValue);
}
}
this.NumberOfItems.Set(context, inputValues.Count);
if (inputValues.Any())
{
this.Mean.Set(context, this.RoundValue(context, inputValues.Average()));
this.Median.Set(context, this.RoundValue(context, this.CalculateMedian(inputValues)));
this.Highest.Set(context, this.RoundValue(context, inputValues.Max()));
this.Lowest.Set(context, this.RoundValue(context, inputValues.Min()));
this.StandardDeviation.Set(context, this.RoundValue(context, CalculateStandardDeviation(inputValues)));
}
}
19
View Source File : DebugViewXNA.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
private void DrawPerformanceGraph()
{
_graphValues.Add(World.UpdateTime / TimeSpan.TicksPerMillisecond);
if (_graphValues.Count > ValuesToGraph + 1)
_graphValues.RemoveAt(0);
float x = PerformancePanelBounds.X;
float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph;
float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top;
// we must have at least 2 values to start rendering
if (_graphValues.Count > 2)
{
_max = _graphValues.Max();
_avg = _graphValues.Average();
_min = _graphValues.Min();
if (AdaptiveLimits)
{
MaximumValue = _max;
MinimumValue = 0;
}
// start at last value (newest value added)
// continue until no values are left
for (int i = _graphValues.Count - 1; i > 0; i--)
{
float y1 = PerformancePanelBounds.Bottom - ((_graphValues[i] / (MaximumValue - MinimumValue)) * yScale);
float y2 = PerformancePanelBounds.Bottom - ((_graphValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);
Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
Vector2 x2 = new Vector2(MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
DrawSegment(x1, x2, Color.LightGreen);
x += deltaX;
}
}
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, string.Format("Max: {0} ms", _max));
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Center.Y - 7, string.Format("Avg: {0} ms", _avg));
DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, string.Format("Min: {0} ms", _min));
//Draw background.
_background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y);
_background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
_background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y);
DrawSolidPolygon(_background, 4, Color.DarkGray, true);
}
19
View Source File : MapboxUnitTests_SQLiteCache.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void logTime(string label, List<long> elapsed)
{
double overall = elapsed.Sum() / 1000.0;
double min = elapsed.Min() / 1000.0;
double max = elapsed.Max() / 1000.0;
double avg = elapsed.Average() / 1000.0;
double sum = elapsed.Sum(d => Math.Pow(d - avg, 2));
double stdDev = (Math.Sqrt((sum) / (elapsed.Count - 1))) / 1000.0;
ued.Log(string.Format(
CultureInfo.InvariantCulture
, "[{0}] {1} items, overall time:{2,6:0.000}s avg:{3,6:0.000}s min:{4,6:0.000}s max:{5,6:0.000}s stdDev:{6,6:0.000}s"
, label
, elapsed.Count
, overall
, avg
, min
, max
, stdDev
));
}
19
View Source File : ContourSeries.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
protected internal override void UpdateMaxMin()
{
this.MinX = this.ColumnCoordinates.Min();
this.MaxX = this.ColumnCoordinates.Max();
this.MinY = this.RowCoordinates.Min();
this.MaxY = this.RowCoordinates.Max();
}
19
View Source File : HeatMapSeries.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
protected internal override void UpdateMaxMin()
{
base.UpdateMaxMin();
this.MinX = Math.Min(this.X0, this.X1);
this.MaxX = Math.Max(this.X0, this.X1);
this.MinY = Math.Min(this.Y0, this.Y1);
this.MaxY = Math.Max(this.Y0, this.Y1);
this.MinValue = this.GetData().Min();
this.MaxValue = this.GetData().Max();
this.XAxis.Include(this.MinX);
this.XAxis.Include(this.MaxX);
this.YAxis.Include(this.MinY);
this.YAxis.Include(this.MaxY);
this.ColorAxis.Include(this.MinValue);
this.ColorAxis.Include(this.MaxValue);
}
19
View Source File : ZigZag.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private decimal GetExtremum(List<Candle> candles, int period, string points, int index)
{
try
{
List<decimal> values = new List<decimal>();
for (int i = index; i >= index - period; i--)
values.Add(candles[i].GetPoint(points));
if (points == "High")
return values.Max();
if (points == "Low")
return values.Min();
}
catch (Exception e)
{
}
return 0;
}
19
View Source File : DynamicTrendDetector.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private decimal GetValue(List<Candle> candles,int index)
{
if (index <= 2)
{
Period = 0;
}
decimal currentCandleClose = candles[index].Close;
if (Values == null || Values.Count == 0)
{
return currentCandleClose;
}
decimal previousTrendClose = Values[Math.Max(0, index - 2)];
decimal currentTrendClose = Values[Math.Max(0, index - 1)];
decimal previousCandleClose = candles[Math.Max(0, index - 1)].Close;
if (index >= 1)
{
if (currentTrendClose < currentCandleClose)
{
if (currentSide != Side.Buy)
{
Period = 0;
}
currentSide = Side.Buy;
} else if (currentTrendClose >= currentCandleClose)
{
if (currentSide != Side.Sell)
{
Period = 0;
}
currentSide = Side.Sell;
} else
{
currentSide = Side.None;
Period = 0;
}
}
List<Candle> subList;
List<decimal> highs;
List<decimal> lows;
int startIdx;
int numItems;
decimal value;
decimal highest;
decimal lowest;
decimal correctionPercent = Decimal.Divide(CorrectionCoeff, 100);
decimal coeffUp = 1m - correctionPercent;
decimal coeffDown = 1m + correctionPercent;
if (Period < Lenght)
{
if (currentSide != Side.None)
{
startIdx = Math.Max(0, index - Period-1);
numItems = Math.Max(1, Period - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
Period += 1;
if (currentSide == Side.Buy)
{
highest = highs.Max();
value = highest * coeffUp;
} else
{
lowest = lows.Min();
value = lowest * coeffDown;
}
return value;
} else
{
return currentTrendClose;
}
} else
{
startIdx = Math.Max(0, index - Lenght -1);
numItems = Math.Max(1, Lenght - 1);
subList = candles.GetRange(startIdx, numItems);
highs = subList.Select(o => o.High).ToList();
lows = subList.Select(o => o.Low).ToList();
return currentSide == Side.Buy ? highs.Max() * coeffUp : lows.Min() * coeffDown;
}
}
19
View Source File : Benchmark.cs
License : Apache License 2.0
Project Creator : alexyakunin
License : Apache License 2.0
Project Creator : alexyakunin
public override string ToString()
{
if (!Timings.Any())
return $"{replacedle}: n/a";
var count = Timings.Count;
var midPointL = (count - 1) / 2;
var midPointR = count / 2;
var min = Timings.Min().TotalMilliseconds;
var max = Timings.Max().TotalMilliseconds;
var avg = Timings.Average(t => t.TotalMilliseconds);
var p50 = (Timings[midPointL] + Timings[midPointR]).TotalMilliseconds / 2;
return $"{replacedle}: {avg:0.000}ms avg -- [{min:0.000}ms ... {p50:0.000}ms ... {max:0.000}ms] in {count} run(s)";
}
19
View Source File : OutputHelper.cs
License : Apache License 2.0
Project Creator : alexyakunin
License : Apache License 2.0
Project Creator : alexyakunin
public static void AppendHistogram(this IndentedTextWriter writer,
string replacedle, double[] data, string unit,
string format = "0.####",
double[] percentiles = null)
{
percentiles = percentiles ?? DefaultPercentiles;
IndentedTextWriter AppendLine(string s) => writer.AppendLine(s);
IndentedTextWriter AppendMetric(string name, double value) => writer.AppendMetric(name, value, unit);
using (writer.Section($"{replacedle}")) {
if (data.Length == 0) {
AppendLine("No data.");
return;
}
AppendLine("Min .. Max:");
using (writer.Indent()) {
AppendMetric("Min", data.Min());
AppendMetric("Avg", data.Average());
AppendMetric("Max", data.Max());
}
if (percentiles.Length > 0) {
AppendLine("Percentiles:");
using (writer.Indent()) {
var maxIndex = data.Length - 1;
foreach (var p in percentiles)
AppendMetric($"{p:#.##}%", data[(int) (maxIndex * p / 100)]);
}
}
}
}
19
View Source File : ConvexHullAlgorithm.Initialize.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private int DetermineDimension()
{
var r = new Random();
var dimensions = new List<int>();
for (var i = 0; i < 10; i++)
dimensions.Add(Vertices[r.Next(NumberOfVertices)].Position.Length);
var dimension = dimensions.Min();
if (dimension != dimensions.Max())
throw new ConvexHullGenerationException(ConvexHullCreationResultOutcome.NonUniformDimension, "Invalid input data (non-uniform dimension).");
return dimension;
}
19
View Source File : DataColumnReader.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
private long GetFileOffset()
{
//get the minimum offset, we'll just read pages in sequence
return
new[]
{
_thriftColumnChunk.Meta_data.Dictionary_page_offset,
_thriftColumnChunk.Meta_data.Data_page_offset
}
.Where(e => e != 0)
.Min();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : anastasios-stamoulis
License : MIT License
Project Creator : anastasios-stamoulis
static public System.Drawing.Bitmap createBitmap(float[] src, int gridIndex, int width, int height, bool adjustColorRange, int numChannels) {
SciColorMaps.Portable.ColorMap cmap = null;
var colorScaleFactor = 1.0;
var numPixels = width * height;
if (adjustColorRange) {
var maxValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Max();
var minValue = src.Skip(gridIndex * numPixels * numChannels).Take(numPixels * numChannels).Min();
if (numChannels == 1) {
cmap = new SciColorMaps.Portable.ColorMap("viridis", minValue, maxValue);
}
colorScaleFactor = (float)(254.0 / maxValue);
}
var bitmap = new System.Drawing.Bitmap(width, height);
var srcStart = gridIndex * numPixels;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
var pos = srcStart + row * width + col;
if (cmap!=null) {
var rgb = cmap[colorScaleFactor * src[pos]];
var color = System.Drawing.Color.FromArgb(rgb[0], rgb[1], rgb[2]);
bitmap.SetPixel(col, row, color);
}
else {
var b = (int)(colorScaleFactor * src[pos]);
var g = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + numPixels]);
var r = (numChannels == 1) ? b : (int)(colorScaleFactor * src[pos + 2 * numPixels]);
bitmap.SetPixel(col, row, System.Drawing.Color.FromArgb(r, g, b));
}
}
}
return bitmap;
}
19
View Source File : TimeUnit.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public static TimeUnit GetBestTimeUnit(params double[] values)
{
if (values.Length == 0)
return Nanosecond;
// Use the largest unit to display the smallest recorded measurement without loss of precision.
double minValue = values.Min();
foreach (var timeUnit in All)
if (minValue < timeUnit.NanosecondAmount * 1000)
return timeUnit;
return All.Last();
}
19
View Source File : Histogram.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
[Pure, NotNull]
internal static Histogram BuildManual(double binSize, [NotNull] double[][] bins)
{
var histogramBins = bins.Select(bin => new HistogramBin(bin.Any() ? bin.Min() : 0, bin.Any() ? bin.Max() : 0, bin)).ToArray();
return new Histogram(binSize, histogramBins);
}
19
View Source File : QuickSelectAdaptive.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public double Select([NotNull] double[] values, int k)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (values.Length == 0)
throw new ArgumentOutOfRangeException(nameof(values), "values.Length should be positive");
if (k < 0)
throw new ArgumentOutOfRangeException(nameof(k), $"k ({k}) should be positive");
if (k >= values.Length)
throw new ArgumentOutOfRangeException(nameof(k),
$"k ({k}) should be less than values.Length ({values.Length})");
if (k == 0)
return values.Min();
if (k == values.Length - 1)
return values.Max();
return Select(values, k, 0, values.Length - 1);
}
19
View Source File : FrequencyUnit.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public static FrequencyUnit GetBestFrequencyUnit(params double[] values)
{
if (values.Length == 0)
return Hz;
// Use the largest unit to display the smallest recorded measurement without loss of precision.
double minValue = values.Min();
foreach (var frequencyUnit in All)
if (minValue < frequencyUnit.HertzAmount * 1000)
return frequencyUnit;
return All.Last();
}
19
View Source File : QuantileCompareFunction.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public Range GetRange([NotNull] Sample a, [NotNull] Sample b, Probability margin, int? quantizationCount = null)
{
replacedertion.NotNull(nameof(a), a);
replacedertion.NotNull(nameof(b), b);
replacedertion.InRangeInclusive(nameof(margin), margin, 0, 0.5);
if (quantizationCount.HasValue)
replacedertion.Positive(nameof(quantizationCount), quantizationCount.Value);
double left = margin.Value;
double right = 1 - left;
int count = quantizationCount ?? (int)Math.Round((right - left) / 0.01 + 1);
var probabilities = new Probability[count];
if (count == 1)
probabilities[0] = Probability.Half;
else
for (int i = 0; i < count; i++)
probabilities[i] = left + (right - left) / (count - 1) * i;
double[] quantileValues = GetValues(a, b, probabilities);
return Range.Of(quantileValues.Min(), quantileValues.Max());
}
19
View Source File : AdaptiveHistogramBuilder.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public Histogram Build(IReadOnlyList<double> values, double binSize)
{
const double eps = 1e-9;
const double margin = 0.1;
const double adaptiveFactor = 0.02;
if (binSize < eps)
throw new ArgumentException(
$"binSize ({binSize.ToString("0.##", DefaultCultureInfo.Instance)}) should be a positive number",
nameof(binSize));
if (binSize < Resolution)
binSize = Resolution;
binSize = NiceCeiling(binSize);
var list = values.ToList();
if (list.Count == 0)
throw new ArgumentException("Values should be non-empty", nameof(values));
list.Sort();
if (list.Last() - list.First() < binSize)
{
double center = (list.First() + list.Last()) / 2;
double lower = center - binSize / 2;
double upper = center + binSize / 2;
return new Histogram(binSize, new[] {new HistogramBin(lower, upper, list.ToArray())});
}
var points = new List<double> {NiceFloor(list.Min() - binSize / 2), NiceCeiling(list.Max() + binSize / 2)};
int processedPointCount = 0;
while (true)
{
if (points.Count > 10 * list.Count)
{
var errorMessage = new StringBuilder();
errorMessage.AppendLine("Failed to run AdaptiveHistogramBuilder.BuildWithFixedBinSize");
errorMessage.AppendLine("BinSize: " + binSize.ToString("N12", DefaultCultureInfo.Instance));
errorMessage.AppendLine("Values: ");
foreach (double value in list)
errorMessage.AppendLine(" " + value.ToString("N12", DefaultCultureInfo.Instance));
throw new InvalidOperationException(errorMessage.ToString());
}
int pointIndex = -1;
for (int i = processedPointCount; i < points.Count - 1; i++)
{
double adaptiveBinSize = (points[i] + points[i + 1]) / 2.0 * adaptiveFactor;
double maxSize = Math.Max(binSize * (1.0 + 2 * margin), adaptiveBinSize);
if (points[i + 1] - points[i] > maxSize)
{
pointIndex = i;
break;
}
}
if (pointIndex == -1)
break;
double lower = points[pointIndex];
double upper = points[pointIndex + 1];
int bestIndex1 = -1;
int bestIndex2 = -1;
int bestCount = -1;
double bestDist = double.MaxValue;
bool Inside(double x) => x > lower - eps && x < upper - eps;
for (int i = 0; i < list.Count; i++)
if (Inside(list[i]))
{
int j = i;
while (j < list.Count && Inside(list[j]) && list[j] - list[i] < binSize)
j++;
int count = j - i;
double dist = list[j - 1] - list[i];
if (count > bestCount || count == bestCount && dist < bestDist)
{
bestCount = count;
bestIndex1 = i;
bestIndex2 = j - 1;
bestDist = dist;
}
}
if (bestIndex1 != -1)
{
double center = (list[bestIndex1] + list[bestIndex2]) / 2.0;
double adaptiveBinSize = Math.Max(binSize, center * adaptiveFactor);
double left = NiceFloor(center - adaptiveBinSize / 2);
double right = NiceFloor(Math.Min(center + adaptiveBinSize / 2, upper));
if (left > lower + binSize * margin)
points.Insert(pointIndex + 1, left);
else if (right < upper - binSize * margin && right > lower + binSize * margin)
{
points.Insert(pointIndex + 1, right);
processedPointCount++;
}
else
processedPointCount++;
}
else
{
points.Insert(pointIndex + 1, NiceFloor(lower + binSize));
processedPointCount++;
}
}
var bins = new List<HistogramBin>(points.Count - 1);
int counter = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var bin = new List<double>();
double lower = points[i];
double upper = points[i + 1];
while (counter < list.Count && (list[counter] < upper || i == points.Count - 1))
bin.Add(list[counter++]);
bins.Add(new HistogramBin(lower, upper, bin.ToArray()));
}
// Trim
while (bins.Any() && bins.First().IsEmpty)
bins.RemoveAt(0);
while (bins.Any() && bins.Last().IsEmpty)
bins.RemoveAt(bins.Count - 1);
// Join small bins to neighbors
counter = 0;
double lastValue = 0;
while (counter < bins.Count)
{
if (bins[counter].HasAny)
lastValue = Math.Max(lastValue, bins[counter].Values.Last());
double adaptiveThreshold = Math.Max(binSize / 3, lastValue * adaptiveFactor);
if (bins[counter].Gap < adaptiveThreshold)
{
double leftGap = counter > 0 ? bins[counter - 1].Gap : double.MaxValue;
double rightGap = counter < bins.Count - 1 ? bins[counter + 1].Gap : double.MaxValue;
if (leftGap < rightGap && counter > 0)
{
bins[counter - 1] = HistogramBin.Union(bins[counter - 1], bins[counter]);
bins.RemoveAt(counter);
}
else if (counter < bins.Count - 1)
{
bins[counter] = HistogramBin.Union(bins[counter], bins[counter + 1]);
bins.RemoveAt(counter + 1);
}
else
counter++;
}
else
counter++;
}
return new Histogram(binSize, bins.ToArray());
}
19
View Source File : VisualTreeExtensions.cs
License : MIT License
Project Creator : anjoy8
License : MIT License
Project Creator : anjoy8
public static Rect GetBoundingRect(this FrameworkElement dob, FrameworkElement relativeTo = null)
{
if (DesignMode.DesignModeEnabled)
{
return Rect.Empty;
}
if (relativeTo == null)
{
relativeTo = Window.Current.Content as FrameworkElement;
}
if (relativeTo == null)
{
throw new InvalidOperationException("Element not in visual tree.");
}
if (dob == relativeTo)
{
return new Rect(0, 0, relativeTo.ActualWidth, relativeTo.ActualHeight);
}
var ancestors = dob.GetAncestors().ToArray();
if (!ancestors.Contains(relativeTo))
{
throw new InvalidOperationException("Element not in visual tree.");
}
var topLeft =
dob
.TransformToVisual(relativeTo)
.TransformPoint(new Point());
var topRight =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
dob.ActualWidth,
0));
var bottomLeft =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
0,
dob.ActualHeight));
var bottomRight =
dob
.TransformToVisual(relativeTo)
.TransformPoint(
new Point(
dob.ActualWidth,
dob.ActualHeight));
var minX = new[] { topLeft.X, topRight.X, bottomLeft.X, bottomRight.X }.Min();
var maxX = new[] { topLeft.X, topRight.X, bottomLeft.X, bottomRight.X }.Max();
var minY = new[] { topLeft.Y, topRight.Y, bottomLeft.Y, bottomRight.Y }.Min();
var maxY = new[] { topLeft.Y, topRight.Y, bottomLeft.Y, bottomRight.Y }.Max();
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
19
View Source File : SingleCourseController.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
private decimal GetStudentMin(List<SingleCourse> totalGradeSingleCourses, string leave)
{
if (totalGradeSingleCourses.Where(d => d.Leave == leave).Count()>0)
{
return (totalGradeSingleCourses.Where(d => d.Leave == leave)?.Select(d => d.TotalScore)?.Min()).ObjToDecimal();
}
else
{
return 0;
}
}
19
View Source File : AbnormalDetection.cs
License : MIT License
Project Creator : aoso3
License : MIT License
Project Creator : aoso3
public double[][][] Detect()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
List<double> eucledianDist = new List<double>();
for (int k = 0; k < total_frames; k++)
{
for (int q = 0; q < cluster_n; q++)
{
double temp = 0;
for (int w = 0; w < 8; w++)
temp += MegaBlock[i][j][k][w] * MegaBlock[i][j][k][w] - codewords[i][j][q][w] * codewords[i][j][q][w];
eucledianDist.Add(Math.Sqrt(temp));
}
if (!Double.IsNaN(eucledianDist.Min()) && !Double.IsInfinity(eucledianDist.Min()))
minDistMatrix[k][i][j] = eucledianDist.Min();
else
minDistMatrix[k][i][j] = 0;
eucledianDist.Clear();
}
}
}
return minDistMatrix;
}
19
View Source File : ListView.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
public void Render(Rect rect, IEnumerable<T> itemList, float elementHeight = 20f, float elementPadding = 1f)
{
var totalElementHeight = elementHeight + elementPadding;
var width = rect.width;
var height = rect.height;
if (!object.ReferenceEquals(itemList, _itemList))
{
_itemList = itemList;
_filteredList = null;
}
GUI.BeginGroup(rect);
// Search Field
var searchFieldRect = new Rect(5f, 5f, width - 25f, elementHeight);
var lastSearchString = _searchString;
GUI.SetNextControlName("Apex_ListView_Search");
_searchString = EditorGUI.TextField(searchFieldRect, _searchString, SharedStyles.BuiltIn.searchFieldStyle);
EditorGUI.FocusTextInControl("Apex_ListView_Search");
var searchCancelRect = new Rect(searchFieldRect.x + searchFieldRect.width, 5f, 10f, elementHeight);
if (GUI.Button(searchCancelRect, GUIContent.none, string.IsNullOrEmpty(_searchString) ? SharedStyles.BuiltIn.searchCancelButtonEmpty : SharedStyles.BuiltIn.searchCancelButton))
{
_searchString = string.Empty;
GUIUtility.keyboardControl = 0;
}
// filter list based on search string
if (_filteredList == null || !string.Equals(lastSearchString, _searchString, StringComparison.OrdinalIgnoreCase))
{
if (string.IsNullOrEmpty(_searchString))
{
_filteredList = _itemList as T[];
if (_filteredList == null)
{
_filteredList = _itemList.ToArray();
}
}
else
{
_filteredList = _itemList.Where(t => _searchPredicate(t, _searchString)).ToArray();
}
_selectRangeStart = _selectRangeEnd = -1;
_selectedIndexes.Clear();
}
// Scroll View
var noneItemAdjust = _allowNoneSelect ? 1 : 0;
float listStartY = searchFieldRect.y + searchFieldRect.height + 5f;
var scrollViewRect = new Rect(0f, listStartY, width, height - listStartY);
var innerScrollView = new Rect(0f, 0f, scrollViewRect.width - 20f, (_filteredList.Length + noneItemAdjust) * totalElementHeight);
//Do preselect if applicable
var evt = Event.current;
if (evt != null && evt.type == EventType.Repaint && _selectPredicate != null)
{
_selectedIndexes.AddRange(_filteredList.Select((item, idx) => _selectPredicate(item) ? idx : -1).Where(idx => idx >= 0));
if (_selectedIndexes.Count > 0)
{
_selectRangeStart = _selectRangeEnd = _selectedIndexes.Min();
EnsureInView(_selectRangeStart, totalElementHeight, scrollViewRect.height);
}
_selectPredicate = null;
}
_scrollPos = GUI.BeginScrollView(scrollViewRect, _scrollPos, innerScrollView);
// Element List
int startIdx = Math.Max(Mathf.FloorToInt(_scrollPos.y / totalElementHeight) - noneItemAdjust, 0);
int endIdx = Math.Min(startIdx + Mathf.CeilToInt(Mathf.Min(scrollViewRect.height, innerScrollView.height) / totalElementHeight), _filteredList.Length);
if (_allowNoneSelect && _scrollPos.y < totalElementHeight)
{
var itemRect = new Rect(2f, 0f, innerScrollView.width, elementHeight);
var style = _noneSelected ? SharedStyles.BuiltIn.objectSelectorBoxActive : SharedStyles.BuiltIn.objectSelectorBoxNormal;
GUI.Box(itemRect, "None", style);
}
var currentY = (startIdx + noneItemAdjust) * totalElementHeight;
for (var i = startIdx; i < endIdx; i++)
{
var item = _filteredList[i];
var itemRect = new Rect(2f, currentY, innerScrollView.width, elementHeight);
var style = _selectedIndexes.Contains(i) ? SharedStyles.BuiltIn.objectSelectorBoxActive : SharedStyles.BuiltIn.objectSelectorBoxNormal;
GUI.Box(itemRect, _itemRenderer(item), style);
currentY += totalElementHeight;
}
GUI.EndScrollView();
//Handle mouse clicks and key presses
if (evt.type == EventType.MouseDown && evt.button == MouseButton.left)
{
evt.Use();
float adjustedMouseY = evt.mousePosition.y + (_scrollPos.y - listStartY);
var index = Mathf.FloorToInt(adjustedMouseY / totalElementHeight) - noneItemAdjust;
if (_allowNoneSelect && index < 0)
{
SelectNone();
}
else if (_allowMultiSelect)
{
if (evt.command || evt.control)
{
SingleToggle(index);
}
else if (evt.shift)
{
RangeSelect(index);
}
else
{
SingleSelect(index);
}
}
else
{
SingleSelect(index);
}
//We allow double-click selection under all cirreplacedstances
_singleSelected = (_onSelect != null) && (evt.clickCount == 2) && (_selectedIndexes.Count == 1 || _noneSelected);
if (!_singleSelected)
{
_owner.Repaint();
}
}
else if (evt.type == EventType.MouseUp && evt.button == MouseButton.left)
{
evt.Use();
if (_singleSelected)
{
// double click detected
DoSelect();
}
}
else if (evt.type == EventType.KeyUp)
{
if (evt.keyCode == KeyCode.DownArrow)
{
evt.Use();
if (_selectRangeStart < 0 && _allowNoneSelect && !_noneSelected)
{
SelectNone();
}
else if (_allowMultiSelect && evt.shift)
{
RangeSelect(_selectRangeEnd + 1);
}
else
{
SingleSelect(_selectRangeStart + 1);
}
EnsureInView(_selectRangeEnd, totalElementHeight, scrollViewRect.height);
}
else if (evt.keyCode == KeyCode.UpArrow)
{
evt.Use();
if (_selectRangeStart == 0 && _selectRangeEnd == 0 && _allowNoneSelect)
{
SelectNone();
}
else if (_selectRangeEnd < 0 && !_noneSelected)
{
SingleSelect(_filteredList.Length - 1);
}
else if (_allowMultiSelect && evt.shift)
{
RangeSelect(_selectRangeEnd - 1);
}
else
{
SingleSelect(_selectRangeStart - 1);
}
EnsureInView(_selectRangeStart, totalElementHeight, scrollViewRect.height);
}
else if (evt.keyCode == KeyCode.A && (evt.control || evt.command))
{
evt.Use();
_noneSelected = false;
AddSelected(0, _filteredList.Length - 1);
}
else if (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)
{
evt.Use();
if (_onSelect != null && (_selectedIndexes.Count > 0 || _noneSelected))
{
DoSelect();
}
}
}
GUI.EndGroup();
}
19
View Source File : SortTest.cs
License : MIT License
Project Creator : appie2go
License : MIT License
Project Creator : appie2go
[TestMethod]
public void SmallestValue_ShouldSelectFirsreplacedem()
{
// arrange
var n1 = Number.Create(1);
var n2 = Number.Create(2);
var n3 = Number.Create(3);
var values = new[] { n2, n1, n3 };
// act
var actual = values.Min();
// replacedert
actual.Should().Be(n1);
}
19
View Source File : FeatureVectorExtensions.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
public static Dictionary<string, float> Statistics(this float[] vector)
{
var mean = vector.Average();
return new Dictionary<string, float>
{
{ "min", vector.Min() },
{ "max", vector.Max() },
{ "mean", mean },
{ "var", vector.Average(v => (v - mean) * (v - mean)) }
};
}
19
View Source File : GrayColorMap.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
private void MakePaletteGrayscale()
{
#if !RECTANGULAR
var prevPalette = _palette;
// important: create new array for palette
_palette = new byte[PaletteColors][];
Func<byte[], byte> convertToGray;
switch (_options)
{
case GrayScaleOptions.Lightness:
convertToGray = color => (byte)((color.Max() + color.Min()) / 2);
break;
case GrayScaleOptions.Average:
convertToGray = color => (byte)((color[0] + color[1] + color[2]) / 3);
break;
default:
convertToGray = color => (byte)(color[0] * 0.21 + color[1] * 0.72 + color[2] * 0.07);
break;
}
for (var i = 0; i < PaletteColors; i++)
{
var gray = convertToGray(prevPalette[i]);
_palette[i] = new [] { gray, gray, gray };
}
#else
var prevPalette = _palette;
// important: create new array for palette
_palette = new byte[PaletteColors, 3];
Func<byte, byte, byte, byte> convertToGray;
switch (_options)
{
case GrayScaleOptions.Lightness:
convertToGray = (r, g, b) => (byte)(r * 0.21 + g * 0.72 + b * 0.07);
break;
case GrayScaleOptions.Average:
convertToGray = (r, g, b) => (byte)((r + g + b) / 3);
break;
default:
convertToGray = (r, g, b) => (byte)((Math.Max(r, Math.Max(g, b)) + Math.Min(r, Math.Min(g, b))) / 2);
break;
}
for (var i = 0; i < PaletteColors; i++)
{
var r = prevPalette[i, 0];
var g = prevPalette[i, 1];
var b = prevPalette[i, 2];
var gray = convertToGray(r, g, b);
_palette[i, 0] = gray;
_palette[i, 1] = gray;
_palette[i, 2] = gray;
}
#endif
}
19
View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
private void CalculateSpectrogram()
{
const int fftSize = 512;
const int spectrumSize = fftSize / 2;
const int hopSize = fftSize / 4;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// from the huge amount of samples take some first ones (let's say, 400 samples)
var samples = _signal.Samples.Take(400 * spectrumSize).ToArray();
// the central part of the code:
_spectrogram = Transform.Spectrogram(samples, fftSize, hopSize);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var spectraCount = _spectrogram.Count;
var minValue = _spectrogram.SelectMany(s => s).Min();
var maxValue = _spectrogram.SelectMany(s => s).Max();
// post-process spectrogram for better visualization
for (var i = 0; i < spectraCount; i++)
{
// amplify insignificant values and attenuate big outliers a little bit
// (yes, the magic numbers are guests today in our studio )))
_spectrogram[i] = _spectrogram[i].Select(s => (s * 3 < maxValue) ? s * 3 : s / 1.5)
.ToArray();
}
maxValue /= 2;
// ...
_cmap = new ColorMap(_currentColorMap, minValue, maxValue);
}
19
View Source File : Zone.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
private Tuple<Wall[], Roof[], Floor[], Window[], Shading[]>
IdentifyComponents(rg.Brep zone_geometry, rg.BrepFace[] window_geometry, rg.BrepFace[] shading_geometry)
{
var wallIndices = new List<int>();
var roofIndices = new List<int>();
var floorIndices = new List<int>();
var floorHeights = new List<double>();
for (int i = 0; i < zone_geometry.Faces.Count(); i++)
{
rg.BrepFace srf = zone_geometry.Faces[i];
rg.Point3d centroid = rg.AreaMreplacedProperties.Compute(srf).Centroid;
srf.ClosestPoint(centroid, out double u, out double v);
rg.Vector3d normal = srf.NormalAt(u, v); // for some reason, the bottom surface also has postivie normal here?!... using wrong point at line above?
double angle = rg.Vector3d.VectorAngle(normal, new rg.Vector3d(0, 0, 1)) * 180 / Math.PI;
// Floor: flat surface with normal pointing downwards.
// but careful, it could also be an overhanging wall. so floor is that surface with the lowest corner point
// lets say, floor MUST be flat
if (normal.Z == -1.0)
{
floorIndices.Add(i);
floorHeights.Add(centroid.Z);
}
else if (angle < 45.0) // Roof: surface angle < 45?
roofIndices.Add(i);
else // Wall: surface angle >= 45?
wallIndices.Add(i);
}
Wall[] walls = new Wall[wallIndices.Count()];
Roof[] roofs = new Roof[roofIndices.Count()];
Floor[] floors = new Floor[floorIndices.Count()];
double minFloorHeight = floorHeights.Min();
for (int i = 0; i < walls.Length; i++)
{
walls[i] = new Wall(zone_geometry.Faces[wallIndices[i]]);
walls[i].IsExternal = true;
}
for (int i = 0; i < roofs.Length; i++)
{
roofs[i] = new Roof(zone_geometry.Faces[roofIndices[i]]);
roofs[i].IsExternal = true;
}
for (int i = 0; i < floors.Length; i++)
{
floors[i] = new Floor(zone_geometry.Faces[floorIndices[i]]);
// this might only work in single zone models, coz in multi zone, we could have a building on a slope, where several floors are touching the ground
if (Math.Abs(floorHeights[i] - minFloorHeight) > Tolerance)
{
floors[i].IsExternal = true;
}
else
{
floors[i].IsExternal = false;
}
}
var windowList = new List<Window>();
if (window_geometry != null && window_geometry.Length > 0)
{
foreach (var w in walls.Cast<Component>().Concat(roofs).Concat(floors))
{
if (!w.IsExternal) continue;
w.SubComponents = new List<Component>();
foreach (var win in window_geometry)
{
if (CheckWindowOnZone(w.BrepGeometry, win, this.Tolerance)) // how to return error message, if window is not on zone without double running this routine? (in constructor, CheckWindowSSSOnZone())
{
Window window = new Window(win);
windowList.Add(window);
w.SubComponents.Add(window);
}
}
}
}
Shading[] shadings = new Shading[0];
if (shading_geometry != null && shading_geometry.Length > 0)
{
shadings = new Shading[shading_geometry.Length];
for (int i = 0; i < shading_geometry.Length; i++)
{
shadings[i] = new Shading(shading_geometry[i]);
}
}
return new Tuple<Wall[], Roof[], Floor[], Window[], Shading[]>(walls, roofs, floors, windowList.ToArray(), shadings);
}
19
View Source File : GeomUtil.cs
License : MIT License
Project Creator : arcplus
License : MIT License
Project Creator : arcplus
public static PlanarAxis ComputeProjectTo2DArguments(IList<Vec3> positions)
{
var box = OrientedBoundingBox.FromPoints(positions);
var halfAxis = box.HalfAxis;
var xAxis = halfAxis.GetColumn(0);
var scratchXAxis = xAxis;
var yAxis = halfAxis.GetColumn(1);
var scratchYAxis = yAxis;
var zAxis = halfAxis.GetColumn(2);
var scratchZAxis = zAxis;
var xMag = xAxis.GetLength();
var yMag = yAxis.GetLength();
var zMag = zAxis.GetLength();
var min = new[] { xMag, yMag, zMag }.Min();
// If all the points are on a line return undefined because we can't draw a polygon
if ((xMag == 0 && (yMag == 0 || zMag == 0)) || (yMag == 0 && zMag == 0))
{
return null;
}
var planeAxis1 = new Vec3();
var planeAxis2 = new Vec3();
if (min == yMag || min == zMag)
{
planeAxis1 = xAxis;
}
if (min == xMag)
{
planeAxis1 = yAxis;
}
else if (min == zMag)
{
planeAxis2 = yAxis;
}
if (min == xMag || min == yMag)
{
planeAxis2 = zAxis;
}
return new PlanarAxis
{
Center = box.Center,
Axis1 = planeAxis1,
Axis2 = planeAxis2
};
}
19
View Source File : OrientedBoundingBox.cs
License : MIT License
Project Creator : arcplus
License : MIT License
Project Creator : arcplus
public static OrientedBoundingBox FromPoints(IList<Vec3> positions)
{
var result = new OrientedBoundingBox();
var length = positions.Count;
var meanPoint = positions[0];
for(var i = 1; i< length;i++)
{
meanPoint = Vec3.Add(meanPoint, positions[i]);
}
var invLength = 1.0 / length;
meanPoint = meanPoint.MultiplyBy(invLength);
var exx = 0.0;
var exy = 0.0;
var exz = 0.0;
var eyy = 0.0;
var eyz = 0.0;
var ezz = 0.0;
for(var i = 0;i<length;i++)
{
var p = positions[i].Substract(meanPoint);
exx += p.X * p.X;
exy += p.X * p.Y;
exz += p.X * p.Z;
eyy += p.Y * p.Y;
eyz += p.Y * p.Z;
ezz += p.Z * p.Z;
}
exx *= invLength;
exy *= invLength;
exz *= invLength;
eyy *= invLength;
eyz *= invLength;
ezz *= invLength;
var covarianceMatrix = new Matrix3(exx, exy, exz, exy, eyy, eyz, exz, eyz, ezz);
var eigenDecomposition = covarianceMatrix.ComputeEigenDecomposition();
var diagMatrix = eigenDecomposition.Item1;
var unitaryMatrix = eigenDecomposition.Item2;
var rotation = unitaryMatrix.Clone();
var v1 = rotation.GetColumn(0);
var v2 = rotation.GetColumn(1);
var v3 = rotation.GetColumn(2);
var u1 = double.MinValue; //-Number.MAX_VALUE;
var u2 = double.MinValue; //-Number.MAX_VALUE;
var u3 = double.MinValue; //-Number.MAX_VALUE;
var l1 = double.MaxValue; //Number.MAX_VALUE;
var l2 = double.MaxValue; //Number.MAX_VALUE;
var l3 = double.MaxValue; //Number.MAX_VALUE;
for(var i = 0;i <length;i++)
{
var p = positions[i];
u1 = new[] { Vec3.Dot(v1, p), u1 }.Max();
u2 = new[] { Vec3.Dot(v2, p), u2 }.Max();
u3 = new[] { Vec3.Dot(v3, p), u3 }.Max();
l1 = new[] { Vec3.Dot(v1, p), l1 }.Min();
l2 = new[] { Vec3.Dot(v2, p), l2 }.Min();
l3 = new[] { Vec3.Dot(v3, p), l3 }.Min();
}
v1 = v1.MultiplyBy(0.5 * (l1 + u1));
v2 = v2.MultiplyBy(0.5 * (l2 + u2));
v3 = v3.MultiplyBy(0.5 * (l3 + u3));
var center = Vec3.Add(v1, v2);
center = Vec3.Add(center, v3);
var scale = new Vec3(u1 - l1, u2 - l2, u3 - l3);
scale = scale.MultiplyBy(0.5);
rotation = rotation.MultiplyByScale(scale);
return new OrientedBoundingBox
{
Center = center,
HalfAxis = rotation
};
}
19
View Source File : Converter.cs
License : MIT License
Project Creator : arcplus
License : MIT License
Project Creator : arcplus
public static void UpdateMinMax(double[] vs, MinMax minMax)
{
var min = vs.Min();
var max = vs.Max();
if (minMax.Min > min)
{
minMax.Min = min;
}
if (minMax.Max < max)
{
minMax.Max = max;
}
}
19
View Source File : AuthenticationApiClientCachingDecorator.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
private static TimeSpan _expiresIn(AccessTokenResponse r)
{
var expAccessToken = _expiresIn(r.AccessToken);
var expIdToken = TimeSpan.FromSeconds(r.ExpiresIn);
return new[] { expAccessToken, expIdToken }.Min();
}
19
View Source File : MinMaxExtensions.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public static T MinWith<T>(this T first, params T[] args) where T : IComparable<T>
{
if (args?.Length > 0)
{
var argmin = args.Min();
return argmin.CompareTo(first) < 0 ? argmin : first;
}
return first;
}
19
View Source File : Propagate_attribute.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
string attribute = (string)parameterValues["Attribute:"];
string attributeType = (string)parameterValues["Attribute type:"];
int direction = (int)parameterValues["Direction:"];
int propagationMode = (int)parameterValues["Propagation mode:"];
int propagationMode2 = (int)parameterValues["Propagation mode: "];
string defaultValue = (string)parameterValues["Default value:"];
double defaultDouble = double.NaN;
if (attributeType == "Number")
{
if (!double.TryParse(defaultValue, out defaultDouble))
{
defaultDouble = double.NaN;
}
}
double subtractValue = (double)parameterValues["Subtract value:"];
bool overwrite = (bool)parameterValues["Overwrite existing values"];
List<TreeNode> nodes = tree.GetChildrenRecursive();
if (direction == 0)
{
for (int i = nodes.Count - 1; i >= 0; i--)
{
if (nodes[i].Children.Count == 0)
{
if (nodes[i].Attributes.TryGetValue(attribute, out object attributeValue))
{
if (overwrite)
{
if (attributeType == "String" && !(attributeValue is string))
{
nodes[i].Attributes[attribute] = defaultValue;
}
else if (attributeType == "Number" && !(attributeValue is double))
{
nodes[i].Attributes[attribute] = defaultDouble;
}
}
}
else
{
if (attributeType == "String")
{
nodes[i].Attributes[attribute] = defaultValue;
}
else if (attributeType == "Number")
{
nodes[i].Attributes[attribute] = defaultDouble;
}
}
}
else
{
if (overwrite || !nodes[i].Attributes.ContainsKey(attribute))
{
if (attributeType == "String")
{
bool found = false;
bool allEqual = true;
string currVal = null;
for (int j = 0; j < nodes[i].Children.Count; j++)
{
if (nodes[i].Children[j].Attributes.TryGetValue(attribute, out object attributeValue) && attributeValue is string attributeStringValue && !string.IsNullOrEmpty(attributeStringValue))
{
found = true;
if (string.IsNullOrEmpty(currVal))
{
currVal = attributeStringValue;
}
else
{
allEqual = allEqual && (attributeStringValue == currVal);
}
}
}
if (!found || !allEqual)
{
nodes[i].Attributes[attribute] = defaultValue;
}
else
{
nodes[i].Attributes[attribute] = currVal;
}
}
else if (attributeType == "Number")
{
List<double> values = new List<double>();
for (int j = 0; j < nodes[i].Children.Count; j++)
{
if (nodes[i].Children[j].Attributes.TryGetValue(attribute, out object attributeValue) && attributeValue is double attributeDoubleValue)
{
if (!double.IsNaN(attributeDoubleValue))
{
values.Add(attributeDoubleValue);
}
}
else
{
if (!double.IsNaN(defaultDouble))
{
values.Add(defaultDouble);
}
}
}
if (values.Count > 0)
{
switch (propagationMode)
{
case 0:
nodes[i].Attributes[attribute] = values.Average();
break;
case 1:
nodes[i].Attributes[attribute] = values.Min();
break;
case 2:
nodes[i].Attributes[attribute] = values.Max();
break;
}
}
else
{
nodes[i].Attributes[attribute] = defaultDouble;
}
}
}
}
}
}
else if (direction == 1)
{
for (int i = 0; i < nodes.Count; i++)
{
if (nodes[i].Children.Count > 0)
{
if (attributeType == "String")
{
if (nodes[i].Parent == null)
{
if (!nodes[i].Attributes.ContainsKey(attribute))
{
nodes[i].Attributes[attribute] = defaultValue;
}
}
string currValue = defaultValue;
if (nodes[i].Attributes.TryGetValue(attribute, out object nodeAttributeValue) && nodeAttributeValue is string nodeAttributeString && !string.IsNullOrEmpty(nodeAttributeString))
{
currValue = nodeAttributeString;
}
for (int j = 0; j < nodes[i].Children.Count; j++)
{
if (overwrite || !nodes[i].Children[j].Attributes.ContainsKey(attribute))
{
nodes[i].Children[j].Attributes[attribute] = currValue;
}
}
}
else if (attributeType == "Number")
{
if (nodes[i].Parent == null)
{
if (!nodes[i].Attributes.ContainsKey(attribute))
{
nodes[i].Attributes[attribute] = defaultDouble;
}
}
double currValue = defaultDouble;
if (nodes[i].Attributes.TryGetValue(attribute, out object nodeAttributeValue) && nodeAttributeValue is double nodeAttributeDouble && !double.IsNaN(nodeAttributeDouble))
{
currValue = nodeAttributeDouble;
}
for (int j = 0; j < nodes[i].Children.Count; j++)
{
if (overwrite || !nodes[i].Children[j].Attributes.ContainsKey(attribute))
{
if (propagationMode2 == 0)
{
nodes[i].Children[j].Attributes[attribute] = currValue;
}
else if (propagationMode2 == 1)
{
nodes[i].Children[j].Attributes[attribute] = currValue / nodes[i].Children.Count;
}
else if (propagationMode2 == 2)
{
nodes[i].Children[j].Attributes[attribute] = currValue - subtractValue;
}
}
}
}
}
}
}
}
19
View Source File : Plot_age_distributions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static Point[] PlotAction(TreeNode tree, Dictionary<string, object> parameterValues, Dictionary<string, Point> coordinates, Graphics graphics)
{
bool autoColourByNode = (bool)parameterValues["Auto colour by node"];
double opacity = (double)parameterValues["Opacity:"];
ColourFormatterOptions customColour = (ColourFormatterOptions)parameterValues["Colour:"];
Colour defaultFill = customColour.DefaultColour;
Func<object, Colour?> fillFormatter = customColour.Formatter;
double maxHeight = (double)parameterValues["Height:"];
int plotType = (int)parameterValues["Plot type:"];
int showWhere = (int)parameterValues["Show on:"];
bool circular = false;
Point scalePoint;
if (coordinates.TryGetValue("92aac276-3af7-4506-a263-7220e0df5797", out _))
{
scalePoint = coordinates["d0ab64ba-3bcd-443f-9150-48f6e85e97f3"];
circular = true;
}
else if (!coordinates.TryGetValue("68e25ec6-5911-4741-8547-317597e1b792", out scalePoint))
{
throw new Exception("The coordinates module is not supported!");
}
InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];
if (!stateData.Tags.ContainsKey("a1ccf05a-cf3c-4ca4-83be-af56f501c2a6") || !tree.Attributes.ContainsKey("a1ccf05a-cf3c-4ca4-83be-af56f501c2a6"))
{
throw new Exception("The node ages have not been correctly set up!\nPlease use the \"Set up age distributions\" module.");
}
Dictionary<string, List<double>> ageDistributions = (Dictionary<string, List<double>>)stateData.Tags["a1ccf05a-cf3c-4ca4-83be-af56f501c2a6"];
List<TreeNode> nodes = tree.GetChildrenRecursive();
double minX = double.MaxValue;
double maxX = double.MinValue;
double minY = double.MaxValue;
double maxY = double.MinValue;
void updateMaxMin(Point pt)
{
minX = Math.Min(minX, pt.X);
maxX = Math.Max(maxX, pt.X);
minY = Math.Min(minY, pt.Y);
maxY = Math.Max(maxY, pt.Y);
}
static Point sumPoint(Point pt1, Point pt2)
{
return new Point(pt1.X + pt2.X, pt1.Y + pt2.Y);
}
static Point rotatePoint(Point pt, double angle)
{
return new Point(pt.X * Math.Cos(angle) - pt.Y * Math.Sin(angle), pt.X * Math.Sin(angle) + pt.Y * Math.Cos(angle));
}
static Point normalizePoint(Point pt)
{
double modulus = Math.Sqrt(pt.X * pt.X + pt.Y * pt.Y);
return new Point(pt.X / modulus, pt.Y / modulus);
}
static (int[], double[]) histogram(List<double> samples)
{
samples.Sort();
double iqr = BayesStats.Quantile(samples, 0.75) - BayesStats.Quantile(samples, 0.25);
double binWidth = 2 * iqr / Math.Cbrt(samples.Count);
double min = samples.Min();
double max = samples.Max();
int binCount = (int)Math.Ceiling((max - min) / binWidth);
if (binCount < 0 || binCount > 100)
{
binCount = 100;
binWidth = (max - min) / binCount;
}
int[] bins = new int[binCount];
for (int i = 0; i < samples.Count; i++)
{
int bin = (int)Math.Floor((samples[i] - min) / binWidth);
bins[Math.Min(bin, binCount - 1)]++;
}
return (bins, new double[] { min, max, binWidth });
}
static (int[], double[], double[]) histogramWithBinMeans(List<double> samples)
{
samples.Sort();
double iqr = BayesStats.Quantile(samples, 0.75) - BayesStats.Quantile(samples, 0.25);
double binWidth = 2 * iqr / Math.Cbrt(samples.Count);
double min = samples.Min();
double max = samples.Max();
int binCount = (int)Math.Ceiling((max - min) / binWidth);
if (binCount < 0 || binCount > 100)
{
binCount = 100;
binWidth = (max - min) / binCount;
}
int[] bins = new int[binCount];
double[] binValues = new double[binCount];
for (int i = 0; i < samples.Count; i++)
{
int bin = (int)Math.Floor((samples[i] - min) / binWidth);
bins[Math.Min(bin, binCount - 1)]++;
binValues[Math.Min(bin, binCount - 1)] += samples[i];
}
for (int i = 0; i < bins.Length; i++)
{
if (bins[i] > 0)
{
binValues[i] /= bins[i];
}
else
{
binValues[i] = min + binWidth * (i + 0.5);
}
}
return (bins, new double[] { min, max, binWidth }, binValues);
}
Point circularScalePoint = scalePoint;
Point perpScale = normalizePoint(rotatePoint(scalePoint, Math.PI / 2));
if (circular)
{
perpScale = new Point(0, 1);
scalePoint = new Point(circularScalePoint.X, 0);
}
double totalTreeLength = tree.LongestDownstreamLength();
for (int i = 0; i < nodes.Count; i++)
{
if (showWhere == 2 || (showWhere == 1 && nodes[i].Children.Count > 0) || (showWhere == 0 && nodes[i].Children.Count == 0))
{
List<double> distrib = ageDistributions[nodes[i].Id];
if (distrib.Count > 0)
{
Colour colour = defaultFill;
if (autoColourByNode)
{
colour = Modules.DefaultColours[Math.Abs(nodes[i].GetLeafNames().Aggregate((a, b) => a + "," + b).GetHashCode()) % Modules.DefaultColours.Length].WithAlpha(opacity);
}
else if (nodes[i].Attributes.TryGetValue(customColour.AttributeName, out object fillAttributeObject) && fillAttributeObject != null)
{
colour = fillFormatter(fillAttributeObject) ?? defaultFill;
}
if (colour.A > 0)
{
if (!circular)
{
if (plotType == 0)
{
(int[], double[]) hist = histogram(distrib);
int[] bins = hist.Item1;
double[] range = hist.Item2;
double maxBin = bins.Max();
double age = totalTreeLength - nodes[i].UpstreamLength();
double deltaLeft = age - range[1];
double deltaRight = range[0] - age;
Point rightPoint = sumPoint(new Point(-scalePoint.X * deltaRight, -scalePoint.Y * deltaRight), coordinates[nodes[i].Id]);
Point leftPoint = sumPoint(new Point(scalePoint.X * deltaLeft, scalePoint.Y * deltaLeft), coordinates[nodes[i].Id]);
updateMaxMin(leftPoint);
updateMaxMin(rightPoint);
GraphicsPath histPth = new GraphicsPath();
for (int j = 0; j < bins.Length; j++)
{
Point vertDist = new Point(perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point binStart = sumPoint(leftPoint, new Point(scalePoint.X * range[2] * j, scalePoint.Y * range[2] * j));
Point binEnd = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(range[2] * (j + 1), range[1] - range[0]), scalePoint.Y * Math.Min(range[2] * (j + 1), range[1] - range[0])));
histPth.MoveTo(sumPoint(binStart, vertDist)).LineTo(sumPoint(binStart, new Point(-vertDist.X, -vertDist.Y))).LineTo(sumPoint(binEnd, new Point(-vertDist.X, -vertDist.Y))).LineTo(sumPoint(binEnd, vertDist)).Close();
}
graphics.FillPath(histPth, colour, tag: nodes[i].Id);
}
else if (plotType == 1)
{
(int[], double[], double[]) hist = histogramWithBinMeans(distrib);
int[] bins = hist.Item1;
double[] range = hist.Item2;
double[] binMeans = hist.Item3;
double maxBin = bins.Max();
double age = totalTreeLength - nodes[i].UpstreamLength();
double deltaLeft = age - range[1];
double deltaRight = range[0] - age;
Point rightPoint = sumPoint(new Point(-scalePoint.X * deltaRight, -scalePoint.Y * deltaRight), coordinates[nodes[i].Id]);
Point leftPoint = sumPoint(new Point(scalePoint.X * deltaLeft, scalePoint.Y * deltaLeft), coordinates[nodes[i].Id]);
updateMaxMin(leftPoint);
updateMaxMin(rightPoint);
List<Point> pointsUp = new List<Point>();
GraphicsPath histPth = new GraphicsPath();
pointsUp.Add(sumPoint(leftPoint, new Point(perpScale.X / maxBin * maxHeight, perpScale.Y / maxBin * maxHeight)));
for (int j = 0; j < bins.Length; j++)
{
Point vertDist = new Point(perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point horiz = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(binMeans[j] - range[0], range[1] - range[0]), scalePoint.Y * Math.Min(binMeans[j] - range[0], range[1] - range[0])));
pointsUp.Add(sumPoint(horiz, vertDist));
}
histPth.AddSmoothSpline(pointsUp.ToArray());
List<Point> pointsDown = new List<Point>();
for (int j = bins.Length - 1; j >= 0; j--)
{
Point vertDist = new Point(-perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, -perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point horiz = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(binMeans[j] - range[0], range[1] - range[0]), scalePoint.Y * Math.Min(binMeans[j] - range[0], range[1] - range[0])));
pointsDown.Add(sumPoint(horiz, vertDist));
}
pointsDown.Add(sumPoint(leftPoint, new Point(perpScale.X / maxBin * maxHeight, perpScale.Y / maxBin * maxHeight)));
histPth.AddSmoothSpline(pointsDown.ToArray());
histPth.Close();
graphics.FillPath(histPth, colour, tag: nodes[i].Id);
}
}
else
{
if (plotType == 0)
{
(int[], double[]) hist = histogram(distrib);
int[] bins = hist.Item1;
double[] range = hist.Item2;
double maxBin = bins.Max();
double age = totalTreeLength - nodes[i].UpstreamLength();
double deltaLeft = age - range[1];
double deltaRight = range[0] - age;
Point pt = coordinates[nodes[i].Id];
double r = Math.Sqrt(pt.X * pt.X + pt.Y * pt.Y);
double theta = Math.Atan2(pt.Y, pt.X);
double rightR = r - circularScalePoint.X * deltaRight;
double leftR = r + circularScalePoint.X * deltaLeft;
Point leftPoint = new Point(leftR * Math.Cos(theta), leftR * Math.Sin(theta));
Point rightPoint = new Point(rightR * Math.Cos(theta), rightR * Math.Sin(theta));
updateMaxMin(leftPoint);
updateMaxMin(rightPoint);
leftPoint = new Point(leftR - r, 0);
rightPoint = new Point(rightR - r, 0);
graphics.Save();
graphics.Translate(pt);
graphics.Rotate(theta);
GraphicsPath histPth = new GraphicsPath();
for (int j = 0; j < bins.Length; j++)
{
Point vertDist = new Point(perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point binStart = sumPoint(leftPoint, new Point(scalePoint.X * range[2] * j, scalePoint.Y * range[2] * j));
Point binEnd = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(range[2] * (j + 1), range[1] - range[0]), scalePoint.Y * Math.Min(range[2] * (j + 1), range[1] - range[0])));
histPth.MoveTo(sumPoint(binStart, vertDist)).LineTo(sumPoint(binStart, new Point(-vertDist.X, -vertDist.Y))).LineTo(sumPoint(binEnd, new Point(-vertDist.X, -vertDist.Y))).LineTo(sumPoint(binEnd, vertDist)).Close();
}
graphics.FillPath(histPth, colour, tag: nodes[i].Id);
graphics.Restore();
}
else if (plotType == 1)
{
(int[], double[], double[]) hist = histogramWithBinMeans(distrib);
int[] bins = hist.Item1;
double[] range = hist.Item2;
double[] binMeans = hist.Item3;
double maxBin = bins.Max();
double age = totalTreeLength - nodes[i].UpstreamLength();
double deltaLeft = age - range[1];
double deltaRight = range[0] - age;
Point pt = coordinates[nodes[i].Id];
double r = Math.Sqrt(pt.X * pt.X + pt.Y * pt.Y);
double theta = Math.Atan2(pt.Y, pt.X);
double rightR = r - circularScalePoint.X * deltaRight;
double leftR = r + circularScalePoint.X * deltaLeft;
Point leftPoint = new Point(leftR * Math.Cos(theta), leftR * Math.Sin(theta));
Point rightPoint = new Point(rightR * Math.Cos(theta), rightR * Math.Sin(theta));
updateMaxMin(leftPoint);
updateMaxMin(rightPoint);
leftPoint = new Point(leftR - r, 0);
rightPoint = new Point(rightR - r, 0);
graphics.Save();
graphics.Translate(pt);
graphics.Rotate(theta);
List<Point> pointsUp = new List<Point>();
GraphicsPath histPth = new GraphicsPath();
pointsUp.Add(sumPoint(leftPoint, new Point(perpScale.X / maxBin * maxHeight, perpScale.Y / maxBin * maxHeight)));
for (int j = 0; j < bins.Length; j++)
{
Point vertDist = new Point(perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point horiz = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(binMeans[j] - range[0], range[1] - range[0]), scalePoint.Y * Math.Min(binMeans[j] - range[0], range[1] - range[0])));
pointsUp.Add(sumPoint(horiz, vertDist));
}
histPth.AddSmoothSpline(pointsUp.ToArray());
List<Point> pointsDown = new List<Point>();
for (int j = bins.Length - 1; j >= 0; j--)
{
Point vertDist = new Point(-perpScale.X * bins[bins.Length - j - 1] / maxBin * maxHeight, -perpScale.Y * bins[bins.Length - j - 1] / maxBin * maxHeight);
Point horiz = sumPoint(leftPoint, new Point(scalePoint.X * Math.Min(binMeans[j] - range[0], range[1] - range[0]), scalePoint.Y * Math.Min(binMeans[j] - range[0], range[1] - range[0])));
pointsDown.Add(sumPoint(horiz, vertDist));
}
pointsDown.Add(sumPoint(leftPoint, new Point(perpScale.X / maxBin * maxHeight, perpScale.Y / maxBin * maxHeight)));
histPth.AddSmoothSpline(pointsDown.ToArray());
histPth.Close();
graphics.FillPath(histPth, colour, tag: nodes[i].Id);
graphics.Restore();
}
}
}
}
}
}
return new Point[] { new Point(minX, minY), new Point(maxX, maxY) };
}
19
View Source File : BayesStats.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static double[] HighestDensityInterval(IEnumerable<double> samples, double threshold)
{
if (threshold < 0 || threshold > 1)
{
throw new ArgumentOutOfRangeException("The threshold should be between 0 and 1 (inclusive).");
}
else if (threshold == 1)
{
return new double[] { samples.Min(), samples.Max() };
}
List<double> sorted = new List<double>(samples);
sorted.Sort();
int windowSize = (int)Math.Ceiling(threshold * sorted.Count);
if (windowSize < 2)
{
throw new ArgumentException("The threshold is too low or the data does not contain enough samples!");
}
int nCIs = sorted.Count - windowSize;
if (nCIs < 1)
{
throw new ArgumentException("The threshold is too high or the data does not contain enough samples!");
}
double[] ciWidths = new double[nCIs];
double minWidth = double.MaxValue;
List<int> minI = new List<int>();
for (int i = 0; i < nCIs; i++)
{
ciWidths[i] = sorted[i + windowSize] - sorted[i];
if (ciWidths[i] < minWidth)
{
minWidth = ciWidths[i];
minI.Clear();
minI.Add(i);
}
else if (ciWidths[i] == minWidth)
{
minI.Add(i);
}
}
int realMinI = minI[0];
if (minI.Count > 1)
{
bool foundDiff = false;
for (int i = 1; i < minI.Count; i++)
{
if (minI[i] - minI[i - 1] != 1)
{
foundDiff = true;
break;
}
}
if (foundDiff)
{
realMinI = minI.Max();
}
else
{
realMinI = (int)Math.Floor(minI.Average());
}
}
return new double[] { sorted[realMinI], sorted[realMinI + windowSize] };
}
19
View Source File : Extensions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static double MinOrDefault(this IEnumerable<double> array, double defaultValue)
{
return array.Any() ? array.Min() : defaultValue;
}
19
View Source File : TokenKindTests.cs
License : Apache License 2.0
Project Creator : atifaziz
License : Apache License 2.0
Project Creator : atifaziz
[Test]
public void InvalidKind()
{
var kinds = (TokenKind[])Enum.GetValues(typeof(TokenKind));
var min = kinds.Min();
replacedert.Throws<ArgumentOutOfRangeException>(() =>
(min - 1).GetTraits());
var max = kinds.Max();
replacedert.Throws<ArgumentOutOfRangeException>(() =>
(max + 1).GetTraits());
}
19
View Source File : Exemplo8.8.cs
License : MIT License
Project Creator : atrigo
License : MIT License
Project Creator : atrigo
static void Main(string[] args)
{
int[] v = new int[] { 3, 7, 4, 9, 2, 6, 7, 8, 9, 2 };
Console.WriteLine("Soma dos valores: {0}", v.Sum());
Console.WriteLine("Media dos valores: {0}", v.Average());
Console.WriteLine("Valor minimo: {0}", v.Min());
Console.WriteLine("Valor maximo: {0}", v.Max());
if (v.Contains(5))
Console.WriteLine("O vetor contem o numero 5.");
}
19
View Source File : EnumUtil.cs
License : GNU General Public License v3.0
Project Creator : audiamus
License : GNU General Public License v3.0
Project Creator : audiamus
public static string ToDisplayString<TEnum, TPunct> (this TEnum value, ResourceManager rm)
where TEnum: struct, Enum
where TPunct : clreplaced, IChainPunctuation, new()
{
var punct = Singleton<TPunct>.Instance;
string sval = value.ToString ();
//verbatim ?
if (sval.StartsWith ("_")) {
return rm.GetStringEx (sval.Substring (1));
}
string[] parts = sval.Split (USCORE);
bool noSubsreplacedutes = parts.Select (s => s.Length).Min () > 1;
StringBuilder sb = new StringBuilder ();
if (noSubsreplacedutes) {
for (int i = 0; i < parts.Length; i++)
parts[i] = punct.Prefix + rm.GetStringEx (parts[i]) + punct.Suffix;
foreach (string s in parts) {
if (sb.Length > 0)
sb.Append (punct.Infix?[0]);
sb.Append (s);
}
} else {
for (int i = 0; i < parts.Length; i++) {
if (parts[i].Length > 1)
parts[i] = punct.Prefix + rm.GetStringEx (parts[i]) + punct.Suffix;
else {
byte x = Convert.ToByte (parts[i][0]);
try {
parts[i] = punct.Infix?[x - __a];
} catch (IndexOutOfRangeException) {
parts[i] = string.Empty;
}
}
}
foreach (string s in parts)
sb.Append (s);
}
return sb.ToString ();
}
19
View Source File : HsbConverter.cs
License : MIT License
Project Creator : AvaloniaCommunity
License : MIT License
Project Creator : AvaloniaCommunity
public static Hsb ToHsb(this Color color) {
double r = color.R;
double g = color.G;
double b = color.B;
r = r / 255;
g = g / 255;
b = b / 255;
var rgb = new[] {r, g, b};
var max = rgb.Max();
var min = rgb.Min();
var v = max;
var h = max;
var d = max - min;
var s = max.IsCloseTo(0) ? 0 : d / max;
if (max.IsCloseTo(min)) {
h = 0; // achromatic
}
else {
if (max.IsCloseTo(r))
h = (g - b) / d + (g < b ? 6 : 0);
else if (max.IsCloseTo(g))
h = (b - r) / d + 2;
else if (max.IsCloseTo(b)) h = (r - g) / d + 4;
h *= 60;
}
return new Hsb(h, s, v);
}
19
View Source File : CosmosLinqExtensions.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public static Task<Response<TSource>> MinAsync<TSource>(
this IQueryable<TSource> source,
CancellationToken cancellationToken = default)
{
if (!(source.Provider is CosmosLinqQueryProvider cosmosLinqQueryProvider))
{
return ResponseHelperAsync(source.Min());
}
return cosmosLinqQueryProvider.ExecuteAggregateAsync<TSource>(
Expression.Call(
GetMethodInfoOf<IQueryable<TSource>, TSource>(Queryable.Min),
source.Expression),
cancellationToken);
}
See More Examples