private static void ProcessOrders(AlgorithmResult result, ICollection <Model.Order> orders) { if (orders.Count == 0) { return; } if (result.Orders == null) { result.Orders = new Orders(); } result.Orders.Updated(); foreach (var order in orders) { try { var newOrder = new Algorithms.Results.Order { DateTime = order.Time, Id = order.Id, Quantity = order.Quantity, OrderType = (Algorithms.Results.OrderType)order.Type, Status = (Algorithms.Results.OrderStatus)order.Status, Symbol = order.Symbol?.Value }; result.Orders.Items.Add(newOrder); } catch (Exception) { } } }
private static AlgorithmResult GetCollisions(IEnumerable <string> strings, string algorithmName, Func <string, ulong> algorithm) { var result = new AlgorithmResult(); var dictionary = new Dictionary <ulong, List <string> >(); var collisions = new Dictionary <ulong, List <string> >(); var sw = Stopwatch.StartNew(); foreach (var text in strings) { var hash = algorithm(text); if (!dictionary.TryGetValue(hash, out var bucket)) { bucket = new List <string>(); dictionary[hash] = bucket; bucket.Add(text); } else { if (!bucket.Contains(text)) { collisions[hash] = bucket; bucket.Add(text); } } } result.Name = algorithmName; result.Collisions = collisions; result.ElapsedTime = sw.Elapsed; return(result); }
private static void Main() { #region Initialize var random = new Random(); var chromosomes = new List <Chromosome>(); for (var i = 0; i < ChromosomesNumber; i++) { var chromosome = new Chromosome(); for (var d = 0; d < Dimensions; d++) { chromosome.X.Add(random.Next(30)); // chromosome.X.Add(-100 + 200 * random.NextDouble()); } chromosomes.Add(chromosome); } #endregion #region Functions var fitnessFunction = new Func <Chromosome, double>(c => { // return Math.Abs(c.X[0] + 2 * c.X[1] + 3 * c.X[2] + 4 * c.X[3] - 30); return(c.X.Sum(x => x * x)); }); var mutationFunction = new Func <Chromosome, Chromosome>(c => { int value = random.Next(5) * (random.Next(2) - 2); c.X[random.Next(c.X.Count)] += value; // c.X[random.Next(c.X.Count)] = random.Next(); return(c); }); var crossOverFunction = new Func <Chromosome, Chromosome, Chromosome>((father, mother) => { var child = new Chromosome(); int crossOverPoint = random.Next(father.X.Count); for (var i = 0; i < crossOverPoint; i++) { child.X.Add(father.X[i]); } for (int i = crossOverPoint; i < father.X.Count; i++) { child.X.Add(mother.X[i]); } return(child); }); #endregion var algorithm = new Algorithm <Chromosome>(random); AlgorithmResult <Chromosome> result = algorithm.Run(chromosomes, fitnessFunction, crossOverFunction, mutationFunction, RunOptions.Interactive); Console.WriteLine(result.Result); Console.WriteLine(fitnessFunction(result.Result)); }
private static Bitmap SimpleProcessing(Bitmap image, IAlgorithm algorithm) { algorithm.Input = new AlgorithmInput(image); AlgorithmResult result = algorithm.ProcessData(); return(result.Image.ToManagedImage()); }
public AlgorithmResult DetectDisparity( string filenameL, string filenameR, int numberOfDisparities, int blockSize) { AlgorithmResult result = new AlgorithmResult(); Image <Bgr, byte> imageLeft = ImageHelper.GetImage(filenameL); Image <Bgr, byte> imageRight = ImageHelper.GetImage(filenameR); var resultImage = new Image <Bgr, byte>(imageLeft.Width, imageLeft.Height); // Create new (gray, float) image for disparity var imageDisparity = new Image <Gray, float>(imageLeft.Size); StereoBM stereoBM = new StereoBM(numberOfDisparities, blockSize); StereoMatcherExtensions.Compute( stereoBM, imageLeft.Convert <Gray, byte>(), imageRight.Convert <Gray, byte>(), imageDisparity); // Normalize CvInvoke.Normalize(imageDisparity, imageDisparity, 0, 255, NormType.MinMax, DepthType.Cv8U); // Set resultImage after normalizing resultImage = imageDisparity.Convert <Bgr, byte>(); result.ImageArray = ImageHelper.SetImage(resultImage); return(result); }
public void ShouldAttendTheServiceFlow() { var sentences = new[] { new Sentence(null, 1, "1") }; var algorithmResult = new AlgorithmResult(sentences); var serializationResult = Guid.NewGuid().ToString(); _mockAlgorithm .Setup(m => m.Analyse(It.IsAny <StreamReader>())) .Returns(algorithmResult) .Verifiable(); _mockSerializer .Setup(m => m.Serialize(It.IsAny <Analyse>())) .Callback(new Action <Analyse>(a => Validations.SentenceValidator.AssertAreEquivalents(sentences, a.Sentences, true))) .Returns(serializationResult) .Verifiable(); _mockRepository .Setup(m => m.SaveAnalyse(It.IsAny <Analyse>())) .Callback(new Action <Analyse>(a => Validations.SentenceValidator.AssertAreEquivalents(sentences, a.Sentences, true))) .Returns(1) .Verifiable(); var tempFile = Path.GetTempFileName(); var result = _testingObject.Analyse(new AnalyseCommand(tempFile)); Assert.AreEqual(serializationResult, result.Result); _mockRepository.VerifyAll(); _mockSerializer.VerifyAll(); _mockAlgorithm.VerifyAll(); }
public void ProcessLiveResult(AlgorithmResult result, LiveAlgorithmResultsResponse response) { response.EnsureSuccess(); if (response.LiveResults.Resolution != Resolution.Second) { // TODO: Confirm whether resolution is always second. // I tried multiple live algorithms, subscribing to minute and daily data. Resolution // always appears to be in seconds. throw new Exception($"Unexpected resolution: {response.LiveResults.Resolution}"); } var serverStatistics = response.LiveResults?.Results?.ServerStatistics; if (serverStatistics != null) { ProcessServerStatistics(result, serverStatistics); } var orders = response.LiveResults?.Results?.Orders; if (orders != null) { ProcessOrders(result, orders); } var charts = response.LiveResults?.Results?.Charts; if (charts != null) { ProcessCharts(result, charts); } }
private void ProcessCharts(AlgorithmResult result, IDictionary <string, Model.Chart> charts) { if (!charts.TryGetValue("Strategy Equity", out var sourceChart)) { return; } if (!sourceChart.Series.TryGetValue("Equity", out var sourceSeries)) { return; } var convertedSeries = sourceSeries.Values.Select(v => new Algorithms.Results.ChartPoint { X = Instant.FromUnixTimeSeconds(v.X), Y = v.Y }); if (result.EquityChart == null) { result.EquityChart = new List <ChartPoint>(); } result.EquityChart.Clear(); result.EquityChart.AddRange(convertedSeries); }
public async Task Run() { const string authUserToken = ""; const string authAccessToken = ""; const string endpointAddress = "https://www.quantconnect.com/api/v2"; //const int projectId = 2416667; const int projectId = 530955; //const string deployId = "L-82bee18752ab30d0c0705bf1962e6e9d"; const string deployId = "L-c69ee5e5557ddc525532d9fd9dd4b2f7"; _api = Create(authUserToken, authAccessToken, endpointAddress); var liveAlgorithmResponse = await _api.GetLiveAlgorithmListAsync(AlgorithmStatus.Running); var liveAlgorithmResultsResponse = await _api.GetLiveAlgorithmResultsAsync(projectId, deployId); //var logsResponse = await _api.GetLiveAlgorithmLogs(projectId, deployId); //var projectsResponse = await _api.GetProjectsAsync(); //var projectResponse = await _api.GetProjectAsync(projectId).ConfigureAwait(false); var result = new AlgorithmResult(); var parser = new ApiResultParser(); parser.ProcessLiveResult(result, liveAlgorithmResultsResponse); var firstItem = result.EquityChart.First().X; var lastItem = result.EquityChart.Last().X; }
public void TestGetBestAlgorPrice() { string json = System.IO.File.ReadAllText("miner.json"); MinerModel miners = JsonConvert.DeserializeObject <MinerModel>(json); List <AlgorithmResult> algors = new List <AlgorithmResult>(); List <KeyValuePair <string, string> > paths = new List <KeyValuePair <string, string> >(); AlgorithmResult algorX17 = new AlgorithmResult(); algorX17.name = "x17"; algorX17.Pool = PoolName.Zpool; algorX17.estimate_current = 600; algorX17.estimate_last24h = 700; algors.Add(algorX17); AlgorithmResult algorSkein = new AlgorithmResult(); algorSkein.name = "skein"; algorSkein.Pool = PoolName.Zpool; algorSkein.estimate_current = 500; algorSkein.estimate_last24h = 400; algors.Add(algorSkein); paths.Add(new KeyValuePair <string, string>("x17@zpool", "c:\\miner\\start-t-rex.bat")); miners.Path = paths; string algorAtPool; double price; (algorAtPool, price) = MinerControl.FindBestPrice(algors, true, miners); Assert.AreEqual(0, String.Compare("x17@zpool", algorAtPool, true)); }
public TaskResultsDialog() { InitializeComponent(); Owner = App.Window; Icon = AppResources.GetAppIcon; InitConfigProperty(); InitResultTableProperty(); InitReportMethods(); var entityList = new GenericEntityListControl <AlgorithmResult>( "Результаты", AlgorithmResult.PropertyMatcher(), DisplayProperties); ListPanel.Children.Add(entityList.GetUiElement()); entityList.SetSource(App.DataBase.GetCollection <AlgorithmResult>().FindAll()); ComponentUtils.InsertIconToButton(RemoveButton, AppResources.GetRemoveItemIcon, "Удалить результат из списка"); RemoveButton.Click += (sender, args) => { if (entityList.Selected == null) { return; } foreach (var result in entityList.SelectedAll()) { App.DataBase.GetCollection <AlgorithmResult>().Delete(result.Id); } entityList.SetSource(App.DataBase.GetCollection <AlgorithmResult>().FindAll()); VisibilityPanel.Visibility = Visibility.Collapsed; }; }
public AlgorithmResult Aggregate(IEnumerable <AlgorithmResult> results) { var res = results.OrderBy(a => a.Similarity).ToArray(); var agg = res[res.Length / 2]; return(AlgorithmResult.Res(Constants.AggregatorId, agg.Similarity, agg.AlgorithmVerdict)); }
private static void ProcessServerStatistics(AlgorithmResult result, IDictionary <string, string> serverStatistics) { // TODO: Implement this as soon as QuantConnect provides this data over the API result.ServerStatistics = new ServerStatistics { DateUpdated = DateTime.UtcNow }; if (serverStatistics.TryGetValue("CpuUsage", out string statistic)) { // TODO: Parse the statistic result.ServerStatistics.CpuUsage = 50; } if (serverStatistics.TryGetValue("Uptime", out statistic)) { // TODO: Parse the statistic result.ServerStatistics.Uptime = new TimeSpan(); } if (serverStatistics.TryGetValue("MemoryUsed", out statistic)) { // TODO: Parse the statistic result.ServerStatistics.MemoryUsed = 128; } if (serverStatistics.TryGetValue("MemoryTotal", out statistic)) { // TODO: Parse the statistic result.ServerStatistics.MemoryTotal = 512; } }
public static void AssertAreEquivalents(AlgorithmResult expected, AlgorithmResult result, bool validateText) { if (expected == null && result == null) { return; } SentenceValidator.AssertAreEquivalents(expected.Sentences, result.Sentences, validateText); }
public override (byte R, byte G, byte B) Color(AlgorithmResult result) { double abs = result.z.Magnitude; double hue = 180d * (result.z.Phase + Math.PI) / Math.PI;//(360/2) * ..., don't worry, overflow is allowed int iterationsSquared = result.iterations * result.iterations; double saturation = 700d / (800d + Math.Log(result.iterations)) * (1 - eps10 / (eps10 + abs * abs)); double value = 10d / (10d + result.iterations); return(ColorFromHSV(hue, saturation, value)); }
public void MatrixReport(AlgorithmResult res) { var fileName = EnterFileName("matrix-report", "Csv file (*.csv)|*.csv"); if (fileName == null) { return; } File.WriteAllText(fileName, ReportUtils.MatrixReport(res)); ComponentUtils.ShowMessage("Результат в файл успешно записан", MessageBoxImage.Information); }
public AlgorithmResult DetectContours( string filename, ContourRetrType rtype, ContourMethodType mtype, double threshold1, double threshold2, int apertureSize) { AlgorithmResult result = new AlgorithmResult(); Image <Bgr, byte> image = ImageHelper.GetImage(filename); var cannyImage = new Image <Gray, byte>(image.Width, image.Height); var resultImage = new Image <Bgr, byte>(filename); var contours = new VectorOfVectorOfPoint(); // Apply canny algorithm CvInvoke.Canny( image.Convert <Gray, byte>(), cannyImage, threshold1, threshold2, apertureSize); // Find the contours CvInvoke.FindContours( cannyImage, contours, null, GetRetrType(rtype), GetMethodType(mtype)); resultImage = cannyImage.Convert <Bgr, byte>(); // Draw the contours resultImage.DrawPolyline( contours.ToArrayOfArray(), false, new Bgr(Color.FromArgb(255, 77, 77)), 3); // Return collection of contours result.ImageArray = ImageHelper.SetImage(resultImage); result.ContourDatas = new List <ContourPointModel>(); result.ContourDatas = contours.ToArrayOfArray().Select(c => new ContourPointModel() { Count = c.Select(p => new PointF(p.X, p.Y)).ToArray().Length, StartX = c.Length > 0 ? c[0].X : float.NaN, StartY = c.Length > 0 ? c[0].Y : float.NaN, EndX = c.Length > 0 ? c[c.Length - 1].X : float.NaN, EndY = c.Length > 0 ? c[c.Length - 1].Y : float.NaN, Length = GetLength(c.Select(p => new PointF(p.X, p.Y)).ToArray()) }).ToList(); return(result); }
public void FullReport(AlgorithmResult res) { var fileName = EnterFileName("full-report", "Txt file (*.txt)|*.txt"); if (fileName == null) { return; } File.WriteAllText(fileName, ReportUtils.FullReport(res)); ComponentUtils.ShowMessage("Результат в файл успешно записан", MessageBoxImage.Information); }
private double GetSystemScore(AlgorithmInput input, AlgorithmResult result) { var inputStatistics = Statistics.FromUnmanagedImage(input.Image); var outputStatistics = Statistics.FromUnmanagedImage(result.Image); double inputScore = inputStatistics.GetContrastMeasure(); double resultScore = outputStatistics.GetContrastMeasure(); double finalScore = resultScore / inputScore; return(finalScore); }
public static string JsonReport(AlgorithmResult res) { var options = new JsonSerializerOptions { WriteIndented = true, IgnoreNullValues = true }; options.Converters.Add(new AlgorithmTypeOffsetConverter()); options.Converters.Add(new MethodTypeOffsetConverter()); var jsonString = JsonSerializer.Serialize(res, options); return(jsonString); }
public IAlgorithmResult Calculate(decimal balance) { IAlgorithmResult result = new AlgorithmResult(); // ----- // NOTE: Obviously, in the real world, this example wouldn't warrant an Strategy. This is for "semantic" demostration ONLY !!! // ----- result.Result = (balance < 0.0m); result.Amount = balance; return(result); }
/// <summary> /// Updates the algorithm. /// </summary> /// <remarks> /// Is *always* invoked from the UI thread. /// This method should not block for longer than a few milliseconds or otherwise the UI might become stuck. /// </remarks> /// <param name="elapsed"></param> public void Update(TimeSpan elapsed) { if (elapsed > TimeSpan.Zero) { double dt = Math.Min(0.06, elapsed.TotalSeconds); Repulse(); Attract(); UpdatePositions(dt); _result = AlgorithmResult.Create(_bodiesByNode.Select(CreateResult)); } }
public void Returns_AlgorithmResult() { // Arrange var expected = new AlgorithmResult <int>(0); // Act var sut = new TestInt32Algorithm(1, 1); var actual = sut.Execute(new Die[] { new Die() }); // Assert Assert.Equal(actual.Value, expected.Value); Assert.Equal(actual.HasError, expected.HasError); Assert.Equal(actual.ErrorMessage, expected.ErrorMessage); }
private static void ExploreMiningDetail(string algorithmName, PoolName pool) { double btcCurrentPerDay = _calc.GetTotalFiatMoneyMiningPerday(algorithmName, pool, true, _fiat); double btc24HoursPerDay = _calc.GetTotalFiatMoneyMiningPerday(algorithmName, pool, false, _fiat); if (btc24HoursPerDay > _keepMoreThan || btcCurrentPerDay > _keepMoreThan) { AlgorithmResult algorAtBlockMaster = new AlgorithmResult(); algorAtBlockMaster.name = algorithmName; algorAtBlockMaster.Pool = pool; algorAtBlockMaster.estimate_current = btcCurrentPerDay; algorAtBlockMaster.estimate_last24h = btc24HoursPerDay; _algorsResult.Add(algorAtBlockMaster); } }
public void TestDoMining() { List <AlgorithmResult> algors = new List <AlgorithmResult>(); List <KeyValuePair <string, string> > paths = new List <KeyValuePair <string, string> >(); string json = System.IO.File.ReadAllText("miner.json"); MinerModel miners = JsonConvert.DeserializeObject <MinerModel>(json); AlgorithmResult algorX17 = new AlgorithmResult(); algorX17.name = "x17"; algorX17.Pool = PoolName.Zpool; algorX17.estimate_current = 600; algorX17.estimate_last24h = 700; algors.Add(algorX17); AlgorithmResult algorSkein = new AlgorithmResult(); algorSkein.name = "skein"; algorSkein.Pool = PoolName.Zpool; algorSkein.estimate_current = 500; algorSkein.estimate_last24h = 400; algors.Add(algorSkein); paths.Add(new KeyValuePair <string, string>("x17@zpool", "C:\\SoftwareMiner\\CryptoDredge_0.9.3\\start-BCD-bcd-zpool.bat")); miners.Path = paths; string bestAlgorAtPool; double bestPrice; (bestAlgorAtPool, bestPrice) = MinerControl.FindBestPrice(algors, true, miners); MinerControl.DoMining(bestAlgorAtPool, miners.Path); System.Threading.Thread.Sleep(12000); AlgorithmResult algorNewGreater = new AlgorithmResult(); algorNewGreater.name = "skein"; algorNewGreater.Pool = PoolName.Zpool; algorNewGreater.estimate_current = 1000; algorNewGreater.estimate_last24h = 1000; algors.Add(algorNewGreater); (bestAlgorAtPool, bestPrice) = MinerControl.FindBestPrice(algors, true, miners); MinerControl.DoMining(bestAlgorAtPool, miners.Path); Assert.AreEqual(true, miners.SwapTime > 0); }
public AlgorithmResult Analyse(StreamReader textReader) { var c = default(char); var next = default(char); var aux = default(char); while ((_countRead = textReader.ReadBlock(buffer, 0, BufferSize)) > 0) { if (aux != default(char)) { ProcessCharacter(aux, buffer[0], false); } for (int i = 0; i < _countRead; i++) { c = buffer[i]; if (i + 1 < _countRead) { next = buffer[i + 1]; } else if (!textReader.EndOfStream) { // // It's necessary to know the next charater to handle correcty decimal numbers // To garantee, the knologement of the next character, when the cursor in at i - 1 from the end of the buffer // we copy c to aux and refill the buffer. Consequently, the next char will go to buffer[0] // aux = c; break; } var lastCharacter = i == _countRead - 1 && textReader.EndOfStream; ProcessCharacter(c, next, lastCharacter); } } var sentences = _sentenceBuilders.Values.Select(s => s.Build()).ToArray(); var result = new AlgorithmResult(sentences); ResetCounters(); return(result); }
public static string MinimalReport(AlgorithmResult res) { var sb = new StringBuilder("Минимальный отчет результата работы алгоритма"); sb.AppendLine(); sb.AppendLine($"Дата выполнения: {res.RunDate}"); sb.AppendLine($"Использованный алгоритм: {res.AlgorithmConfig.AlgorithmType.GetDescription()}"); sb.AppendLine("В каждой строчке названию города сопоставляется значение транспортной доступности"); foreach (var node in res.Nodes) { sb.Append(node.Name) .Append(" ") .Append(WeightValueWithExtension(node, res.AlgorithmConfig.AlgorithmType)) .AppendLine(); } return(sb.ToString()); }
public override (byte R, byte G, byte B) Color(AlgorithmResult result) { double abs = result.z.Magnitude; double iter = Math.Pow(result.iterations, 1.4); var t = 1 - (.5 * eps10 / (eps10 + abs * abs)); var tmp = ( (byte)(255d * 10d / (10d + iter) * t + 255 * (1 - t)), (byte)(255d * 70d / (70d + iter) * t + 255 * (1 - t)), (byte)(255d * 300d / (300d + iter) * t + 255 * (1 - t)) ); //if (result.iterations >= 15) //{ // tmp = ((byte)(tmp.R / (result.iterations - 15)), (byte)(tmp.G / (result.iterations - 15)), (byte)(tmp.B / (result.iterations - 15))); //} return(tmp); }
public AlgorithmAggregatedResult Check(Source source1, Source source2) { var answer = new List <AlgorithmResult>(); foreach (var algo in Algos) { var baseAlgo = (algo as BaseAlgorithm); var cmpRes = algo.CompareSrc(source1, source2); var res = AlgorithmResult.Res(baseAlgo.Id, cmpRes.Key, cmpRes.Value); answer.Add(res); } var result = new AlgorithmAggregatedResult(); result.AlgoResults = answer.ToArray(); result.AggregationInfo = Aggregator.Aggregate(answer); return(result); }
public static string MatrixReport(AlgorithmResult res) { var sb = new StringBuilder("Название"); sb.Append(",Индекс"); for (var i = 0; i < res.Nodes.Count; i++) { sb.Append($",{i}"); } sb.AppendLine(); for (var i = 0; i < res.Nodes.Count; i++) { var fromNode = res.Nodes[i]; sb.Append($"\"{fromNode.Name}\""); sb.Append($",{i}"); for (var j = 0; j < res.Nodes.Count; j++) { var toNode = res.Nodes[j]; if (i == j) { sb.Append(",-1"); continue; } var found = fromNode.Weights.FirstOrDefault(w => toNode.Equals(w.From)); if (found == null) { sb.Append(",-1"); continue; } sb.Append($",{found.Weight.Value:F}"); } sb.AppendLine(); } return(sb.ToString()); }
public static AlgorithmResult CalcMealCarbsDeviation(Meal meal, UserBaseInsulinCalcProfile insulinProfile) { AlgorithmResult result = new AlgorithmResult() { Status = "Unsuccess"}; if (IfValidParameters(meal, insulinProfile)) { log.InfoFormat("[CalcMealCarbsDeviation] meal.Id={0}, meal.PreMealSugarLevel={1}, meal.PostMealSugarLevel={2}.", meal.Id.ToString(), meal.PreMealSugarLevel, meal.PostMealSugarLevel); double unitReductionValue = (insulinProfile.UnitReductionUnits == UnitReductionUnits.mmolL) ? UnitsConverter.MmolLToMgDl(insulinProfile.UnitReductionValue) : insulinProfile.UnitReductionValue; double insulinDosage = BaseInsulineFormulas.CalculatingInsulinDose(insulinProfile.MaxSugarRange, meal.PreMealSugarLevel, insulinProfile.UnitReductionUnits, unitReductionValue, insulinProfile.InsulinCarbohydrateRatio, insulinProfile.DosageUnits, meal.CarbAmount); double calculatedCarbsAmount = BaseInsulineFormulas.CalculateMealCarbs(insulinProfile.MaxSugarRange, meal.PostMealSugarLevel, insulinProfile.UnitReductionUnits, unitReductionValue, insulinProfile.InsulinCarbohydrateRatio, insulinProfile.DosageUnits, insulinDosage); result.Status = "Success"; result.Result = Math.Round(calculatedCarbsAmount - meal.CarbAmount, 2); } else { log.ErrorFormat("[CalcMealCarbsDeviation] Error: Some input parameters was invalid."); } return result; }