├── .gitignore ├── Jtc.Optimization.Api ├── .config │ └── dotnet-tools.json ├── Controllers │ ├── CompilerController.cs │ ├── DataController.cs │ └── MscorlibController.cs ├── Jtc.Optimization.Api.csproj ├── MscorlibProvider.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Resource.Designer.cs ├── Resource.resx ├── Resources │ └── mscorlib.dll ├── Startup.cs ├── appsettings.Development.json ├── appsettings.json └── nlog.config ├── Jtc.Optimization.BlazorClient.Objects ├── BlazorClientConfiguration.cs ├── IBlazorClientConfiguration.cs ├── Jtc.Optimization.BlazorClient.Objects.csproj └── PlotlyData.cs ├── Jtc.Optimization.BlazorClient ├── App.razor ├── Attributes │ ├── ExportedWebAssemblyJSRuntime.cs │ ├── GreaterThanAttribute.cs │ ├── JavascriptFunctionValidatorAttribute.cs │ └── RequiredIfAttribute.cs ├── BlazorClientState.cs ├── GlobalSuppressions.cs ├── Jtc.Optimization.BlazorClient.csproj ├── Jtc.Optimization.BlazorClient.runtimeconfig.json ├── Models │ ├── FitnessConfiguration.cs │ ├── GeneConfiguration.cs │ ├── MinimizeFunctionCode.cs │ └── OptimizerConfiguration.cs ├── Pages │ ├── Chart.razor │ ├── ChartBase.cs │ ├── ChartWorker.cs │ ├── CodeEditor.razor │ ├── CodeEditorBase.cs │ ├── Config.razor │ ├── ConfigBase.cs │ ├── Default.razor │ ├── Info.razor │ └── Quickstart.razor ├── Program.cs ├── Properties │ └── launchSettings.json ├── Resource.Designer.cs ├── Resource.resx ├── Shared │ ├── GeneConfig.razor │ ├── GeneConfigBase.cs │ ├── MainLayout.razor │ ├── Sidebar.razor │ ├── SidebarBase.cs │ ├── SidebarShow.razor │ ├── Wait.razor │ └── WaitBase.cs ├── _Imports.razor ├── libman.json └── wwwroot │ ├── ChartWorkerMessaging.js │ ├── ClientStorage.js │ ├── MainInterop.js │ ├── PlotlyInterop.js │ ├── SideBar.js │ ├── WorkerInterop.js │ ├── WorkerPoolInterop.js │ ├── appSettings.json │ ├── css │ └── site.css │ ├── donate-bitcoin │ ├── index.html │ ├── index.js │ ├── js │ │ ├── jquery.js │ │ └── jquery.qrcode.min.js │ └── stylesheets │ │ ├── normalize.css │ │ └── stylesheet.css │ ├── favicon.ico │ ├── images │ ├── Hamburger_icon.svg │ └── run2.gif │ ├── index.html │ ├── lib │ ├── crosstalk-1.0.0 │ │ ├── css │ │ │ └── crosstalk.css │ │ └── js │ │ │ ├── crosstalk.js │ │ │ ├── crosstalk.js.map │ │ │ ├── crosstalk.min.js │ │ │ └── crosstalk.min.js.map │ ├── htmlwidgets-1.3 │ │ └── htmlwidgets.js │ ├── jquery │ │ ├── jquery.min.js │ │ └── jquery.min.map │ ├── plotly-binding-4.8.0 │ │ └── plotly.js │ ├── plotly-htmlwidgets-css-1.39.2 │ │ └── plotly-htmlwidgets.css │ ├── plotly.js │ │ └── plotly.min.js │ ├── typedarray-0.1 │ │ └── typedarray.min.js │ └── workerpool │ │ └── dist │ │ ├── worker.js │ │ ├── worker.min.js │ │ ├── workerpool.js │ │ ├── workerpool.map │ │ └── workerpool.min.js │ ├── robots.txt │ ├── sitemap.xml │ └── worker.js ├── Jtc.Optimization.ChartJs ├── ChartJS │ ├── BarChart │ │ ├── BarAxis.cs │ │ ├── BarConfig.cs │ │ ├── BarData.cs │ │ ├── BarOptions.cs │ │ ├── BarOptionsScales.cs │ │ └── Dataset │ │ │ ├── BarDataset.cs │ │ │ ├── BaseBarDataset.cs │ │ │ └── IndividualBarDataset.cs │ ├── BubbleChart │ │ ├── BubbleConfig.cs │ │ ├── BubbleData.cs │ │ ├── BubbleDataPoint.cs │ │ ├── BubbleDataset.cs │ │ └── BubbleOptions.cs │ ├── ChartJsInterop.cs │ ├── Common │ │ ├── Axis.cs │ │ ├── BaseConfigOptions.cs │ │ ├── ConfigBase.cs │ │ ├── Enums │ │ │ ├── AxisDisplay.cs │ │ │ ├── AxisType.cs │ │ │ ├── BorderAlign.cs │ │ │ ├── BorderCapStyle.cs │ │ │ ├── BorderJoinStyle.cs │ │ │ ├── ChartType.cs │ │ │ ├── CubicInterpolationMode.cs │ │ │ ├── FontStyle.cs │ │ │ ├── InteractionMode.cs │ │ │ ├── JsonConverter │ │ │ │ ├── JsonObjectEnumConverter.cs │ │ │ │ └── JsonStringEnumConverter.cs │ │ │ ├── ObjectEnum.cs │ │ │ ├── PointStyle.cs │ │ │ ├── Position.cs │ │ │ ├── ScaleBound.cs │ │ │ ├── SteppedLine.cs │ │ │ ├── StringEnum.cs │ │ │ ├── TickSource.cs │ │ │ ├── TimeDistribution.cs │ │ │ ├── TimeMeasurement.cs │ │ │ └── TooltipPosition.cs │ │ ├── GridLines.cs │ │ ├── IndexableOption.cs │ │ ├── IndexableOptionConverter.cs │ │ ├── JsonWriteOnlyConverter.cs │ │ ├── Legends │ │ │ ├── Labels.cs │ │ │ ├── Legend.cs │ │ │ ├── OnClickHandler │ │ │ │ ├── DotNetInstanceClickHandler.cs │ │ │ │ ├── DotNetStaticClickHandler.cs │ │ │ │ ├── ILegendClickHandler.cs │ │ │ │ └── JsClickHandler.cs │ │ │ └── OnHover │ │ │ │ ├── DotNetInstanceHoverHandler.cs │ │ │ │ ├── DotNetStaticHoverHandler.cs │ │ │ │ ├── ILegendOnHoverHandler.cs │ │ │ │ └── JsHoverHandler.cs │ │ ├── MajorTicks.cs │ │ ├── MinorTicks.cs │ │ ├── Point.cs │ │ ├── Properties │ │ │ ├── Animation.cs │ │ │ ├── ArcAnimation.cs │ │ │ ├── OptionsTitle.cs │ │ │ └── Tooltips.cs │ │ ├── SubTicks.cs │ │ ├── Ticks.cs │ │ ├── Utils │ │ │ ├── ArgValidation.cs │ │ │ └── PointUtil.cs │ │ └── Wrappers │ │ │ ├── ByteWrapper.cs │ │ │ ├── DoubleWrapper.cs │ │ │ ├── FloatWrapper.cs │ │ │ ├── Int16Wrapper.cs │ │ │ ├── Int32Wrapper.cs │ │ │ ├── Int64Wrapper.cs │ │ │ ├── JsonValueWrapperConverter.cs │ │ │ ├── ValueWrapper.cs │ │ │ └── WrapperExtensions.cs │ ├── LineChart │ │ ├── Axes │ │ │ ├── CartesianAxis.cs │ │ │ ├── CategoryAxis.cs │ │ │ ├── LinearCartesianAxis.cs │ │ │ ├── LogarithmicAxis.cs │ │ │ ├── Ticks │ │ │ │ ├── CartesianTicks.cs │ │ │ │ ├── CategoryTicks.cs │ │ │ │ ├── LinearCartesianTicks.cs │ │ │ │ ├── LogarithmicTicks.cs │ │ │ │ └── TimeTicks.cs │ │ │ └── TimeAxis.cs │ │ ├── JsonMomentConverter.cs │ │ ├── LineConfig.cs │ │ ├── LineData.cs │ │ ├── LineDataset.cs │ │ ├── LineOptions.cs │ │ ├── LineOptionsHover.cs │ │ ├── Moment.cs │ │ ├── ScaleLabel.cs │ │ ├── Scales.cs │ │ ├── TimeDisplayFormats.cs │ │ ├── TimeOptions.cs │ │ └── TimeTuple.cs │ ├── MixedChart │ │ ├── BaseMixableDataset.cs │ │ ├── IMixableDataset.cs │ │ ├── MixedConfig.cs │ │ ├── MixedData.cs │ │ └── MixedOptions.cs │ ├── MomentJsInterop.cs │ ├── PieChart │ │ ├── PieConfig.cs │ │ ├── PieData.cs │ │ ├── PieDataset.cs │ │ └── PieOptions.cs │ ├── PolarAreaChart │ │ ├── Axis │ │ │ ├── AngleLines.cs │ │ │ ├── LinearRadialAxis.cs │ │ │ ├── LinearRadialTicks .cs │ │ │ └── PointLabels.cs │ │ ├── PolarAreaConfig.cs │ │ ├── PolarAreaData.cs │ │ ├── PolarAreaDataset.cs │ │ └── PolarAreaOptions.cs │ ├── RadarChart │ │ ├── RadarConfig.cs │ │ ├── RadarData.cs │ │ ├── RadarDataset.cs │ │ ├── RadarOptions.cs │ │ └── Scale.cs │ └── ScatterChart │ │ ├── GridLineSettings.cs │ │ ├── ScatterAxis.cs │ │ ├── ScatterConfig.cs │ │ ├── ScatterData.cs │ │ ├── ScatterDataset.cs │ │ ├── ScatterOptions.cs │ │ └── ScatterScales.cs ├── Jtc.Optimization.ChartJs.csproj └── Util │ └── Color │ └── ColorUtil.cs ├── Jtc.Optimization.IntegrationTests ├── Features │ ├── LeanOptimization.feature │ ├── LeanOptimization.feature.cs │ ├── LeanOptimizationExecutable.feature │ └── LeanOptimizationExecutable.feature.cs ├── Jtc.Optimization.IntegrationTests.csproj ├── Steps │ ├── Given.cs │ ├── Then.cs │ └── When.cs ├── config.json └── optimization_test.json ├── Jtc.Optimization.Launcher.Legacy ├── App.config ├── Jtc.Optimization.Launcher.Legacy.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── Jtc.Optimization.LeanOptimizer.Base ├── BaseContextIsolator.cs ├── IRunner.cs ├── Jtc.Optimization.LeanOptimizer.Base.csproj ├── MultipleAssemblyLoadContext.cs ├── MultipleContextIsolator.cs ├── ResultMediator.cs └── SingleAssemblyLoadContext.cs ├── Jtc.Optimization.LeanOptimizer.Example ├── InstancedConfig.cs ├── Jtc.Optimization.LeanOptimizer.Example.csproj ├── ParameterizedAlgorithm.cs ├── ParameterizedSharedAppDomainAlgorithm.cs └── ParameterizedSharedAppDomainAlgorithm.py ├── Jtc.Optimization.LeanOptimizer.Launcher ├── Jtc.Optimization.LeanOptimizer.Launcher.csproj └── Program.cs ├── Jtc.Optimization.LeanOptimizer.Legacy ├── Jtc.Optimization.LeanOptimizer.Legacy.csproj ├── LegacyAppDomainManager.cs ├── Properties │ └── AssemblyInfo.cs ├── app.config └── packages.config ├── Jtc.Optimization.LeanOptimizer.Tests ├── ChromosomeTests.cs ├── Fitness │ ├── AdaptiveSharpeRatioFitnessTests.cs │ ├── ConfiguredFitnessTests.cs │ ├── DeflatedSharpeRatioFitnessTest.cs │ ├── DualPeriodSharpeFitnessTests.cs │ ├── NFoldCrossSharpeMaximizerTests.cs │ ├── OptimizerFitnessTests.cs │ ├── SharpeMaximizerTests.cs │ ├── WalkForwardPeriodCalculatorTests.cs │ ├── WalkForwardSharpeMaximizerTests.cs │ ├── WalkForwardWeightedMetricSharpeMaximizerTests.cs │ └── WeightedMetricCostTest.cs ├── GeneConverterTests.cs ├── GeneFactoryTests.cs ├── GeneManagerTests.cs ├── Handlers │ └── OptimizerResultHandlerTests.cs ├── Jtc.Optimization.LeanOptimizer.Tests.csproj ├── OptimizerInitializerTests.cs ├── StatisticsAdapterTests.cs ├── optimization_test.json └── packages.config ├── Jtc.Optimization.LeanOptimizer ├── BaseRunner.cs ├── ConfigMerger.cs ├── ExtensionMethods.cs ├── FibonacciRandomization.cs ├── Fitness │ ├── AdaptiveSharpeRatioFitness.cs │ ├── CompoundingAnnualReturnFitness.cs │ ├── ConfiguredFitness.cs │ ├── DeflatedSharpeRatioFitness.cs │ ├── DualPeriodSharpeFitness.cs │ ├── FitnessFilter.cs │ ├── ISharpeMaximizerFactory.cs │ ├── IWalkForwardSharpeMaximizer.cs │ ├── IWalkForwardSharpeMaximizerFactory.cs │ ├── NFoldCrossReturnMaximizer.cs │ ├── NFoldCrossSharpeMaximizer.cs │ ├── NestedCrossSharpeMaximizer.cs │ ├── OptimizerFitness.cs │ ├── SharpeMaximizer.cs │ ├── SharpeMaximizerFactory.cs │ ├── WalkForwardPeriodCalculator.cs │ ├── WalkForwardSharpeMaximizer.cs │ ├── WalkForwardSharpeMaximizerFactory.cs │ ├── WalkForwardWeightedMetricSharpeMaximizer.cs │ └── WeightedMetricCost.cs ├── Genetic │ ├── Chromosome.cs │ ├── ChromosomeBase.cs │ ├── GeneFactory.cs │ ├── GeneManager.cs │ └── PreloadPopulation.cs ├── Handlers │ ├── EmptyApiHandler.cs │ ├── EmptyObjectStore.cs │ ├── OptimizerAlphaHandler.cs │ ├── OptimizerResultHandler.cs │ └── OptimizerSubscriptionDataReaderHistoryProvider.cs ├── Interfaces │ ├── IFitnessFilter.cs │ └── IOptimizerManager.cs ├── Jtc.Optimization.LeanOptimizer.csproj ├── LogProvider.cs ├── LogSingleton.cs ├── MaximizerManager.cs ├── NLog.config ├── OptimizerLauncher.cs ├── Runner.cs ├── SingleContextIsolator.cs ├── SingleRunner.cs ├── StatisticsAdapter.cs ├── optimization.json └── remove_logs.bat ├── Jtc.Optimization.Objects ├── Enums.cs ├── FitnessConfiguration.cs ├── FitnessOptions.cs ├── FitnessResult.cs ├── GeneConfiguration.cs ├── Interfaces │ ├── IFitnessConfiguration.cs │ ├── IGeneConfiguration.cs │ └── IOptimizerConfiguration.cs ├── IterationResult.cs ├── Jtc.Optimization.Objects.csproj ├── OptimizerConfiguration.cs └── StatisticsBinding.cs ├── Jtc.Optimization.OnlineOptimizer ├── CSharpOptimizer.cs ├── CSharpThreadedOptimizer.cs ├── JavascriptOptimizer.cs ├── Jtc.Optimization.OnlineOptimizer.csproj └── OptimizerBase.cs ├── Jtc.Optimization.Tests ├── Attributes │ └── JavascriptFunctionValidatorAttributeTest.cs ├── CSharpCompilerTest.cs ├── JavascriptOptimizerTest.cs ├── Jtc.Optimization.Tests.csproj ├── PlotlyBinderTest.cs ├── PlotlyThreadedBinderTest.cs ├── RangeWithPrecisionTest.cs └── optimizer.txt ├── Jtc.Optimization.Transformation ├── ActivityLogger.cs ├── CSharpCompiler.cs ├── CSharpRemoteCompiler.cs ├── Interfaces │ ├── IActivityLogger.cs │ ├── ICSharpCompiler.cs │ ├── IMscorlibProvider.cs │ ├── IPlotlyBinder.cs │ ├── IPlotlyLineSplitter.cs │ └── IPlotlyLineSplitterBackgroundWrapper.cs ├── Jtc.Optimization.Transformation.csproj ├── MscorlibRemoteProvider.cs ├── PlotlyBinder.cs ├── PlotlyLineSplitter.cs ├── PlotlyLineSplitterBackgroundWrapper.cs ├── PlotlyThreadedBinder.cs ├── RangeWithPrecision.cs └── SwitchReader.cs ├── Jtc.Optimization.WpfClient ├── App.config ├── App.xaml ├── App.xaml.cs ├── Jtc.Optimization.WpfClient.csproj ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── packages.config └── running.ico ├── LICENSE ├── LeanParameterOptimization.BlazorClient.sln ├── LeanParameterOptimization.sln ├── README.md ├── SharpLearning.Common.Interfaces ├── IIndexedLearner.cs ├── ILearner.cs ├── IMetric.cs ├── IModelVariableImportance.cs ├── IPredictor.cs ├── IPredictorModel.cs └── SharpLearning.Common.Interfaces.csproj ├── SharpLearning.Containers ├── Arithmetic │ ├── MatrixAdd.cs │ ├── MatrixMultiplication.cs │ ├── MatrixSubtraction.cs │ └── MatrixTranspose.cs ├── CertaintyPrediction.cs ├── Checks.cs ├── Extensions │ └── ArrayExtensions.cs ├── FloatingPointConversion.cs ├── Matrices │ ├── F64Matrix.cs │ ├── F64MatrixExtensions.cs │ ├── IMatrix.cs │ ├── StringMatrix.cs │ └── StringMatrixExtensions.cs ├── ObservationTargetSet.cs ├── ProbabilityPrediction.cs ├── SharpLearning.Containers.csproj └── Views │ ├── F64MatrixColumnView.cs │ ├── F64MatrixPinnedPtr.cs │ ├── F64MatrixView.cs │ ├── F64VectorPinnedPtr.cs │ ├── F64VectorView.cs │ ├── Interval1D.cs │ └── Interval2D.cs ├── SharpLearning.DecisionTrees ├── ImpurityCalculators │ ├── ChildImpurities.cs │ ├── ClassificationImpurityCalculator.cs │ ├── GiniClassificationImpurityCalculator.cs │ ├── IImpurityCalculator.cs │ ├── RegressionImpurityCalculator.cs │ └── TargetCounts.cs ├── Learners │ ├── ClassificationDecisionTreeLearner.cs │ ├── DecisionTreeLearner.cs │ └── RegressionDecisionTreeLearner.cs ├── Models │ ├── ClassificationDecisionTreeModel.cs │ └── RegressionDecisionTreeModel.cs ├── Nodes │ ├── BinaryTree.cs │ ├── DecisionNodeCreationItem.cs │ ├── Node.cs │ ├── NodeExtensions.cs │ └── NodePositionType.cs ├── SharpLearning.DecisionTrees.csproj ├── SplitSearchers │ ├── ISplitSearcher.cs │ ├── LinearSplitSearcher.cs │ ├── OnlyUniqueThresholdsSplitSearcher.cs │ ├── RandomSplitSearcher.cs │ └── SplitResult.cs └── TreeBuilders │ ├── BestFirstTreeBuilder.cs │ ├── DepthFirstTreeBuilder.cs │ └── ITreeBuilder.cs ├── SharpLearning.InputOutput ├── Csv │ ├── CsvParser.cs │ ├── CsvRow.cs │ ├── CsvRowExtensions.cs │ ├── CsvWriter.cs │ └── DictionaryExtensions.cs ├── Serialization │ ├── GenericBinarySerializer.cs │ ├── GenericXmlDataContractSerializer.cs │ └── IGenericSerializer.cs └── SharpLearning.InputOutput.csproj ├── SharpLearning.Optimization ├── AcquisitionFunctions.cs ├── BayesianOptimizer.cs ├── GlobalizedBoundedNelderMeadOptimizer.cs ├── GridSearchOptimizer.cs ├── HyperbandOptimizer.cs ├── IOptimizer.cs ├── OptimizerResult.cs ├── ParameterSamplers │ ├── IParameterSampler.cs │ └── RandomUniform.cs ├── ParameterSpecs │ ├── GridParameterSpec.cs │ ├── IParameterSpec.cs │ └── MinMaxParameterSpec.cs ├── ParameterType.cs ├── ParticleSwarmOptimizer.cs ├── RandomSearchOptimizer.cs ├── SharpLearning.Optimization.csproj ├── SmacOptimizer.cs ├── Transform.cs └── Transforms │ ├── ExponentialAverageTransform.cs │ ├── ITransform.cs │ ├── LinearTransform.cs │ ├── Log10Transform.cs │ └── TransformFactory.cs ├── SharpLearning.RandomForest ├── Learners │ ├── ClassificationExtremelyRandomizedTreesLearner.cs │ ├── ClassificationRandomForestLearner.cs │ ├── RegressionExtremelyRandomizedTreesLearner.cs │ └── RegressionRandomForestLearner.cs ├── Models │ ├── ClassificationForestModel.cs │ └── RegressionForestModel.cs └── SharpLearning.RandomForest.csproj ├── chart.png ├── config.png ├── run_blazor.bat └── run_debugger.bat /Jtc.Optimization.Api/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "dotnet-ef": { 6 | "version": "3.1.2", 7 | "commands": [ 8 | "dotnet-ef" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Controllers/CompilerController.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Transformation; 2 | using Microsoft.AspNetCore.Cors; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Net.Http.Headers; 9 | using System.Reflection; 10 | using System.Runtime.Serialization.Formatters.Binary; 11 | using System.Text; 12 | using System.Threading.Tasks; 13 | 14 | namespace Jtc.Optimization.Api.Controllers 15 | { 16 | 17 | [Route("api/[controller]")] 18 | [ApiController] 19 | public class CompilerController : ControllerBase 20 | { 21 | 22 | private readonly ICSharpCompiler _cSharpCompiler; 23 | 24 | public CompilerController(ICSharpCompiler cSharpCompiler) 25 | { 26 | _cSharpCompiler = cSharpCompiler; 27 | } 28 | 29 | [HttpPost] 30 | public async Task Index() 31 | { 32 | throw new NotSupportedException(); 33 | 34 | var code = ""; 35 | using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) 36 | { 37 | code = await reader.ReadToEndAsync(); 38 | } 39 | 40 | var stream = await _cSharpCompiler.GetStream(code); 41 | 42 | if (stream == null) 43 | { 44 | return new StatusCodeResult(412); 45 | } 46 | 47 | return File(((MemoryStream)stream).ToArray(), "application/octet-stream"); 48 | } 49 | 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Controllers/MscorlibController.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Transformation; 2 | using Microsoft.AspNetCore.Cors; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Net.Http.Headers; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace Jtc.Optimization.Api.Controllers 13 | { 14 | 15 | [Route("api/[controller]")] 16 | [ApiController] 17 | public class MscorlibController : ControllerBase 18 | { 19 | 20 | private readonly IMscorlibProvider _mscorlibProvider; 21 | 22 | public MscorlibController(IMscorlibProvider mscorlibProvider) 23 | { 24 | _mscorlibProvider = mscorlibProvider; 25 | } 26 | 27 | [HttpGet] 28 | public async Task Index() 29 | { 30 | var assembly = await _mscorlibProvider.Get(); 31 | 32 | return File(assembly.ToArray(), "application/octet-stream"); 33 | } 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Jtc.Optimization.Api.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | InProcess 6 | false 7 | false 8 | AnyCPU;x64 9 | true 10 | 1a1618c5-c7d1-4eb8-94c3-46bc285b13c7 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | True 26 | True 27 | Resource.resx 28 | 29 | 30 | 31 | 32 | 33 | ResXFileCodeGenerator 34 | Resource.Designer.cs 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/MscorlibProvider.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Transformation; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | 8 | namespace Jtc.Optimization.Api 9 | { 10 | public class MscorlibProvider : IMscorlibProvider 11 | { 12 | 13 | public Task Get() 14 | { 15 | return Task.FromResult(Resource.mscorlib); 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Jtc.Optimization.Api 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseStartup(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:5000", 7 | "sslPort": 44338 8 | } 9 | }, 10 | "$schema": "http://json.schemastore.org/launchsettings.json", 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchUrl": "api/values", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "Jtc.Optimization.Api": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | }, 26 | "applicationUrl": "http://localhost:5000" 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Api/Resources/mscorlib.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/Jtc.Optimization.Api/Resources/mscorlib.dll -------------------------------------------------------------------------------- /Jtc.Optimization.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*", 8 | "ResultsPath": "" 9 | } 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.Api/nlog.config: -------------------------------------------------------------------------------- 1 |  2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient.Objects/BlazorClientConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Jtc.Optimization.BlazorClient.Objects 6 | { 7 | public class BlazorClientConfiguration : IBlazorClientConfiguration 8 | { 9 | 10 | public bool CompileCSharpInBrowser { get; set; } = true; 11 | public bool EnableThreadedCSharpOptimizer { get; set; } = false; 12 | public bool EnableOptimizerWorker { get; set; } = true; 13 | public bool EnableOptimizerMultithreading { get; set; } = false; 14 | 15 | #if DEBUG 16 | public string ApiUrl { get; set; } = "localhost:5000"; 17 | #else 18 | public string ApiUrl { get; set; } = "api.optimizers.ml"; 19 | #endif 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient.Objects/IBlazorClientConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace Jtc.Optimization.BlazorClient.Objects 2 | { 3 | public interface IBlazorClientConfiguration 4 | { 5 | bool CompileCSharpInBrowser { get; set; } 6 | bool EnableThreadedCSharpOptimizer { get; set; } 7 | bool EnableOptimizerWorker { get; set; } 8 | bool EnableOptimizerMultithreading { get; set; } 9 | string ApiUrl { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient.Objects/Jtc.Optimization.BlazorClient.Objects.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient.Objects/PlotlyData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace Jtc.Optimization.BlazorClient.Objects 6 | { 7 | 8 | public class PlotlyData 9 | { 10 | 11 | public List X { get; set; } = new List(); 12 | public List Text { get; set; } = new List(); 13 | public List Y { get; set; } = new List(); 14 | public string Mode { get; set; } = "markers"; 15 | public string Type { get; set; } = "scattergl"; 16 | public string Name { get; set; } 17 | public Marker Marker { get; set; } 18 | [JsonPropertyName("hovertemplate")] 19 | public string HoverTemplate { get; set; } = "%{text}"; 20 | } 21 | 22 | public class Line 23 | { 24 | public string Color { get; set; } 25 | } 26 | 27 | public class Marker 28 | { 29 | public string Color { get; set; } 30 | public Line Line { get; set; } 31 | } 32 | 33 | public class ErrorY 34 | { 35 | public string Color { get; set; } 36 | } 37 | 38 | public class ErrorX 39 | { 40 | public string Color { get; set; } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 |

Sorry, there's nothing at this address.

8 |
9 |
10 |
11 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Attributes/ExportedWebAssemblyJSRuntime.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Globalization; 3 | using System.Text.Json; 4 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 5 | using Microsoft.JSInterop; 6 | using Microsoft.JSInterop.Infrastructure; 7 | using Microsoft.JSInterop.WebAssembly; 8 | 9 | namespace Jtc.Optimization.BlazorClient.Attributes 10 | { 11 | 12 | /// 13 | /// Export internal IJSRuntime implemenation 14 | /// 15 | internal sealed class ExportedWebAssemblyJSRuntime : WebAssemblyJSRuntime 16 | { 17 | internal static readonly ExportedWebAssemblyJSRuntime Instance = new(); 18 | 19 | } 20 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/BlazorClientState.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.BlazorClient 8 | { 9 | public class BlazorClientState 10 | { 11 | 12 | Dictionary _registry = new Dictionary(); 13 | 14 | public void SubscribeStateHasChanged(Type componentType, Action action) 15 | { 16 | if (_registry.ContainsKey(componentType)) 17 | { 18 | _registry.Remove(componentType); 19 | } 20 | _registry.Add(componentType, action); 21 | 22 | } 23 | 24 | public void NotifyStateHasChanged(Type componentType) 25 | { 26 | _registry[componentType].Invoke(); 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "", Scope = "namespaceanddescendants", Target = "Jtc.Optimization.BlazorClient")] 7 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "", Scope = "namespaceanddescendants", Target = "Jtc.Optimization.BlazorClient")] 8 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "", Scope = "namespaceanddescendants", Target = "Jtc.Optimization.BlazorClient")] -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Jtc.Optimization.BlazorClient.runtimeconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "runtimeOptions": { 3 | "tfm": "netcoreapp3.0", 4 | "framework": { 5 | "name": "Microsoft.NETCore.App", 6 | "version": "3.0.0" 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Models/FitnessConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using static Jtc.Optimization.Objects.Enums; 4 | using Jtc.Optimization.Objects.Interfaces; 5 | 6 | namespace Jtc.Optimization.BlazorClient.Models 7 | { 8 | [Serializable] 9 | public class FitnessConfiguration : IFitnessConfiguration 10 | { 11 | 12 | [Required] 13 | public string Name { get; set; } 14 | 15 | [Required] 16 | public string ResultKey { get; set; } 17 | 18 | [Range(1, int.MaxValue)] 19 | public double? Scale { get; set; } = 1; 20 | 21 | public double? Modifier { get; set; } = 1; 22 | 23 | public string OptimizerTypeName { get; set; } = OptimizerTypeOptions.Genetic.ToString(); 24 | 25 | [Range(1, int.MaxValue)] 26 | public int Folds { get; set; } = 1; 27 | 28 | public string FoldOptimizerTypeName { get; set; } 29 | 30 | public int? FoldGenerations { get; set; } 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Models/GeneConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Jtc.Optimization.BlazorClient.Models 10 | { 11 | 12 | public class GeneConfiguration 13 | { 14 | /// 15 | /// The unique key of the gene 16 | /// 17 | [Required] 18 | public string Key { get; set; } 19 | 20 | /// 21 | /// The minimum value for a value 22 | /// 23 | [Required] 24 | public double? Min { get; set; } 25 | 26 | /// 27 | /// The maximum value for a value 28 | /// 29 | [Required] 30 | public double? Max { get; set; } 31 | 32 | /// 33 | /// The precision (rounding) for gene values 34 | /// 35 | public int? Precision { get; set; } 36 | 37 | /// 38 | /// The non-random starting value 39 | /// 40 | public double? Actual { get; set; } 41 | 42 | /// 43 | /// When true, will randomly select a value between 0 to 10946 from the Fibonacci sequence instead of generating random values 44 | /// 45 | /// 46 | public bool Fibonacci { get; set; } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Models/MinimizeFunctionCode.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.BlazorClient.Attributes; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.BlazorClient.Models 8 | { 9 | 10 | public class MinimizeFunctionCode 11 | { 12 | 13 | public string Language { get; set; } = "javascript"; 14 | 15 | [JavascriptFunctionValidator] 16 | public string Code { get; set; } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Pages/CodeEditor.razor: -------------------------------------------------------------------------------- 1 | @page "/CodeEditor" 2 | @inherits Jtc.Optimization.BlazorClient.CodeEditorBase 3 | @using Jtc.Optimization.BlazorClient.Models 4 | 5 |
6 | 7 | 8 |
9 |
10 |
11 | 12 | 16 | @if (MinimizeFunctionCode.Language == "javascript") 17 | { 18 | 19 | 20 | } 21 | 22 |
23 |
24 |
25 | 26 |
27 |
28 | 29 |
30 | 31 | 32 |
33 | 34 | 35 |
36 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Pages/Default.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | @{ } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:61221/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 15 | "launchUrl": "http://localhost:61221/codeeditor", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Jtc.Optimization.BlazorClient": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 24 | "environmentVariables": { 25 | "ASPNETCORE_ENVIRONMENT": "Development" 26 | }, 27 | "applicationUrl": "http://localhost:61222/" 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/GeneConfig.razor: -------------------------------------------------------------------------------- 1 | @inherits Jtc.Optimization.BlazorClient.Shared.GeneConfigBase 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/GeneConfigBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Components; 4 | 5 | namespace Jtc.Optimization.BlazorClient.Shared 6 | { 7 | public class GeneConfigBase : ComponentBase 8 | { 9 | 10 | 11 | [Parameter] 12 | public Models.GeneConfiguration Gene { get; set; } 13 | 14 | 15 | protected string GetStep() 16 | { 17 | if (Gene.Precision == null || !Gene.Precision.HasValue) 18 | { 19 | return "1"; 20 | } 21 | 22 | return Math.Pow(0.1, Gene.Precision.Value).ToString(); 23 | } 24 | 25 | 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 | 10 |
11 | 12 | 13 | @Body 14 |
15 |
16 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/Sidebar.razor: -------------------------------------------------------------------------------- 1 | @inherits BlazorClient.Shared.SidebarBase 2 | 3 | 29 |
30 | 31 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/SidebarShow.razor: -------------------------------------------------------------------------------- 1 |  2 | 4 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/Shared/Wait.razor: -------------------------------------------------------------------------------- 1 | @inherits Jtc.Optimization.BlazorClient.Shared.WaitBase 2 | 3 |
4 | 5 |
@Message
6 |
7 |
8 | Cancel? Are you sure? 9 | 10 | 11 |
12 | @*
13 |
14 |
*@ 15 |
-------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using Microsoft.AspNetCore.Components.Forms 3 | @using Microsoft.AspNetCore.Components.Routing 4 | @using Microsoft.JSInterop 5 | @using Jtc.Optimization.BlazorClient 6 | @using Jtc.Optimization.BlazorClient.Shared 7 | @using Microsoft.AspNetCore.Components.Web 8 | @using Blazored.Toast 9 | @using Blazored.Toast.Services 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/libman.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "defaultProvider": "cdnjs", 4 | "libraries": [ 5 | { 6 | "library": "plotly.js@1.51.1", 7 | "destination": "wwwroot/lib/plotly.js/", 8 | "files": [ 9 | "plotly.min.js" 10 | ] 11 | }, 12 | { 13 | "library": "jquery@3.4.1", 14 | "destination": "wwwroot/lib/jquery/", 15 | "files": [ 16 | "jquery.min.js", 17 | "jquery.min.map" 18 | ] 19 | }, 20 | { 21 | "provider": "jsdelivr", 22 | "library": "workerpool@5.0.4", 23 | "destination": "wwwroot/lib/workerpool/", 24 | "files": [ 25 | "dist/worker.js", 26 | "dist/worker.min.js", 27 | "dist/workerpool.js", 28 | "dist/workerpool.map", 29 | "dist/workerpool.min.js" 30 | ] 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/ChartWorkerMessaging.js: -------------------------------------------------------------------------------- 1 | //importScripts("_framework/blazor.webassembly.js"); 2 | //importScripts("ChartJsInterop.js"); 3 | 4 | 5 | onmessage = function (e) { 6 | //innerWorker = e.data; 7 | //innerWorker.invokeMethodAsync("UpdateChart"); 8 | //DotNet.invokeMethodAsync('', 'UpdateChart'); 9 | //DotNet.invokeMethod("Jtc.Optimization.BlazorClient", "ChartWorker.UpdateChart"); 10 | //ChartJsInterop.UpdateChartData("Scatter", e.data); 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/ClientStorage.js: -------------------------------------------------------------------------------- 1 | window.ClientStorage = { 2 | 3 | storeConfig: (data) => { 4 | localStorage.setItem("config", data); 5 | }, 6 | 7 | fetchConfig: () => { 8 | return localStorage.getItem("config"); 9 | }, 10 | 11 | storeChartData: (data) => { 12 | localStorage.setItem("chartData", data); 13 | }, 14 | 15 | fetchChartData: () => { 16 | return localStorage.getItem("chartData"); 17 | }, 18 | 19 | hasChartData: () => { 20 | return localStorage.hasOwnProperty("chartData") && localStorage.getItem("chartData").length > 0; 21 | } 22 | 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/MainInterop.js: -------------------------------------------------------------------------------- 1 | window.MainInterop = { 2 | 3 | readUploadedFileAsText: (inputFile) => { 4 | const temporaryFileReader = new FileReader(); 5 | 6 | return new Promise((resolve, reject) => { 7 | temporaryFileReader.onerror = () => { 8 | temporaryFileReader.abort(); 9 | reject(new DOMException("Problem parsing input file.")); 10 | }; 11 | 12 | temporaryFileReader.onload = () => { 13 | resolve(temporaryFileReader.result); 14 | }; 15 | temporaryFileReader.readAsText(inputFile); 16 | }); 17 | }, 18 | 19 | getFileData: async () => { 20 | const file = document.getElementById("fileUpload").files[0]; 21 | 22 | try { 23 | const fileContents = await MainInterop.readUploadedFileAsText(file); 24 | return fileContents; 25 | } 26 | catch (e) { 27 | console.warn(e.message); 28 | } 29 | }, 30 | 31 | downloadConfig: (json) => { 32 | blob = new Blob([json], { type: "octet/stream" }), url = window.URL.createObjectURL(blob); 33 | 34 | var save = document.getElementById("save"); 35 | save.href = url; 36 | 37 | // target filename 38 | save.download = 'optimization.json'; 39 | }, 40 | 41 | activityLogChanged: (e) => { 42 | e.target.scrollTop(Number.MAX_SAFE_INTEGER); 43 | }, 44 | 45 | }; 46 | 47 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/SideBar.js: -------------------------------------------------------------------------------- 1 |  2 | window.Sidebar = { 3 | 4 | initialize: function () { 5 | $("#sidebar").mCustomScrollbar({ 6 | theme: "minimal" 7 | }); 8 | 9 | $('#dismiss, .overlay, a[data-toggle=collapse]').on('click', function () { 10 | // hide sidebar 11 | $('#sidebar').removeClass('active'); 12 | // hide overlay 13 | $('.overlay').removeClass('active'); 14 | }); 15 | 16 | $('#sidebarCollapse').on('click', function () { 17 | // open sidebar 18 | $('#sidebar').addClass('active'); 19 | // fade in the overlay 20 | $('.overlay').addClass('active'); 21 | $('.collapse.in').toggleClass('in'); 22 | $('a[aria-expanded=true]').attr('aria-expanded', 'false'); 23 | }); 24 | } 25 | }; -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/WorkerInterop.js: -------------------------------------------------------------------------------- 1 | window.WorkerInterop = { 2 | 3 | instance: null, 4 | 5 | runWorker: (code) => { 6 | if (typeof (Worker) !== "undefined") { 7 | 8 | if (typeof (instance) === "undefined") { 9 | instance = new Worker("worker.js"); 10 | //console.log("Worker was initialized."); 11 | } 12 | 13 | instance.onmessage = function (event) { 14 | //console.log("Worker sent:" + event.data); 15 | workerCallback.invokeMethodAsync(workerMethodname, event.data); 16 | }; 17 | 18 | } 19 | else { 20 | //todo: fall back to ui thread 21 | document.getElementsByTagName("body").innerHTML += "Sorry, your browser is not supported."; 22 | } 23 | 24 | instance.postMessage(code); 25 | }, 26 | 27 | workerCallback: null, 28 | 29 | workerMethodname: null, 30 | 31 | setWorkerCallback: (reference, methodName) => { 32 | workerCallback = reference; 33 | workerMethodname = methodName; 34 | } 35 | 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/WorkerPoolInterop.js: -------------------------------------------------------------------------------- 1 | window.pool = workerpool.pool(); 2 | 3 | window.WorkerPoolInterop = { 4 | 5 | methodName: null, 6 | 7 | //todo: needed? 8 | callBackRegistry: [], 9 | 10 | runWorker: (dotNetreference, methodName, code, key) => { 11 | if (typeof (Worker) !== "undefined") { 12 | 13 | WorkerPoolInterop.methodName = methodName; 14 | 15 | //console.log("Worker thread commenced."); 16 | 17 | WorkerPoolInterop.callBackRegistry[dotNetreference._id] = dotNetreference; 18 | 19 | pool.exec(WorkerPoolInterop.executeEval, [dotNetreference._id, code, key]) 20 | .then(function (result) { 21 | //console.log("Worker thread completed."); 22 | WorkerPoolInterop.callBackRegistry[result[0]].invokeMethodAsync(methodName, result[2], result[1]); 23 | }) 24 | .catch(function (err) { 25 | console.error(err); 26 | dotNetreference.invokeMethodAsync(methodName, -10, key); 27 | }); 28 | } 29 | else { 30 | //todo: fall back to ui thread 31 | document.getElementsByTagName("body").innerHTML += "Sorry, your browser is not supported."; 32 | } 33 | }, 34 | 35 | executeEval: function (callbackId, code, key) { 36 | return [callbackId, eval(code), key]; 37 | } 38 | }; 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/appSettings.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/Jtc.Optimization.BlazorClient/wwwroot/appSettings.json -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/donate-bitcoin/index.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Donate Bitcoin 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 |
18 |
19 | 20 |

21 |
22 |
23 |
24 |
25 |
26 | 27 | 35 | 36 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/Jtc.Optimization.BlazorClient/wwwroot/favicon.ico -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/images/Hamburger_icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | background 5 | 6 | 7 | 8 | Layer 1 9 | 10 | 11 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/images/run2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/Jtc.Optimization.BlazorClient/wwwroot/images/run2.gif -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/lib/crosstalk-1.0.0/css/crosstalk.css: -------------------------------------------------------------------------------- 1 | /* Adjust margins outwards, so column contents line up with the edges of the 2 | parent of container-fluid. */ 3 | .container-fluid.crosstalk-bscols { 4 | margin-left: -30px; 5 | margin-right: -30px; 6 | white-space: normal; 7 | } 8 | 9 | /* But don't adjust the margins outwards if we're directly under the body, 10 | i.e. we were the top-level of something at the console. */ 11 | body > .container-fluid.crosstalk-bscols { 12 | margin-left: auto; 13 | margin-right: auto; 14 | } 15 | 16 | .crosstalk-input-checkboxgroup .crosstalk-options-group .crosstalk-options-column { 17 | display: inline-block; 18 | padding-right: 12px; 19 | vertical-align: top; 20 | } 21 | 22 | @media only screen and (max-width:480px) { 23 | .crosstalk-input-checkboxgroup .crosstalk-options-group .crosstalk-options-column { 24 | display: block; 25 | padding-right: inherit; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/lib/plotly-htmlwidgets-css-1.39.2/plotly-htmlwidgets.css: -------------------------------------------------------------------------------- 1 | /* 2 | just here so that plotly works 3 | correctly with ioslides. 4 | see https://github.com/ropensci/plotly/issues/463 5 | */ 6 | 7 | slide:not(.current) .plotly.html-widget{ 8 | display: none; 9 | } 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/robots.txt: -------------------------------------------------------------------------------- 1 | Sitemap: http://optimizers.ml/sitemap.xml -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/sitemap.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | http://optimizers.ml/ 11 | 12 | 13 | http://optimizers.ml/codeeditor 14 | 15 | 16 | http://optimizers.ml/config 17 | 18 | 19 | http://optimizers.ml/chart 20 | 21 | 22 | http://optimizers.ml/info 23 | 24 | 25 | http://optimizers.ml/quickstart 26 | 27 | -------------------------------------------------------------------------------- /Jtc.Optimization.BlazorClient/wwwroot/worker.js: -------------------------------------------------------------------------------- 1 | onmessage = function (e) { 2 | 3 | // console.log('Message received:' + e.data); 4 | 5 | var result = eval(e.data); 6 | 7 | this.postMessage(result); 8 | }; -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BarChart/BarAxis.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.BarChart 2 | { 3 | public class BarAxis 4 | { 5 | public bool Stacked { get; set; } = false; 6 | } 7 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BarChart/BarConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.BarChart 5 | { 6 | /// 7 | /// Config for a bar chart with type safe data 8 | /// Either 'bar' or 'horizontalBar' 9 | /// 10 | public class BarConfig : ConfigBase 11 | { 12 | public BarConfig(ChartType type = null) : base(type ?? ChartType.Bar) { } 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BarChart/BarData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using ChartJs.Blazor.ChartJS.MixedChart; 3 | 4 | namespace ChartJs.Blazor.ChartJS.BarChart 5 | { 6 | public class BarData 7 | { 8 | public List Labels { get; set; } = new List(); 9 | 10 | // TODO: implement like LineData 11 | public List> Datasets { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BarChart/BarOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | 3 | namespace ChartJs.Blazor.ChartJS.BarChart 4 | { 5 | /// 6 | /// Bar Chart Config Options. Source: http://www.chartjs.org/docs/latest/charts/bar.html#configuration-options 7 | /// 8 | public class BarOptions : BaseConfigOptions 9 | { 10 | // TODO: Make sure these properties are where they're supposed to be. From the looks of the docs they should be in each axis, not in the options itself. 11 | 12 | /// 13 | /// Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other 14 | /// 15 | public double BarPercentage { get; set; } = 0.9; 16 | 17 | /// 18 | /// Percent (0-1) of the available width each category should be within the sample width. 19 | /// 20 | public double CategoryPercentage { get; set; } = 0.8; 21 | 22 | /// 23 | /// Manually set width of each bar in pixels. If set to 'flex', it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. 24 | /// 25 | public object BarThickness { get; set; } 26 | 27 | /// 28 | /// Set this to ensure that bars are not sized thicker than this. 29 | /// 30 | public object MaxBarThickness { get; set; } 31 | 32 | public BarOptionsScales Scales { get; set; } 33 | } 34 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BarChart/BarOptionsScales.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.BarChart 2 | { 3 | public class BarOptionsScales 4 | { 5 | public BarAxis[] xAxes { get; set; } 6 | public BarAxis[] yAxes { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BubbleChart/BubbleConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.BubbleChart 5 | { 6 | public class BubbleConfig : ConfigBase 7 | { 8 | public BubbleConfig() : base(ChartType.Bubble) { } 9 | } 10 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BubbleChart/BubbleData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using ChartJs.Blazor.ChartJS.Common.Properties; 3 | 4 | namespace ChartJs.Blazor.ChartJS.BubbleChart 5 | { 6 | public class BubbleData 7 | { 8 | public Animation Animation { get; set; } 9 | 10 | public List Datasets { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BubbleChart/BubbleDataPoint.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | 3 | namespace ChartJs.Blazor.ChartJS.BubbleChart 4 | { 5 | public class BubbleDataPoint : Point 6 | { 7 | /// 8 | /// Bubble radius, in pixels, not scaled 9 | /// 10 | public double r { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/BubbleChart/BubbleOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Properties; 3 | 4 | namespace ChartJs.Blazor.ChartJS.BubbleChart 5 | { 6 | public class BubbleOptions : BaseConfigOptions 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Axis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common 4 | { 5 | /// 6 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/#common-configuration. 7 | /// 8 | public abstract class Axis 9 | { 10 | /// 11 | /// Controls the axis global visibility (visible when , hidden when ). 12 | /// When display: , the axis is visible only if at least one associated dataset is visible. 13 | /// 14 | public AxisDisplay Display { get; set; } = AxisDisplay.True; 15 | 16 | /// 17 | /// The weight used to sort the axis. Higher weights are further away from the chart area. 18 | /// 19 | public int? Weight { get; set; } 20 | 21 | // TODO: Maybe implement: https://www.chartjs.org/docs/latest/axes/#callbacks 22 | // public object Callbacks { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/AxisDisplay.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common.Enums 3 | { 4 | /// 5 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/#common-configuration 6 | /// 7 | public sealed class AxisDisplay : ObjectEnum 8 | { 9 | /// 10 | /// Hidden 11 | /// 12 | public static AxisDisplay False => new AxisDisplay(false); 13 | 14 | /// 15 | /// Visible 16 | /// 17 | public static AxisDisplay True => new AxisDisplay(true); 18 | 19 | /// 20 | /// Visible only if at least one associated dataset is visible 21 | /// 22 | public static AxisDisplay Auto => new AxisDisplay("auto"); 23 | 24 | 25 | private AxisDisplay(string stringValue) : base(stringValue) { } 26 | private AxisDisplay(bool boolValue) : base(boolValue) { } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/BorderAlign.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies the border alignment of a and a . 5 | /// As per documentation here https://www.chartjs.org/docs/latest/charts/doughnut.html#border-alignment 6 | /// 7 | public sealed class BorderAlign : StringEnum 8 | { 9 | /// 10 | /// When is set, the borders of arcs next to each other will overlap. The default value. 11 | /// 12 | public static BorderAlign Center => new BorderAlign("center"); 13 | 14 | /// 15 | /// When is set, it is guaranteed that all the borders will not overlap. 16 | /// 17 | public static BorderAlign Inner => new BorderAlign("inner"); 18 | 19 | /// 20 | /// Creates a new instance of the class. 21 | /// 22 | /// The value to set. 23 | private BorderAlign(string stringValue) : base(stringValue) { } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/BorderCapStyle.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies the border cap style. 5 | /// As per documentation here https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap 6 | /// 7 | public sealed class BorderCapStyle : StringEnum 8 | { 9 | /// 10 | /// The ends of lines are squared off at the endpoints. 11 | /// 12 | public static BorderCapStyle Butt => new BorderCapStyle("butt"); 13 | 14 | /// 15 | /// The ends of lines are rounded. 16 | /// 17 | public static BorderCapStyle Round => new BorderCapStyle("round"); 18 | 19 | /// 20 | /// The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. 21 | /// 22 | public static BorderCapStyle Square => new BorderCapStyle("square"); 23 | 24 | /// 25 | /// Creates a new instance of the class. 26 | /// 27 | /// The value to set. 28 | private BorderCapStyle(string stringValue) : base(stringValue) { } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/BorderJoinStyle.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies the border join style. 5 | /// As per documentation here https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin 6 | /// 7 | public sealed class BorderJoinStyle : StringEnum 8 | { 9 | /// 10 | /// Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment. 11 | /// 12 | public static BorderJoinStyle Bevel => new BorderJoinStyle("bevel"); 13 | 14 | /// 15 | /// Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to the line width. 16 | /// 17 | public static BorderJoinStyle Round => new BorderJoinStyle("round"); 18 | 19 | /// 20 | /// Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. 21 | /// 22 | public static BorderJoinStyle Miter => new BorderJoinStyle("miter"); 23 | 24 | /// 25 | /// Creates a new instance of the class. 26 | /// 27 | /// The value to set. 28 | private BorderJoinStyle(string stringValue) : base(stringValue) { } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/CubicInterpolationMode.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies the cubic interpolation mode. 5 | /// As per documentation here https://www.chartjs.org/docs/latest/charts/line.html#cubicinterpolationmode 6 | /// 7 | public sealed class CubicInterpolationMode : StringEnum 8 | { 9 | /// 10 | /// The default cubic interpolation mode. 11 | /// The algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets. 12 | /// 13 | public static CubicInterpolationMode Default => new CubicInterpolationMode("default"); 14 | 15 | /// 16 | /// The monotone cubic interpolation mode. 17 | /// The algorithm is more suited to y = f(x) datasets: 18 | /// It preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extrema (if any) stay at input data points. 19 | /// 20 | public static CubicInterpolationMode Monotone => new CubicInterpolationMode("monotone"); 21 | 22 | /// 23 | /// Creates a new instance of the class. 24 | /// 25 | /// The value to set. 26 | private CubicInterpolationMode(string stringValue) : base(stringValue) { } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/JsonConverter/JsonObjectEnumConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common.Enums.JsonConverter 4 | { 5 | /// 6 | /// JsonConverter for converting and writing an ObjectEnum value. This JsonConverter can only write. 7 | /// 8 | internal class JsonObjectEnumConverter : JsonWriteOnlyConverter 9 | { 10 | public override void WriteJson(JsonWriter writer, ObjectEnum wrapper, JsonSerializer serializer) 11 | { 12 | try 13 | { 14 | // if it can be written in a single JToken, 15 | // json.net understands what type the wrapped object (.Value) is and serializes it accordingly -> correct value and type (eg. bool, string, double) 16 | writer.WriteValue(wrapper.Value); 17 | } 18 | catch (JsonWriterException) 19 | { 20 | // if there was an error, try to explicitly serialize it before writing 21 | // if this also fails just let it bubble up because the developer should not have values in their enum that fail here 22 | serializer.Serialize(writer, wrapper.Value); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/JsonConverter/JsonStringEnumConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common.Enums.JsonConverter 4 | { 5 | /// 6 | /// JsonConverter for converting and writing a StringEnum value. This JsonConverter can only write. 7 | /// 8 | internal class JsonStringEnumConverter : JsonWriteOnlyConverter 9 | { 10 | public override void WriteJson(JsonWriter writer, StringEnum value, JsonSerializer serializer) 11 | { 12 | // ToString was overwritten by StringEnum -> safe to just print the string representation 13 | writer.WriteValue(value.ToString()); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/Position.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Represents a relative direction or position on a 2D canvas. 5 | /// 6 | public sealed class Position : StringEnum 7 | { 8 | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 9 | public static Position Left => new Position("left"); 10 | public static Position Right => new Position("right"); 11 | public static Position Top => new Position("top"); 12 | public static Position Bottom => new Position("bottom"); 13 | #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 14 | 15 | private Position(string stringRep) : base(stringRep) { } 16 | } 17 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/ScaleBound.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies the scale boundary strategy. 5 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/time.html#scale-bounds 6 | /// 7 | public sealed class ScaleBound : StringEnum 8 | { 9 | /// 10 | /// Makes sure data are fully visible, labels outside are removed. 11 | /// 12 | public static ScaleBound Data => new ScaleBound("data"); 13 | 14 | /// 15 | /// Makes sure ticks are fully visible, data outside are truncated. 16 | /// 17 | public static ScaleBound Ticks => new ScaleBound("ticks"); 18 | 19 | private ScaleBound(string stringRep) : base(stringRep) { } 20 | } 21 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/SteppedLine.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common.Enums 3 | { 4 | /// 5 | /// As per documentation here https://www.chartjs.org/docs/latest/charts/line.html#stepped-line 6 | /// 7 | public sealed class SteppedLine : ObjectEnum 8 | { 9 | /// 10 | /// No Step Interpolation (default) 11 | /// 12 | public static SteppedLine False => new SteppedLine(false); 13 | 14 | /// 15 | /// Step-before Interpolation (same as ) 16 | /// 17 | public static SteppedLine True => new SteppedLine(true); 18 | 19 | /// 20 | /// Step-before Interpolation 21 | /// 22 | public static SteppedLine Before => new SteppedLine("before"); 23 | 24 | /// 25 | /// Step-after Interpolation 26 | /// 27 | public static SteppedLine After => new SteppedLine("after"); 28 | 29 | /// 30 | /// Step-middle Interpolation 31 | /// 32 | public static SteppedLine Middle => new SteppedLine("middle"); 33 | 34 | private SteppedLine(string stringValue) : base(stringValue) { } 35 | private SteppedLine(bool boolValue) : base(boolValue) { } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/StringEnum.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using ChartJs.Blazor.ChartJS.Common.Enums.JsonConverter; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Enums 5 | { 6 | [JsonConverter(typeof(JsonStringEnumConverter))] 7 | public abstract class StringEnum 8 | { 9 | private readonly string _value; 10 | 11 | protected StringEnum(string stringRep) => _value = stringRep; 12 | 13 | public override string ToString() => _value; 14 | 15 | public static explicit operator string(StringEnum stringEnum) => stringEnum.ToString(); 16 | 17 | 18 | public static bool operator == (StringEnum a, StringEnum b) => a.ToString() == b.ToString(); 19 | public static bool operator != (StringEnum a, StringEnum b) => a.ToString() != b.ToString(); 20 | 21 | public override bool Equals(object obj) 22 | { 23 | if (typeof(StringEnum).IsAssignableFrom(obj.GetType())) return _value.Equals(obj.ToString()); 24 | 25 | // it also counts as equal if the object to compare is equal to the string stored in the wrapper 26 | if (obj.GetType() == typeof(string)) return _value.Equals((string)obj); 27 | 28 | return false; 29 | } 30 | 31 | public override int GetHashCode() => _value.GetHashCode(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/TickSource.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/time.html#ticks-source 5 | /// 6 | /// 7 | public sealed class TickSource : StringEnum 8 | { 9 | /// 10 | /// Generates "optimal" ticks based on scale size and time options 11 | /// 12 | public static TickSource Auto => new TickSource("auto"); 13 | 14 | /// 15 | /// Generates ticks from data (including labels from data {t|x|y} objects) 16 | /// 17 | public static TickSource Data => new TickSource("data"); 18 | 19 | /// 20 | /// Generates ticks from user given values ONLY 21 | /// 22 | public static TickSource Labels => new TickSource("labels"); 23 | 24 | 25 | private TickSource(string stringRep) : base(stringRep) { } 26 | } 27 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/TimeDistribution.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common.Enums 3 | { 4 | /// 5 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/time.html#scale-distribution 6 | /// 7 | public sealed class TimeDistribution : StringEnum 8 | { 9 | /// 10 | /// Data are spread according to their time (distances can vary) 11 | /// 12 | public static TimeDistribution Linear => new TimeDistribution("linear"); 13 | 14 | /// 15 | /// Data are spread at the same distance from each other 16 | /// 17 | public static TimeDistribution Series => new TimeDistribution("series"); 18 | 19 | 20 | private TimeDistribution(string stringRep) : base(stringRep) { } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/TimeMeasurement.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/time.html#time-units 5 | /// 6 | /// 7 | public sealed class TimeMeasurement : StringEnum 8 | { 9 | public static TimeMeasurement Millisecond => new TimeMeasurement("millisecond"); 10 | public static TimeMeasurement Second => new TimeMeasurement("second"); 11 | public static TimeMeasurement Minute => new TimeMeasurement("minute"); 12 | public static TimeMeasurement Hour => new TimeMeasurement("hour"); 13 | public static TimeMeasurement Day => new TimeMeasurement("day"); 14 | public static TimeMeasurement Week => new TimeMeasurement("week"); 15 | public static TimeMeasurement Month => new TimeMeasurement("month"); 16 | public static TimeMeasurement Quarter => new TimeMeasurement("quarter"); 17 | public static TimeMeasurement Year => new TimeMeasurement("year"); 18 | 19 | private TimeMeasurement(string stringRep) : base(stringRep) { } 20 | } 21 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Enums/TooltipPosition.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Enums 2 | { 3 | /// 4 | /// Specifies where the tooltip will be displayed. 5 | /// As per documentation here https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes 6 | /// 7 | public sealed class TooltipPosition : StringEnum 8 | { 9 | /// 10 | /// When is set, the tooltip will be placed at the average position of the items displayed in the tooltip. 11 | /// 12 | public static TooltipPosition Average => new TooltipPosition("average"); 13 | 14 | /// 15 | /// When is set, the tooltip will be placed at the position of the element closest to the event position. 16 | /// 17 | public static TooltipPosition Nearest => new TooltipPosition("nearest"); 18 | 19 | private TooltipPosition(string stringRep) : base(stringRep) { } 20 | } 21 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/JsonWriteOnlyConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common 5 | { 6 | internal abstract class JsonWriteOnlyConverter : JsonConverter 7 | { 8 | public override sealed bool CanRead => false; 9 | public override sealed bool CanWrite => true; 10 | 11 | public override sealed T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer) 12 | { 13 | throw new NotImplementedException("Don't use me to read JSON"); 14 | } 15 | 16 | public abstract override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Legends/OnClickHandler/ILegendClickHandler.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Legends.OnClickHandler 2 | { 3 | /// 4 | /// Specifies how clicking on Legend items is handled 5 | /// 6 | public interface ILegendClickHandler 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Legends/OnClickHandler/JsClickHandler.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Legends.OnClickHandler 2 | { 3 | /// 4 | /// Specified the namespace and name of a Javascript function that should be invoked when clicking Legend items 5 | /// 6 | public class JsClickHandler : ILegendClickHandler 7 | { 8 | /// 9 | /// The namespace and name of a Javascript function to be called when clicking on a Legend item. 10 | /// E.g. "SampleFunctions.HideOtherDatasetsFunc" 11 | /// Note 1: You must create this function in your JS file in wwwroot and reference it in _Host.cshtml 12 | /// Note 2: Make sure the function can handle the click sender and the click event args 13 | /// 14 | public string FullFunctionName { get; set; } 15 | 16 | /// 17 | /// Creates a new instance of 18 | /// 19 | /// The namespace and name of a Javascript function to be called when clicking on a Legend item. 20 | public JsClickHandler(string fullFunctionName) 21 | { 22 | FullFunctionName = fullFunctionName; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Legends/OnHover/ILegendOnHoverHandler.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Legends.OnHover 2 | { 3 | /// 4 | /// Specifies how hovering on Legend items is handled 5 | /// 6 | public interface ILegendHoverHandler 7 | { 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Legends/OnHover/JsHoverHandler.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Legends.OnHover 2 | { 3 | /// 4 | /// Specified the namespace and name of a Javascript function that should be invoked when hovering on Legend items 5 | /// 6 | public class JsHoverHandler : ILegendHoverHandler 7 | { 8 | /// 9 | /// The namespace and name of a Javascript function to be called when hovering the mouse cursor over a Legend item. 10 | /// E.g. "SampleFunctions.ItemHoverHandler" 11 | /// Note 1: You must create this function in your JS file in wwwroot and reference it in index.html 12 | /// Note 2: Make sure the function can handle the 'mousemove' event 13 | /// 14 | public string FullFunctionName { get; } 15 | 16 | /// 17 | /// Creates a new instance of 18 | /// 19 | /// The namespace and name of a Javascript function to be called when hovering on a Legend item. 20 | public JsHoverHandler(string fullFunctionName) 21 | { 22 | FullFunctionName = fullFunctionName; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/MajorTicks.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common 3 | { 4 | /// 5 | /// The major ticks sub-config of the tick-configuration (see ). 6 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/styling.html#major-tick-configuration 7 | /// 8 | public class MajorTicks : SubTicks 9 | { 10 | /// 11 | /// Gets or sets the value indicating whether these options are used to show major ticks. 12 | /// 13 | public bool Enabled { get; set; } = false; 14 | } 15 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/MinorTicks.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common 3 | { 4 | /// 5 | /// The minor ticks sub-config of the tick-configuration (see ). 6 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/styling.html#minor-tick-configuration 7 | /// 8 | public class MinorTicks : SubTicks 9 | { 10 | } 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Point.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common 4 | { 5 | public class Point 6 | { 7 | public Point() { } 8 | 9 | public Point(double x, double y) 10 | { 11 | this.X = x; 12 | this.Y = y; 13 | } 14 | 15 | [JsonProperty("x")] 16 | public double X { get; set; } 17 | 18 | [JsonProperty("y")] 19 | public double Y { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Properties/Animation.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Properties 2 | { 3 | /// 4 | /// Defines some animation configurations 5 | /// 6 | public class Animation 7 | { 8 | /// 9 | /// Defines the duration of the animation 10 | /// 11 | public long Duration { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Properties/ArcAnimation.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Properties 2 | { 3 | /// 4 | /// The animation-subconfig of the options for a radial chart. 5 | /// 6 | public class ArcAnimation 7 | { 8 | /// 9 | /// If true, the chart will animate in with a rotation animation. 10 | /// 11 | public bool AnimateRotate { get; set; } = true; 12 | 13 | /// 14 | /// If true, will animate scaling the chart from the center outwards. 15 | /// 16 | public bool AnimateScale { get; set; } = false; 17 | } 18 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Properties/OptionsTitle.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.Common.Properties 2 | { 3 | /// 4 | /// Represents the title of a chart 5 | /// 6 | public class OptionsTitle 7 | { 8 | /// 9 | /// Determines if the title should be displayed or not 10 | /// 11 | public bool Display { get; set; } 12 | 13 | /// 14 | /// The actual title to display 15 | /// 16 | public string Text { get; set; } 17 | } 18 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/SubTicks.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.Util; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common 5 | { 6 | /// 7 | /// The base class for minor and major ticks (see and see ). 8 | /// 9 | public abstract class SubTicks 10 | { 11 | /// 12 | /// Gets or sets the font color for a tick's labels. 13 | /// See for working with colors. 14 | /// 15 | public string FontColor { get; set; } 16 | 17 | /// 18 | /// Gets or sets the font family for a tick's label. 19 | /// 20 | public string FontFamily { get; set; } 21 | 22 | /// 23 | /// Gets or sets the font size for a tick's label. 24 | /// 25 | public int FontSize { get; set; } = 12; 26 | 27 | /// 28 | /// Gets or sets the font style for a tick's label. 29 | /// 30 | public FontStyle FontStyle { get; set; } 31 | 32 | /// 33 | /// Gets or sets the height of an individual line of text. 34 | /// As per documentation here https://developer.mozilla.org/en-US/docs/Web/CSS/line-height 35 | /// 36 | public double LineHeight { get; set; } = 1.2; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Utils/PointUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common.Utils 4 | { 5 | public class PointUtil 6 | { 7 | private static readonly Random rand = new Random(); 8 | 9 | public static Point NewRandPoint(double minX, double maxX, double minY, double maxY) 10 | { 11 | if (minX > maxX) 12 | { 13 | throw new ArgumentOutOfRangeException(nameof(minX), $"{nameof(minX)} must be less than {nameof(maxX)}"); 14 | } 15 | 16 | if (minY > maxY) 17 | { 18 | throw new ArgumentOutOfRangeException(nameof(minY), $"{nameof(minY)} must be less than {nameof(maxY)}"); 19 | } 20 | 21 | var xRange = Math.Abs(maxX - minX); 22 | var yRange = Math.Abs(maxY - minY); 23 | 24 | var randX = minX + (rand.NextDouble() * xRange); 25 | var randY = minY + (rand.NextDouble() * yRange); 26 | 27 | return new Point(randX, randY); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/ByteWrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | [JsonConverter(typeof(JsonValueWrapperConverter))] 7 | public sealed class ByteWrapper : ValueWrapper 8 | { 9 | public ByteWrapper(Byte value) : base(value) { } 10 | 11 | public static implicit operator Byte(ByteWrapper value) => value.Value; 12 | public static implicit operator ByteWrapper(Byte value) => new ByteWrapper(value); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/DoubleWrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | [JsonConverter(typeof(JsonValueWrapperConverter))] 7 | public sealed class DoubleWrapper : ValueWrapper 8 | { 9 | public DoubleWrapper(Double value) : base(value) { } 10 | 11 | public static implicit operator Double(DoubleWrapper value) => value.Value; 12 | public static implicit operator DoubleWrapper(Double value) => new DoubleWrapper(value); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/FloatWrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 4 | { 5 | [JsonConverter(typeof(JsonValueWrapperConverter))] 6 | public sealed class FloatWrapper : ValueWrapper 7 | { 8 | public FloatWrapper(float value) : base(value) { } 9 | 10 | public static implicit operator float(FloatWrapper value) => value.Value; 11 | public static implicit operator FloatWrapper(float value) => new FloatWrapper(value); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/Int16Wrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | [JsonConverter(typeof(JsonValueWrapperConverter))] 7 | public sealed class Int16Wrapper : ValueWrapper 8 | { 9 | public Int16Wrapper(Int16 value) : base(value) { } 10 | 11 | public static implicit operator Int16(Int16Wrapper value) => value.Value; 12 | public static implicit operator Int16Wrapper(Int16 value) => new Int16Wrapper(value); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/Int32Wrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | [JsonConverter(typeof(JsonValueWrapperConverter))] 7 | public sealed class Int32Wrapper : ValueWrapper 8 | { 9 | public Int32Wrapper(Int32 value) : base(value) { } 10 | 11 | public static implicit operator Int32(Int32Wrapper value) => value.Value; 12 | public static implicit operator Int32Wrapper(Int32 value) => new Int32Wrapper(value); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/Int64Wrapper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | [JsonConverter(typeof(JsonValueWrapperConverter))] 7 | public sealed class Int64Wrapper : ValueWrapper 8 | { 9 | public Int64Wrapper(Int64 value) : base(value) { } 10 | 11 | public static implicit operator Int64(Int64Wrapper value) => value.Value; 12 | public static implicit operator Int64Wrapper(Int64 value) => new Int64Wrapper(value); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/JsonValueWrapperConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 4 | { 5 | class JsonValueWrapperConverter : JsonWriteOnlyConverter 6 | where TData : struct 7 | where TWrapper : ValueWrapper 8 | { 9 | //public override TWrapper ReadJson(JsonReader reader, Type objectType, TWrapper existingValue, bool hasExistingValue, JsonSerializer serializer) 10 | //{ 11 | // throw new NotImplementedException(); // don't know if this is used ever and if it's implemented correctly 12 | 13 | // JToken token = JToken.Load(reader); 14 | // TData val = token.ToObject(); 15 | // return (TWrapper)val; 16 | //} 17 | 18 | public override void WriteJson(JsonWriter writer, TWrapper value, JsonSerializer serializer) 19 | { 20 | writer.WriteValue(value.Value); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/ValueWrapper.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 3 | { 4 | public abstract class ValueWrapper where TData : struct 5 | { 6 | internal TData Value { get; } 7 | 8 | internal ValueWrapper(TData value) => Value = value; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/Common/Wrappers/WrapperExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace ChartJs.Blazor.ChartJS.Common.Wrappers 5 | { 6 | public static class WrapperExtensions 7 | { 8 | public static IEnumerable UnWrap(this IEnumerable> wrappers) where T : struct 9 | { 10 | return wrappers.Select(v => v.Value); 11 | } 12 | 13 | public static IEnumerable Wrap(this IEnumerable values) 14 | { 15 | return values.Select(v => (ByteWrapper)v); 16 | } 17 | 18 | public static IEnumerable Wrap(this IEnumerable values) 19 | { 20 | return values.Select(v => (DoubleWrapper)v); 21 | } 22 | 23 | public static IEnumerable Wrap(this IEnumerable values) 24 | { 25 | return values.Select(v => (FloatWrapper)v); 26 | } 27 | 28 | public static IEnumerable Wrap(this IEnumerable values) 29 | { 30 | return values.Select(v => (Int16Wrapper)v); 31 | } 32 | 33 | public static IEnumerable Wrap(this IEnumerable values) 34 | { 35 | return values.Select(v => (Int32Wrapper)v); 36 | } 37 | 38 | public static IEnumerable Wrap(this IEnumerable values) 39 | { 40 | return values.Select(v => (Int64Wrapper)v); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/CategoryAxis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes 5 | { 6 | /// 7 | /// This axis is to be used when you want to display values for an axis. 8 | /// This axis has to be used when using/defining , and/or . 9 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/category.html 10 | /// 11 | public class CategoryAxis : CartesianAxis 12 | { 13 | /// 14 | /// The type of axis this instance represents. 15 | /// For js-interop/serialization purposes so chart.js knows what axis to use. 16 | /// 17 | public override AxisType Type => AxisType.Category; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/LinearCartesianAxis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes 5 | { 6 | /// 7 | /// The linear scale is use to chart numerical data. It can be placed on either the x or y axis. 8 | /// As the name suggests, linear interpolation is used to determine where a value lies on the axis. 9 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/linear.html 10 | /// 11 | public class LinearCartesianAxis : CartesianAxis 12 | { 13 | /// 14 | /// The type of axis this instance represents. 15 | /// For js-interop/serialization purposes so chart.js knows what axis to use. 16 | /// 17 | public override AxisType Type => AxisType.Linear; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/LogarithmicAxis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes 5 | { 6 | /// 7 | /// The logarithmic scale is use to chart numerical data. It can be placed on either the x or y axis. 8 | /// As the name suggests, logarithmic interpolation is used to determine where a value lies on the axis. 9 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/logarithmic.html 10 | /// 11 | public class LogarithmicAxis : CartesianAxis 12 | { 13 | /// 14 | /// The type of axis this instance represents. 15 | /// For js-interop/serialization purposes so chart.js knows what axis to use. 16 | /// 17 | public override AxisType Type => AxisType.Logarithmic; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/Ticks/CategoryTicks.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks 4 | { 5 | public class CategoryTicks : CartesianTicks 6 | { 7 | /// 8 | /// An array of labels to display. 9 | /// 10 | public List Labels { get; set; } 11 | 12 | /// 13 | /// The minimum item to display. The item has to be present in . 14 | /// Read more https://www.chartjs.org/docs/latest/axes/cartesian/category.html#min-max-configuration 15 | /// 16 | public string Min { get; set; } 17 | 18 | /// 19 | /// The maximum item to display. The item has to be present in . 20 | /// Read more https://www.chartjs.org/docs/latest/axes/cartesian/category.html#min-max-configuration 21 | /// 22 | public string Max { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/Ticks/LogarithmicTicks.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks 3 | { 4 | public class LogarithmicTicks : CartesianTicks 5 | { 6 | /// 7 | /// User defined minimum number for the scale, overrides minimum value from data. 8 | /// 9 | public int Min { get; set; } 10 | 11 | /// 12 | /// User defined maximum number for the scale, overrides maximum value from data. 13 | /// 14 | public int Max { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/Ticks/TimeTicks.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | 3 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks 4 | { 5 | public class TimeTicks : CartesianTicks 6 | { 7 | /// 8 | /// How ticks are generated. 9 | /// 10 | public TickSource Source { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Axes/TimeAxis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart.Axes 5 | { 6 | /// 7 | /// The time scale is used to display times and dates. 8 | /// When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale. 9 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/cartesian/time.html 10 | /// 11 | public class TimeAxis : CartesianAxis 12 | { 13 | /// 14 | /// The type of axis this instance represents. 15 | /// For js-interop/serialization purposes so chart.js knows what axis to use. 16 | /// 17 | public override AxisType Type => AxisType.Time; 18 | 19 | /// 20 | /// The distribution property controls the data distribution along the scale 21 | /// 22 | public TimeDistribution Distribution { get; set; } 23 | 24 | /// 25 | /// The bounds property controls the scale boundary strategy (bypassed by min/max time options). 26 | /// 27 | public ScaleBound Bounds { get; set; } 28 | 29 | /// 30 | /// Configuration for time related stuff 31 | /// 32 | public TimeOptions Time { get; set; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/JsonMomentConverter.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using Newtonsoft.Json; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart 5 | { 6 | internal class JsonMomentConverter : JsonWriteOnlyConverter 7 | { 8 | public override void WriteJson(JsonWriter writer, Moment moment, JsonSerializer serializer) 9 | { 10 | writer.WriteValue(moment.ToString()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/LineConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart 5 | { 6 | /// 7 | /// Config for a 8 | /// 9 | public class LineConfig : ConfigBase 10 | { 11 | /// 12 | /// Creates a new instance of 13 | /// 14 | public LineConfig() : base(ChartType.Line) { } 15 | } 16 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/LineOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Properties; 3 | using ChartJs.Blazor.ChartJS.LineChart.Axes; 4 | 5 | namespace ChartJs.Blazor.ChartJS.LineChart 6 | { 7 | /// 8 | /// The options-subconfig of a 9 | /// 10 | public class LineOptions : BaseConfigOptions 11 | { 12 | /// 13 | /// General animation time 14 | /// 15 | public Animation Animation { get; set; } 16 | 17 | /// 18 | /// Hover options for hovering over an item 19 | /// 20 | public LineOptionsHover Hover { get; set; } 21 | 22 | /// 23 | /// The scales for this chart. You can use any for x and y. 24 | /// 25 | public Scales Scales { get; set; } 26 | 27 | /// 28 | /// If false, the lines between points are not drawn. 29 | /// 30 | public bool ShowLines { get; set; } = true; 31 | 32 | /// 33 | /// If false, NaN data causes a break in the line. 34 | /// 35 | public bool SpanGaps { get; set; } = true; 36 | } 37 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/LineOptionsHover.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Properties; 2 | 3 | namespace ChartJs.Blazor.ChartJS.LineChart 4 | { 5 | // TODO: check if this would apply to more charts (https://www.chartjs.org/docs/latest/general/interactions) 6 | // and if so rename and reuse this 7 | /// 8 | /// The hover-subconfig of 9 | /// 10 | public class LineOptionsHover : Tooltips 11 | { 12 | /// 13 | /// Duration in milliseconds it takes to animate hover style changes. 14 | /// 15 | public long AnimationDuration { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/ScaleLabel.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.Util; 2 | 3 | namespace ChartJs.Blazor.ChartJS.LineChart 4 | { 5 | /// 6 | /// Defines options for how to display an axis title. 7 | /// 8 | public class ScaleLabel 9 | { 10 | /// 11 | /// Creates a new instance of 12 | /// 13 | /// The initial value for 14 | public ScaleLabel(string labelString = null) 15 | { 16 | LabelString = labelString; 17 | } 18 | 19 | /// 20 | /// If true, display the axis title. 21 | /// 22 | public bool Display { get; set; } = true; 23 | 24 | /// 25 | /// Text for the title (i.e. "# of clicks") 26 | /// 27 | public string LabelString { get; set; } 28 | 29 | /// 30 | /// The font color of the label 31 | /// See for working with colors. 32 | /// 33 | public string FontColor { get; set; } 34 | 35 | /// 36 | /// Font size for scale title. 37 | /// 38 | public int? FontSize { get; set; } 39 | } 40 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/Scales.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.LineChart.Axes; 2 | using System.Collections.Generic; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart 5 | { 6 | /// 7 | /// Defines the scales for cartesian charts by holding the x and y axes. 8 | /// 9 | public class Scales 10 | { 11 | #pragma warning disable CS1591, IDE1006 // Missing XML comment for publicly visible type or member 12 | public List xAxes { get; set; } 13 | public List yAxes { get; set; } 14 | #pragma warning restore CS1591, IDE1006 // Missing XML comment for publicly visible type or member 15 | } 16 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/TimeDisplayFormats.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using System.Collections.Generic; 3 | 4 | namespace ChartJs.Blazor.ChartJS.LineChart 5 | { 6 | /// 7 | /// This is a helper class containing pre-made display formats to use in for certain locales. 8 | /// Those s that are not defined, will use the default format from https://www.chartjs.org/docs/latest/axes/cartesian/time.html#display-formats 9 | /// 10 | public static class TimeDisplayFormats 11 | { 12 | 13 | public static Dictionary Default => new Dictionary 14 | { 15 | { TimeMeasurement.Millisecond, "HH:mm:ss.SSS" }, 16 | { TimeMeasurement.Second, "HH:mm:ss" }, 17 | { TimeMeasurement.Minute, "HH:mm" }, 18 | { TimeMeasurement.Hour, "HH:00" }, 19 | { TimeMeasurement.Day, "DD/MM/YYYY hh:mm" } 20 | }; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/LineChart/TimeTuple.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace ChartJs.Blazor.ChartJS.LineChart 4 | { 5 | /// 6 | /// Represents a point on a graph where the X-Value () is represented by a 7 | /// Should be used together with a 8 | /// Reference Type so it can be used in the covariant 9 | /// 10 | /// 11 | public class TimeTuple 12 | { 13 | /// 14 | /// Creates a new instance of 15 | /// 16 | /// The instance to represent the x-value. 17 | /// The value of type which represents the y-value. 18 | public TimeTuple(Moment time, TData yValue) 19 | { 20 | Time = time; 21 | YValue = yValue; 22 | } 23 | 24 | /// 25 | /// The time-/x-value for this . 26 | /// 27 | [JsonProperty("t")] 28 | public Moment Time { get; set; } 29 | 30 | /// 31 | /// The y-value for this . 32 | /// 33 | [JsonProperty("y")] 34 | public TData YValue { get; set; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/MixedChart/IMixableDataset.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common.Enums; 2 | using System.Collections.Generic; 3 | 4 | namespace ChartJs.Blazor.ChartJS.MixedChart 5 | { 6 | /// 7 | /// Interface for a covariant dataset that can be mixed with other datasets. 8 | /// 9 | /// Defines the type of data in this dataset. Use Wrappers from for value types. 10 | public interface IMixableDataset 11 | { 12 | /// 13 | /// The type of chart this dataset is for. 14 | /// 15 | string Type { get; } 16 | 17 | /// 18 | /// The data contained in this dataset (readonly because covariant). 19 | /// 20 | IReadOnlyCollection Data { get; } 21 | } 22 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/MixedChart/MixedConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.MixedChart 5 | { 6 | public class MixedConfig : ConfigBase> 7 | { 8 | public MixedConfig() : base(ChartType.Bar) // This is not a mistake 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/MixedChart/MixedData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.MixedChart 4 | { 5 | public class MixedData 6 | { 7 | public List Labels { get; set; } = new List(); 8 | 9 | public List> Datasets { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/MixedChart/MixedOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | 3 | namespace ChartJs.Blazor.ChartJS.MixedChart 4 | { 5 | public class MixedOptions : BaseConfigOptions 6 | { 7 | } 8 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/MomentJsInterop.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | using System.Threading.Tasks; 3 | 4 | namespace ChartJs.Blazor.ChartJS 5 | { 6 | public static class MomentJsInterop 7 | { 8 | public static ValueTask GetAvailableLocales(this IJSRuntime jsRuntime) 9 | { 10 | return jsRuntime.InvokeAsync("getAvailableMomentLocales"); 11 | } 12 | 13 | public static ValueTask ChangeLocale(this IJSRuntime jsRuntime, string locale) 14 | { 15 | try 16 | { 17 | return jsRuntime.InvokeAsync("changeLocale", locale); 18 | } 19 | catch 20 | { 21 | return new ValueTask(false); 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PieChart/PieConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.PieChart 5 | { 6 | /// 7 | /// Config for a . 8 | /// 9 | public class PieConfig : ConfigBase 10 | { 11 | /// 12 | /// Creates a new instance of . 13 | /// 14 | public PieConfig() : base(ChartType.Pie) 15 | { 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PieChart/PieData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.PieChart 4 | { 5 | /// 6 | /// The data-subconfig of a . 7 | /// 8 | public class PieData 9 | { 10 | /// 11 | /// Gets the labels the chart will use. 12 | /// 13 | public List Labels { get; } = new List(); 14 | 15 | /// 16 | /// Gets the datasets displayed in this chart. 17 | /// 18 | public List Datasets { get; } = new List(); 19 | } 20 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PieChart/PieOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ChartJs.Blazor.ChartJS.Common; 3 | using ChartJs.Blazor.ChartJS.Common.Properties; 4 | 5 | namespace ChartJs.Blazor.ChartJS.PieChart 6 | { 7 | /// 8 | /// The options-subconfig of a . 9 | /// 10 | public class PieOptions : BaseConfigOptions 11 | { 12 | /// 13 | /// Creates a new instance of 14 | /// 15 | /// If true, the start-value for will be 50 (default for Doughnut) instead of 0 (default for Pie). 16 | public PieOptions(bool doughnutCutout = false) 17 | { 18 | if (doughnutCutout) CutoutPercentage = 50; 19 | } 20 | 21 | /// 22 | /// Gets or sets the percentage of the chart that is cut out of the middle. 23 | /// Default for Pie is 0, Default for Doughnut is 50. See constructor-parameter. 24 | /// 25 | public int CutoutPercentage { get; set; } = 0; 26 | 27 | /// 28 | /// Gets or sets the animation-configuration for this chart. 29 | /// 30 | public ArcAnimation Animation { get; set; } 31 | 32 | /// 33 | /// Gets or sets the starting angle to draw arcs from. 34 | /// 35 | public double Rotation { get; set; } = -0.5 * Math.PI; 36 | 37 | /// 38 | /// Gets or sets the sweep to allow arcs to cover. 39 | /// 40 | public double Circumference { get; set; } = 2 * Math.PI; 41 | } 42 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PolarAreaChart/Axis/LinearRadialAxis.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | 3 | namespace ChartJs.Blazor.ChartJS.PolarAreaChart.Axis 4 | { 5 | /// 6 | /// A linear radial axis. 7 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/radial/linear.html. 8 | /// 9 | public class LinearRadialAxis 10 | { 11 | /// 12 | /// Gets or sets the angle lines configuration. 13 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/radial/linear.html#angle-line-options 14 | /// 15 | public AngleLines AngleLines { get; set; } 16 | 17 | /// 18 | /// Gets or sets the grid lines configuration. 19 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration 20 | /// 21 | public GridLines GridLines { get; set; } 22 | 23 | /// 24 | /// Gets or sets the point labels configuration. 25 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/radial/linear.html#point-label-options 26 | /// 27 | public PointLabels PointLabels { get; set; } 28 | 29 | /// 30 | /// Gets or sets the ticks configuration. 31 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/radial/linear.html#tick-options 32 | /// 33 | public LinearRadialTicks Ticks { get; set; } 34 | } 35 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PolarAreaChart/Axis/PointLabels.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | using ChartJs.Blazor.Util; 4 | 5 | namespace ChartJs.Blazor.ChartJS.PolarAreaChart.Axis 6 | { 7 | /// 8 | /// The point labels sub-config of the linear-radial-axis-configuration (see ). 9 | /// As per documentation here https://www.chartjs.org/docs/latest/axes/radial/linear.html#point-label-options 10 | /// 11 | public class PointLabels 12 | { 13 | /// 14 | /// Gets or sets the font color for a point label. 15 | /// See for working with colors. 16 | /// 17 | public IndexableOption FontColor { get; set; } 18 | 19 | /// 20 | /// Gets or sets the font size in pixels. 21 | /// 22 | public int FontSize { get; set; } = 10; 23 | 24 | /// 25 | /// Gets or sets the font style to use when rendering a point label. 26 | /// 27 | public FontStyle FontStyle { get; set; } 28 | 29 | /// 30 | /// Gets or sets the height of an individual line of text. 31 | /// As per documentation here https://developer.mozilla.org/en-US/docs/Web/CSS/line-height 32 | /// 33 | public double LineHeight { get; set; } = 1.2; 34 | } 35 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PolarAreaChart/PolarAreaConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.PolarAreaChart 5 | { 6 | /// 7 | /// Config for a 8 | /// 9 | public class PolarAreaConfig : ConfigBase 10 | { 11 | /// 12 | /// Creates a new instance of 13 | /// 14 | public PolarAreaConfig() : base(ChartType.PolarArea) 15 | { 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PolarAreaChart/PolarAreaData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.PolarAreaChart 4 | { 5 | /// 6 | /// The data-subconfig of a . 7 | /// 8 | public class PolarAreaData 9 | { 10 | /// 11 | /// Gets the labels the chart will use. 12 | /// 13 | public List Labels { get; } = new List(); 14 | 15 | /// 16 | /// Gets the datasets displayed in this chart. 17 | /// 18 | public List Datasets { get; } = new List(); 19 | } 20 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/PolarAreaChart/PolarAreaOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ChartJs.Blazor.ChartJS.Common; 3 | using ChartJs.Blazor.ChartJS.Common.Properties; 4 | using ChartJs.Blazor.ChartJS.PolarAreaChart.Axis; 5 | 6 | namespace ChartJs.Blazor.ChartJS.PolarAreaChart 7 | { 8 | /// 9 | /// The options-subconfig of a . 10 | /// 11 | public class PolarAreaOptions : BaseConfigOptions 12 | { 13 | /// 14 | /// Gets or sets the starting angle to draw arcs for the first item in a dataset. 15 | /// 16 | public double StartAngle { get; set; } = -0.5 * Math.PI; 17 | 18 | /// 19 | /// Gets or sets the animation-configuration for this chart. 20 | /// 21 | public ArcAnimation Animation { get; set; } 22 | 23 | /// 24 | /// The scale (axis) for this chart. 25 | /// 26 | public LinearRadialAxis Scale { get; set; } 27 | } 28 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/RadarChart/RadarConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.RadarChart 5 | { 6 | public class RadarConfig : ConfigBase 7 | { 8 | public RadarConfig() : base(ChartType.Radar) { } 9 | } 10 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/RadarChart/RadarData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.RadarChart 4 | { 5 | public class RadarData 6 | { 7 | public List Labels { get; set; } 8 | 9 | public List Datasets { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/RadarChart/RadarOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | 3 | namespace ChartJs.Blazor.ChartJS.RadarChart 4 | { 5 | public class RadarOptions : BaseConfigOptions 6 | { 7 | public Scale Scale { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/RadarChart/Scale.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.LineChart.Axes.Ticks; 2 | 3 | namespace ChartJs.Blazor.ChartJS.RadarChart 4 | { 5 | public class Scale 6 | { 7 | public CartesianTicks Ticks { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/GridLineSettings.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.ScatterChart 2 | { 3 | public class GridLineSettings 4 | { 5 | public bool DrawOnChartArea { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/ScatterAxis.cs: -------------------------------------------------------------------------------- 1 | namespace ChartJs.Blazor.ChartJS.ScatterChart 2 | { 3 | public class ScatterAxis 4 | { 5 | public bool Display { get; set; } 6 | public string Text { get; set; } 7 | public string Position { get; set; } 8 | 9 | public string Type { get; set; } = "linear"; 10 | 11 | public string Id { get; set; } 12 | 13 | public GridLineSettings GridLines { get; set; } 14 | } 15 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/ScatterConfig.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.ScatterChart 5 | { 6 | public class ScatterConfig : ConfigBase 7 | { 8 | public ScatterConfig() : base(ChartType.Scatter) { } 9 | } 10 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/ScatterData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.ScatterChart 4 | { 5 | public class ScatterData 6 | { 7 | public List Datasets { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/ScatterOptions.cs: -------------------------------------------------------------------------------- 1 | using ChartJs.Blazor.ChartJS.Common; 2 | using ChartJs.Blazor.ChartJS.Common.Enums; 3 | 4 | namespace ChartJs.Blazor.ChartJS.ScatterChart 5 | { 6 | public class ScatterOptions : BaseConfigOptions 7 | { 8 | public InteractionMode HoverMode { get; set; } = InteractionMode.Nearest; 9 | 10 | public bool Intersect { get; set; } 11 | 12 | public ScatterScales Scales { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/ChartJS/ScatterChart/ScatterScales.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace ChartJs.Blazor.ChartJS.ScatterChart 4 | { 5 | public class ScatterScales 6 | { 7 | public List XAxes { get; set; } 8 | public List YAxes { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /Jtc.Optimization.ChartJs/Jtc.Optimization.ChartJs.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Jtc.Optimization.IntegrationTests/Features/LeanOptimizationExecutable.feature: -------------------------------------------------------------------------------- 1 | Feature: LeanOptimizationExecutable 2 | 3 | Scenario Outline: Optimize parameters 4 | Given I have an optimization.config 5 | And I have set maxThreads and generations to 6 | And I have set useSharedAppDomain to 7 | And the algorithm 8 | And I have saved the test config 9 | When I run the Launcher executable 10 | Then the Sharpe Ratio on optimizer.txt should be 11 | #And Total Trades should be 12 | #And last run should produce different result 13 | #And multiple threads should execute in parallel 14 | 15 | Examples: 16 | | maxThreads | useSharedAppDomain | isPython | sharpRatio | totalTrades | 17 | | 1 | true | false | 52.42 | 7 | 18 | -------------------------------------------------------------------------------- /Jtc.Optimization.IntegrationTests/Jtc.Optimization.IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | all 11 | runtime; build; native; contentfiles; analyzers; buildtransitive 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | ..\..\Lean\Configuration\bin\Debug\QuantConnect.Configuration.dll 26 | 27 | 28 | 29 | 30 | 31 | PreserveNewest 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Jtc.Optimization.Launcher.Legacy/Program.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.LeanOptimizer; 2 | using NLog; 3 | using System; 4 | 5 | namespace Jtc.Optimization.Launcher.Legacy 6 | { 7 | 8 | public class Program 9 | { 10 | 11 | public static void Main(string[] args) 12 | { 13 | try 14 | { 15 | LogManager.Configuration.RemoveRuleByName("trace"); 16 | LogManager.Configuration.RemoveTarget("trace"); 17 | new OptimizerInitializer().Initialize(args); 18 | } 19 | catch (Exception ex) 20 | { 21 | LogProvider.ErrorLogger.Error(ex); 22 | throw new Exception("Unhandled Exception", ex); 23 | } 24 | Console.ReadKey(); 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Jtc.Optimization.Launcher.Legacy/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Jtc.Optimization.Launcher.Legacy")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Jtc.Optimization.Launcher.Legacy")] 13 | [assembly: AssemblyCopyright("Copyright © 2019")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("b6c15b87-93ce-4dc2-a44e-271d0c8406e9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Base/IRunner.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Jtc.Optimization.LeanOptimizer.Base 6 | { 7 | public interface IRunner 8 | { 9 | Dictionary Run(Dictionary items, IOptimizerConfiguration config); 10 | } 11 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Base/Jtc.Optimization.LeanOptimizer.Base.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | AnyCPU;x64 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Base/MultipleContextIsolator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.LeanOptimizer.Base 8 | { 9 | public class MultipleContextIsolator : BaseContextIsolator 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Base/ResultMediator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Jtc.Optimization.LeanOptimizer.Base 5 | { 6 | 7 | //todo: No longer any reason to pass through app domain? Could just be a singleton. 8 | public class ResultMediator 9 | { 10 | 11 | public static Dictionary> GetResults(AppDomain ad) 12 | { 13 | return GetData>>(ad, "Results"); 14 | } 15 | 16 | public static T GetData(AppDomain ad, string key) 17 | { 18 | return (T)ad.GetData(key); 19 | } 20 | 21 | public static void SetResults(AppDomain ad, object item) 22 | { 23 | SetData(ad, "Results", item); 24 | } 25 | 26 | public static void SetData(AppDomain ad, string key, object item) 27 | { 28 | ad.SetData(key, item); 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Example/Jtc.Optimization.LeanOptimizer.Example.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | AnyCPU;x64 6 | true 7 | 8 | 9 | 10 | 11 | ..\..\Lean\Algorithm\bin\Debug\QuantConnect.Algorithm.dll 12 | 13 | 14 | ..\..\Lean\Common\bin\Debug\QuantConnect.Common.dll 15 | 16 | 17 | ..\..\Lean\Configuration\bin\Debug\QuantConnect.Configuration.dll 18 | 19 | 20 | ..\..\Lean\Indicators\bin\Debug\QuantConnect.Indicators.dll 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Launcher/Jtc.Optimization.LeanOptimizer.Launcher.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Launcher/Program.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.LeanOptimizer; 2 | using NLog; 3 | using System; 4 | 5 | namespace Jtc.Optimization.Launcher.Legacy 6 | { 7 | 8 | public class Program 9 | { 10 | 11 | public static void Main(string[] args) 12 | { 13 | try 14 | { 15 | LogManager.Configuration.RemoveRuleByName("trace"); 16 | LogManager.Configuration.RemoveTarget("trace"); 17 | 18 | new OptimizerLauncher().Launch(args); 19 | } 20 | catch (Exception ex) 21 | { 22 | LogProvider.ErrorLogger.Error(ex); 23 | throw new Exception("Unhandled Exception", ex); 24 | } 25 | LogManager.Shutdown(); 26 | Console.ReadKey(); 27 | 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Legacy/LegacyAppDomainManager.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.LeanOptimizer.Base; 2 | using Jtc.Optimization.Objects.Interfaces; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Reflection; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Jtc.Optimization.LeanOptimizer.Legacy 12 | { 13 | 14 | public class LegacyAppDomainManager : BaseAppDomainManager 15 | { 16 | 17 | AppDomainSetup _setup; 18 | 19 | public LegacyAppDomainManager() : base() 20 | { 21 | CreateAppDomainSetup(); 22 | } 23 | 24 | private void CreateAppDomainSetup() 25 | { 26 | _setup = new AppDomainSetup(); 27 | _setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; 28 | _setup.DisallowBindingRedirects = false; 29 | _setup.DisallowCodeDownload = true; 30 | _setup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; 31 | } 32 | 33 | protected override IRunner CreateRunnerInAppDomain(ref AppDomain appDomain) 34 | { 35 | var name = Guid.NewGuid().ToString("x"); 36 | appDomain = AppDomain.CreateDomain(name, null, _setup); 37 | 38 | var rc = (IRunner)appDomain.CreateInstanceAndUnwrap("Jtc.Optimization.LeanOptimizer", "Jtc.Optimization.LeanOptimizer.Runner"); 39 | 40 | return rc; 41 | } 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Legacy/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Jtc.Optimization.LeanOptimizer.Legacy")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Jtc.Optimization.LeanOptimizer.Legacy")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a028e36a-18ad-4d7a-85cf-0ca19450a235")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Legacy/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/Fitness/DeflatedSharpeRatioFitnessTest.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using Moq; 3 | using NUnit.Framework; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Jtc.Optimization.LeanOptimizer.Tests 11 | { 12 | 13 | [TestFixture] 14 | public class DeflatedSharpeRatioFitnessTest 15 | { 16 | 17 | [Test] 18 | public void CalculateExpectedMaximumTest() 19 | { 20 | var unit = new Wrapper(null); 21 | unit.Initialize(); 22 | var actual = unit.CalculateExpectedMaximum(); 23 | 24 | Assert.AreEqual(0.1132, actual, 0.0002); 25 | } 26 | 27 | [Test] 28 | public void CalculateDeflatedSharpeRatioTest() 29 | { 30 | var unit = new Wrapper(null); 31 | unit.Initialize(); 32 | var actual = unit.CalculateDeflatedSharpeRatio(0.1132); 33 | 34 | Assert.AreEqual(0.9004, actual, 0.0002); 35 | } 36 | 37 | private class Wrapper : DeflatedSharpeRatioFitness 38 | { 39 | 40 | public Wrapper(IOptimizerConfiguration config) : base(config, null) 41 | { 42 | } 43 | 44 | public override void Initialize() 45 | { 46 | N = 100; 47 | V = 2; 48 | T = 1250; 49 | Skewness = -3; 50 | Kurtosis = 10; 51 | CurrentSharpeRatio = 2.5; 52 | } 53 | 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/Fitness/DualPeriodSharpeFitnessTests.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using Moq; 3 | using NUnit.Framework; 4 | 5 | namespace Jtc.Optimization.LeanOptimizer.Tests 6 | { 7 | [TestFixture] 8 | public class DualPeriodSharpeFitnessTests 9 | { 10 | private MockRepository mockRepository; 11 | 12 | private Mock mockOptimizerConfiguration; 13 | private Mock mockFitnessFilter; 14 | 15 | [SetUp] 16 | public void SetUp() 17 | { 18 | mockRepository = new MockRepository(MockBehavior.Strict); 19 | 20 | mockOptimizerConfiguration = this.mockRepository.Create(); 21 | mockFitnessFilter = this.mockRepository.Create(); 22 | } 23 | 24 | [TearDown] 25 | public void TearDown() 26 | { 27 | this.mockRepository.VerifyAll(); 28 | } 29 | 30 | [Test] 31 | public void TestMethod1() 32 | { 33 | //todo: 34 | DualPeriodSharpeFitness unit = this.CreateDualPeriodSharpeFitness(); 35 | 36 | 37 | } 38 | 39 | private DualPeriodSharpeFitness CreateDualPeriodSharpeFitness() 40 | { 41 | return new DualPeriodSharpeFitness( 42 | this.mockOptimizerConfiguration.Object, 43 | this.mockFitnessFilter.Object); 44 | } 45 | 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/Fitness/WeightedMetricCostTest.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using System; 3 | 4 | namespace Jtc.Optimization.LeanOptimizer.Tests.Fitness 5 | { 6 | public class WeightedMetricCostTest 7 | { 8 | 9 | double[][] GetData(int index) 10 | { 11 | switch (index) 12 | { 13 | case 1: 14 | return new double[][] { new[] { 10.0, 0.1 }, new[] { 10.0, 0.1 } }; 15 | case 2: 16 | return new double[][] { new[] { 10, 0.05 }, new[] { 5, 0.1 } }; 17 | case 3: 18 | return new double[][] { new[] { 1.1, 1.0 }, new[] { 1.0, 1.1 } }; 19 | case 4: 20 | return new double[][] { new[] { 10000, 0.01 }, new[] { 0.01, 10000 } }; 21 | } 22 | 23 | throw new ArgumentException(); 24 | 25 | } 26 | 27 | [TestCase(new[] { 1.0, 1.0 }, 1, 1)] 28 | [TestCase(new[] { 1.0, 1.0 }, 2, -0.26)] 29 | [TestCase(new[] { 1.0, 1.0 }, 3, 0.95)] 30 | [TestCase(new[] { 1.0, 0 }, 1, 0.5)] 31 | [TestCase(new[] { 1.0, 0 }, 3, 0.45)] 32 | [TestCase(new[] { 4.1, 4.1 }, 1, 4)] 33 | [TestCase(new[] { -4.1, -4.1 }, 1, -4)] 34 | [TestCase(new[] { 1.0, 1.0 }, 4, -3)] 35 | public void CalculateTest(double[] sharpeRatio, int dataIndex, double expected) 36 | { 37 | var data = GetData(dataIndex); 38 | 39 | var actual = WeightedMetricCost.Calculate(sharpeRatio, data); 40 | 41 | Assert.AreEqual(expected, actual, 0.01); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/GeneConverterTests.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects; 2 | using Newtonsoft.Json; 3 | using Newtonsoft.Json.Serialization; 4 | using NUnit.Framework; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Jtc.Optimization.LeanOptimizer.Tests 12 | { 13 | [TestFixture()] 14 | public class GeneConverterTests 15 | { 16 | [Test()] 17 | public void ReadWriteJsonTest() 18 | { 19 | string expected = System.IO.File.ReadAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "optimization_test.json")); 20 | var config = JsonConvert.DeserializeObject(expected); 21 | expected = expected.Replace("\n", "").Replace(" ", "").Replace("\r", ""); 22 | 23 | var actual = JsonConvert.SerializeObject(config, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), 24 | DefaultValueHandling = DefaultValueHandling.Ignore }); 25 | 26 | //tolate extra decimal zero 27 | actual = actual.Replace(".0,", ",").Replace(".0}", "}"); 28 | 29 | Assert.AreEqual(expected, actual); 30 | 31 | 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/Jtc.Optimization.LeanOptimizer.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | ..\..\Lean\Common\bin\Debug\QuantConnect.Common.dll 24 | 25 | 26 | ..\..\Lean\Engine\bin\Debug\QuantConnect.Lean.Engine.dll 27 | 28 | 29 | 30 | 31 | 32 | PreserveNewest 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/OptimizerInitializerTests.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using Moq; 3 | using NUnit.Framework; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO.Abstractions; 7 | using System.Linq; 8 | using System.Reflection; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace Jtc.Optimization.LeanOptimizer.Tests 13 | { 14 | [TestFixture()] 15 | public class OptimizerInitializerTests 16 | { 17 | [Test()] 18 | public void InitializeTest() 19 | { 20 | var file = new Mock(); 21 | file.Setup(f => f.File.ReadAllText(It.IsAny())).Returns("{}"); 22 | var manager = new Mock(); 23 | 24 | var unit = new OptimizerLauncher(file.Object, manager.Object); 25 | 26 | unit.Launch(new[] {""}); 27 | 28 | manager.Verify(m => m.Initialize(It.IsAny(), It.IsAny())); 29 | manager.Verify(m => m.Start()); 30 | } 31 | 32 | 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/StatisticsAdapterTests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using QuantConnect.Statistics; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Jtc.Optimization.LeanOptimizer.Tests 10 | { 11 | [TestFixture()] 12 | public class StatisticsAdapterTests 13 | { 14 | 15 | [Test()] 16 | public void TransformTest() 17 | { 18 | var actual = StatisticsAdapter.Transform(new AlgorithmPerformance 19 | { 20 | PortfolioStatistics = new PortfolioStatistics 21 | { 22 | Alpha = 1.23m 23 | }, 24 | TradeStatistics = new TradeStatistics 25 | { 26 | TotalNumberOfTrades = 0, 27 | TotalFees = 0 28 | } 29 | }, 30 | new Dictionary { { "Total Trades", "45" }, { "Total Fees", "$1.23" } }); 31 | 32 | Assert.AreEqual(1.23m, actual["Alpha"]); 33 | Assert.AreEqual(45m, actual["TotalNumberOfTrades"]); 34 | Assert.AreEqual(1.23m, actual["TotalFees"]); 35 | } 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer.Tests/optimization_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "genes": [ 3 | { 4 | "key": "take", 5 | "min": 0.02, 6 | "max": 0.1, 7 | "precision": 2 8 | }, 9 | { 10 | "key": "fast", 11 | "min": 6, 12 | "max": 48, 13 | "precision": 0, 14 | "actual": 13 15 | }, 16 | { 17 | "key": "slow", 18 | "min": 48, 19 | "max": 500 20 | } 21 | ], 22 | "populationSize": 24, 23 | "populationSizeMaximum": 48, 24 | "generations": 1000, 25 | "stagnationGenerations": 30, 26 | "maxThreads": 8, 27 | "algorithmTypeName": "ParameterizedAlgorithm", 28 | "configPath": "../../../../Lean/Launcher/config.json", 29 | "launcherBuildPath": "../../../../../Lean/Launcher/bin/debug/", 30 | "onePointCrossover": true, 31 | "algorithmLocation": "../../../Optimization.Example/bin/debug/Optimization.Example.dll", 32 | "fitnessTypeName": "Jtc.Optimization.LeanOptimizer.OptimizerFitness", 33 | "dataFolder": "../../../../Lean_base/Data", 34 | "startDate": "2016-02-01T00:00:00Z", 35 | "endDate": "2016-02-03T00:00:00Z", 36 | "mutationProbability": 0.5, 37 | "crossoverProbability": 0.75, 38 | "minimumTrades": 1, 39 | "enableFitnessFilter": true 40 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/ExtensionMethods.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Jtc.Optimization.LeanOptimizer 7 | { 8 | public static class ExtensionMethods 9 | { 10 | 11 | 12 | public static T Clone(this T source) 13 | { 14 | var serialized = JsonConvert.SerializeObject(source); 15 | return JsonConvert.DeserializeObject(serialized); 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/CompoundingAnnualReturnFitness.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects; 2 | using Jtc.Optimization.Objects.Interfaces; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Jtc.Optimization.LeanOptimizer 10 | { 11 | public class CompoundingAnnualReturnFitness : OptimizerFitness 12 | { 13 | 14 | public override string Name { get; set; } = "Return"; 15 | 16 | public CompoundingAnnualReturnFitness(IOptimizerConfiguration config, IFitnessFilter filter) : base(config, filter) 17 | { 18 | } 19 | 20 | double scale = 0.01; 21 | 22 | //Fitness based on Compounding Annual Return 23 | protected override FitnessResult CalculateFitness(Dictionary result) 24 | { 25 | var fitness = new FitnessResult(); 26 | 27 | var car = result["CompoundingAnnualReturn"]; 28 | 29 | if (!Filter.IsSuccess(result, this)) 30 | { 31 | car = -100m; 32 | } 33 | 34 | fitness.Value = car; 35 | 36 | fitness.Fitness = (double)car * scale; 37 | 38 | return fitness; 39 | } 40 | 41 | public override double GetValueFromFitness(double? fitness) 42 | { 43 | return fitness.Value / scale; 44 | } 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/ISharpeMaximizerFactory.cs: -------------------------------------------------------------------------------- 1 | using GeneticSharp.Domain.Fitnesses; 2 | using Jtc.Optimization.Objects.Interfaces; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Jtc.Optimization.LeanOptimizer 8 | { 9 | public interface ISharpeMaximizerFactory 10 | { 11 | 12 | SharpeMaximizer Create(IOptimizerConfiguration config, IFitnessFilter filter); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/IWalkForwardSharpeMaximizer.cs: -------------------------------------------------------------------------------- 1 | using GeneticSharp.Domain.Chromosomes; 2 | using Jtc.Optimization.Objects; 3 | using System.Collections.Generic; 4 | 5 | namespace Jtc.Optimization.LeanOptimizer 6 | { 7 | public interface IWalkForwardSharpeMaximizer 8 | { 9 | List> AllBest { get; } 10 | List AllScores { get; } 11 | 12 | double Evaluate(IChromosome chromosome); 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/IWalkForwardSharpeMaximizerFactory.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | public interface IWalkForwardSharpeMaximizerFactory 6 | { 7 | IWalkForwardSharpeMaximizer Create(IOptimizerConfiguration config, IFitnessFilter filter); 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/NFoldCrossReturnMaximizer.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | public class NFoldCrossReturnMaximizer : NFoldCrossSharpeMaximizer 6 | { 7 | 8 | public override string Name { get; set; } = "NFoldCrossReturn"; 9 | public override string ScoreKey { get; set; } = "CompoundingAnnualReturn"; 10 | 11 | public NFoldCrossReturnMaximizer(IOptimizerConfiguration config, IFitnessFilter filter) : base(config, filter) 12 | { 13 | } 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/SharpeMaximizerFactory.cs: -------------------------------------------------------------------------------- 1 | using GeneticSharp.Domain.Fitnesses; 2 | using Jtc.Optimization.Objects.Interfaces; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Jtc.Optimization.LeanOptimizer 8 | { 9 | class SharpeMaximizerFactory : ISharpeMaximizerFactory 10 | { 11 | public SharpeMaximizer Create(IOptimizerConfiguration config, IFitnessFilter filter) 12 | { 13 | return new SharpeMaximizer(config, filter); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/WalkForwardSharpeMaximizerFactory.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | class WalkForwardSharpeMaximizerFactory : IWalkForwardSharpeMaximizerFactory 6 | { 7 | public IWalkForwardSharpeMaximizer Create(IOptimizerConfiguration config, IFitnessFilter filter) 8 | { 9 | return new WalkForwardSharpeMaximizer(config, filter); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Fitness/WeightedMetricCost.cs: -------------------------------------------------------------------------------- 1 | using MathNet.Numerics.LinearAlgebra; 2 | using MathNet.Numerics.Statistics; 3 | using System; 4 | using System.Linq; 5 | 6 | namespace Jtc.Optimization.LeanOptimizer 7 | { 8 | public class WeightedMetricCost 9 | { 10 | 11 | public static double Calculate(double[] sharpeRatio, double[][] parameters) 12 | { 13 | var normalizedSharpe = sharpeRatio.Select(s => Math.Round(Normalize(s), 3)).Average(); 14 | 15 | var matrix = Matrix.Build.DenseOfColumns(parameters); 16 | 17 | var meanDeviation = matrix.EnumerateRows().Select(s => Normalize(Statistics.PopulationStandardDeviation(s))).Average(); 18 | 19 | return -meanDeviation + normalizedSharpe; 20 | } 21 | 22 | /// 23 | /// Normalize to +-4 24 | /// 25 | /// 26 | /// 27 | private static double Normalize(double value) 28 | { 29 | return Math.Max(Math.Min(value, 4.0), -4.0); 30 | } 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Genetic/PreloadPopulation.cs: -------------------------------------------------------------------------------- 1 | using GeneticSharp.Domain.Chromosomes; 2 | using GeneticSharp.Domain.Populations; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Jtc.Optimization.LeanOptimizer 10 | { 11 | public class PreloadPopulation : Population 12 | { 13 | private IList _preloading; 14 | 15 | public PreloadPopulation(int minSize, int maxSize, IList preloading) 16 | : base(minSize, maxSize, preloading.FirstOrDefault()) 17 | { 18 | _preloading = preloading; 19 | } 20 | 21 | public override void CreateInitialGeneration() 22 | { 23 | Generations = new List(); 24 | GenerationsNumber = 0; 25 | 26 | foreach (var c in _preloading) 27 | { 28 | c.ValidateGenes(); 29 | } 30 | 31 | CreateNewGeneration(_preloading); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Handlers/EmptyObjectStore.cs: -------------------------------------------------------------------------------- 1 | using QuantConnect.Interfaces; 2 | using QuantConnect.Packets; 3 | using System; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Jtc.Optimization.LeanOptimizer 11 | { 12 | public class EmptyObjectStore : IObjectStore 13 | { 14 | public event EventHandler ErrorRaised; 15 | 16 | public bool ContainsKey(string key) 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | 21 | public bool Delete(string key) 22 | { 23 | throw new NotImplementedException(); 24 | } 25 | 26 | public void Dispose() 27 | { 28 | } 29 | 30 | public IEnumerator> GetEnumerator() 31 | { 32 | throw new NotImplementedException(); 33 | } 34 | 35 | public string GetFilePath(string key) 36 | { 37 | throw new NotImplementedException(); 38 | } 39 | 40 | public void Initialize(string algorithmName, int userId, int projectId, string userToken, Controls controls) 41 | { 42 | } 43 | 44 | public byte[] ReadBytes(string key) 45 | { 46 | throw new NotImplementedException(); 47 | } 48 | 49 | public bool SaveBytes(string key, byte[] contents) 50 | { 51 | throw new NotImplementedException(); 52 | } 53 | 54 | IEnumerator IEnumerable.GetEnumerator() 55 | { 56 | throw new NotImplementedException(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Handlers/OptimizerAlphaHandler.cs: -------------------------------------------------------------------------------- 1 | using QuantConnect; 2 | using QuantConnect.Interfaces; 3 | using QuantConnect.Lean.Engine.Alpha; 4 | using QuantConnect.Lean.Engine.TransactionHandlers; 5 | using QuantConnect.Packets; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace Jtc.Optimization.LeanOptimizer 13 | { 14 | class OptimizerAlphaHandler : IAlphaHandler 15 | { 16 | public bool IsActive => false; 17 | 18 | public AlphaRuntimeStatistics RuntimeStatistics => null; 19 | 20 | public void Exit() 21 | { 22 | } 23 | 24 | public void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm, IMessagingHandler messagingHandler, IApi api, 25 | ITransactionHandler transactionHandler) 26 | { 27 | //HACK: needed to set id prior to initialize 28 | algorithm.SetAlgorithmId(((BacktestNodePacket)job).AlgorithmId); 29 | } 30 | 31 | public void OnAfterAlgorithmInitialized(IAlgorithm algorithm) 32 | { 33 | } 34 | 35 | public void ProcessSynchronousEvents() 36 | { 37 | } 38 | 39 | public void Run() 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Handlers/OptimizerSubscriptionDataReaderHistoryProvider.cs: -------------------------------------------------------------------------------- 1 | using QuantConnect.Data; 2 | using QuantConnect.Lean.Engine.HistoricalData; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Jtc.Optimization.LeanOptimizer.Handlers 8 | { 9 | public class OptimizerSubscriptionDataReaderHistoryProvider : SubscriptionDataReaderHistoryProvider 10 | { 11 | 12 | private bool _initialized; 13 | private static object locker = new object(); 14 | 15 | public override void Initialize(HistoryProviderInitializeParameters parameters) 16 | { 17 | lock (locker) 18 | { 19 | if (_initialized) 20 | { 21 | return; 22 | } 23 | base.Initialize(parameters); 24 | _initialized = true; 25 | } 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Interfaces/IFitnessFilter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | public interface IFitnessFilter 6 | { 7 | bool IsSuccess(Dictionary result, OptimizerFitness fitness); 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/Interfaces/IOptimizerManager.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | public interface IOptimizerManager 6 | { 7 | void Initialize(IOptimizerConfiguration config, OptimizerFitness fitness); 8 | void Start(); 9 | } 10 | } -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/LogProvider.cs: -------------------------------------------------------------------------------- 1 | using NLog; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Jtc.Optimization.LeanOptimizer 7 | { 8 | public class LogProvider 9 | { 10 | 11 | public static Logger OptimizerLogger { get; set; } = LogManager.GetLogger("optimizer"); 12 | public static Logger GenerationsLogger { get; set; } = LogManager.GetLogger("generations"); 13 | public static Logger ErrorLogger { get; set; } = LogManager.GetLogger("error"); 14 | public static Logger TraceLogger { get; set; } = LogManager.GetLogger("trace"); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/LogSingleton.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Accord.MachineLearning; 7 | using QuantConnect.Logging; 8 | 9 | namespace Jtc.Optimization.LeanOptimizer 10 | { 11 | public class LogSingleton 12 | { 13 | private static readonly Lazy instance = new Lazy(() => 14 | { 15 | return new FileLogHandler("log.txt", true); 16 | }); 17 | 18 | public static ILogHandler Instance { get { return instance.Value; } } 19 | 20 | private LogSingleton() 21 | { 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/MaximizerManager.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | 3 | namespace Jtc.Optimization.LeanOptimizer 4 | { 5 | 6 | public class MaximizerManager : IOptimizerManager 7 | { 8 | public const string Termination = "Termination Reached."; 9 | private IOptimizerConfiguration _config; 10 | private OptimizerFitness _fitness; 11 | 12 | public void Initialize(IOptimizerConfiguration config, OptimizerFitness fitness) 13 | { 14 | _config = config; 15 | _fitness = fitness; 16 | // _executor.MaxThreads = _config.MaxThreads > 0 ? _config.MaxThreads : 8; 17 | } 18 | 19 | public void Start() 20 | { 21 | GeneFactory.Initialize(_config.Genes); 22 | var chromosome = new Chromosome(false, GeneFactory.Config, false); 23 | //todo: should use return value 24 | var cost = _fitness.Evaluate(chromosome); 25 | 26 | LogProvider.GenerationsLogger.Info(Termination); 27 | 28 | var best = (Chromosome)((SharpeMaximizer)_fitness).Best; 29 | 30 | if (best == null) 31 | { 32 | return; 33 | } 34 | 35 | var info = $"Algorithm: {_config.AlgorithmTypeName}, Fitness: {chromosome.Fitness}, {_fitness.Name}: " + 36 | $"{cost.ToString("F")}, {best.ToKeyValueString()}"; 37 | 38 | LogProvider.GenerationsLogger.Info(info); 39 | } 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/NLog.config: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/SingleContextIsolator.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.LeanOptimizer.Base; 2 | using Jtc.Optimization.Objects.Interfaces; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | using System.Runtime.Loader; 7 | 8 | namespace Jtc.Optimization.LeanOptimizer 9 | { 10 | 11 | public class SingleContextIsolator : BaseContextIsolator 12 | { 13 | 14 | public SingleContextIsolator() : base() 15 | { 16 | ResultMediator.SetResults(AppDomain.CurrentDomain, new Dictionary>()); 17 | } 18 | 19 | public override Dictionary RunAlgorithm(Dictionary list, IOptimizerConfiguration config) 20 | { 21 | var context = AssemblyLoadContext.Default; 22 | using (context.EnterContextualReflection()) 23 | { 24 | var runner = new SingleRunner(); 25 | var result = runner.Run(list, config); 26 | runner = null; 27 | return result; 28 | } 29 | } 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/StatisticsAdapter.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects; 2 | using QuantConnect.Statistics; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Globalization; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Jtc.Optimization.LeanOptimizer 11 | { 12 | public class StatisticsAdapter 13 | { 14 | 15 | public static decimal Translate(string key, Dictionary list) 16 | { 17 | if (StatisticsBinding.Binding.ContainsKey(key)) 18 | { 19 | return list[StatisticsBinding.Binding[key]]; 20 | } 21 | 22 | return list[key]; 23 | } 24 | 25 | public static Dictionary Transform(AlgorithmPerformance performance, IDictionary summary) 26 | { 27 | var list = performance.PortfolioStatistics.GetType().GetProperties().ToDictionary(k => k.Name, v => (decimal)v.GetValue(performance.PortfolioStatistics)); 28 | list.Add("TotalNumberOfTrades", int.Parse(summary["Total Trades"])); 29 | list.Add("TotalFees", decimal.Parse(summary["Total Fees"].Substring(1))); 30 | 31 | return list; 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Jtc.Optimization.LeanOptimizer/remove_logs.bat: -------------------------------------------------------------------------------- 1 | del log*.txt 2 | del *-order-events.json 3 | del trace.txt -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/Enums.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.Objects 8 | { 9 | public class Enums 10 | { 11 | public enum OptimizerTypeOptions 12 | { 13 | Genetic = 0, 14 | RandomSearch = 1, 15 | GridSearch = 2, 16 | ParticleSwarm = 3, 17 | Bayesian = 4, 18 | GlobalizedBoundedNelderMead = 5, 19 | Smac = 6 20 | 21 | } 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/FitnessResult.cs: -------------------------------------------------------------------------------- 1 | namespace Jtc.Optimization.Objects 2 | { 3 | 4 | 5 | public class FitnessResult 6 | { 7 | /// 8 | /// The value of the result 9 | /// 10 | public decimal Value { get; set; } 11 | /// 12 | /// The scaled or adjusted fitness 13 | /// 14 | public double Fitness { get; set; } 15 | } 16 | 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/GeneConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Objects.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Jtc.Optimization.Objects 9 | { 10 | 11 | [Serializable] 12 | public class GeneConfiguration : IGeneConfiguration 13 | { 14 | /// 15 | /// The unique key of the gene 16 | /// 17 | public string Key { get; set; } 18 | 19 | /// 20 | /// The minimum value 21 | /// 22 | public double? Min { get; set; } 23 | 24 | /// 25 | /// The maximum value 26 | /// 27 | public double? Max { get; set; } 28 | 29 | /// 30 | /// The precision (rounding) for gene values 31 | /// 32 | public int? Precision { get; set; } 33 | 34 | /// 35 | /// The non-random starting value 36 | /// 37 | public double? Actual { get; set; } 38 | 39 | /// 40 | /// When true, will randomly select a value between 0 to 10946 from the Fibonacci sequence instead of generating random values in Genetic optimization 41 | /// 42 | /// 43 | public bool Fibonacci { get; set; } 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/Interfaces/IFitnessConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace Jtc.Optimization.Objects.Interfaces 2 | { 3 | 4 | public interface IFitnessConfiguration 5 | { 6 | string Name { get; set; } 7 | string ResultKey { get; set; } 8 | double? Scale { get; set; } 9 | double? Modifier { get; set; } 10 | string OptimizerTypeName { get; set; } 11 | string FoldOptimizerTypeName { get; set; } 12 | int? FoldGenerations { get; set; } 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/Interfaces/IGeneConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace Jtc.Optimization.Objects.Interfaces 2 | { 3 | public interface IGeneConfiguration 4 | { 5 | double? Actual { get; set; } 6 | bool Fibonacci { get; set; } 7 | string Key { get; set; } 8 | double? Max { get; set; } 9 | double? Min { get; set; } 10 | int? Precision { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/Interfaces/IOptimizerConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Jtc.Optimization.Objects.Interfaces 4 | { 5 | public interface IOptimizerConfiguration 6 | { 7 | GeneConfiguration[] Genes { get; set; } 8 | string AlgorithmLocation { get; set; } 9 | string AlgorithmTypeName { get; set; } 10 | string ConfigPath { get; set; } 11 | string LauncherBuildPath { get; set; } 12 | int Generations { get; set; } 13 | int MaxThreads { get; set; } 14 | bool OnePointCrossover { get; set; } 15 | int PopulationSize { get; set; } 16 | int PopulationSizeMaximum { get; set; } 17 | int StagnationGenerations { get; set; } 18 | string FitnessTypeName { get; set; } 19 | string DataFolder { get; set; } 20 | FitnessConfiguration Fitness { get; set; } 21 | DateTime? StartDate { get; set; } 22 | DateTime? EndDate { get; set; } 23 | float MutationProbability { get; set; } 24 | float CrossoverProbability { get; set; } 25 | bool UseActualGenesForWholeGeneration { get; set; } 26 | string TransactionLog { get; set; } 27 | bool EnableRunningDuplicateParameters { get; set; } 28 | bool UseSharedAppDomain { get; set; } 29 | string AlgorithmLanguage { get; set; } 30 | 31 | //fitness filter 32 | int MinimumTrades { get; set; } 33 | bool EnableFitnessFilter { get; set; } 34 | bool ExcludeNetLoss { get; set; } 35 | bool IncludeNegativeReturn { get; set; } 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/IterationResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Jtc.Optimization.Objects 6 | { 7 | public class IterationResult 8 | { 9 | public double Cost { get; set; } 10 | public double[] ParameterSet { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/Jtc.Optimization.Objects.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | AnyCPU;x64 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Jtc.Optimization.Objects/StatisticsBinding.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Jtc.Optimization.Objects 6 | { 7 | public class StatisticsBinding 8 | { 9 | 10 | public static Dictionary Binding = new Dictionary 11 | { 12 | //todo: add psr etc 13 | {"Total Trades", "TotalNumberOfTrades"}, 14 | {"Average Win","AverageWinRate"}, 15 | {"Average Loss","AverageLossRate"}, 16 | {"Compounding Annual Return ","CompoundingAnnualReturn"}, 17 | {"Drawdown","Drawdown"}, 18 | {"Expectancy","Expectancy"}, 19 | {"Net Profit","TotalNetProfit"}, 20 | {"Sharpe Ratio","SharpeRatio"}, 21 | {"Loss Rate","LossRate"}, 22 | {"Win Rate","WinRate"}, 23 | {"Profit-Loss Ratio","ProfitLossRatio"}, 24 | {"Alpha","Alpha"}, 25 | {"Beta","Beta"}, 26 | {"Annual Standard Deviation","AnnualStandardDeviation"}, 27 | {"Annual Variance","AnnualVariance"}, 28 | {"Information Ratio","InformationRatio"}, 29 | {"Tracking Error","TrackingError"}, 30 | {"Treynor Ratio","TreynorRatio"}, 31 | {"Total Fees","TotalFees"} 32 | }; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Jtc.Optimization.OnlineOptimizer/Jtc.Optimization.OnlineOptimizer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | false 6 | false 7 | AnyCPU;x64 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | PreserveNewest 26 | 27 | 28 | PreserveNewest 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Jtc.Optimization.Tests/CSharpCompilerTest.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.Api; 2 | using Jtc.Optimization.Objects; 3 | using Jtc.Optimization.Transformation; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Reflection; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using Xunit; 11 | 12 | namespace Jtc.Optimization.Tests 13 | { 14 | public class CSharpCompilerTest 15 | { 16 | 17 | [Fact] 18 | public async Task Given_csharp_code_When_compiled_Then_returns_expected_assembly_And_assembly_can_be_invoked() 19 | { 20 | var unit = new CSharpCompiler(null, new MscorlibProvider()); 21 | 22 | var assembly = await unit.CreateAssembly("public class Test { public double Getter(double[] input) { return input[0]+1; } }"); 23 | 24 | var func = unit.GetDelegate(assembly); 25 | var actual = await func(new[] { 1d }); 26 | 27 | Assert.Equal(2, actual); 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Jtc.Optimization.Tests/Jtc.Optimization.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | false 9 | 10 | false 11 | 12 | AnyCPU;x64 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | Always 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Jtc.Optimization.Tests/PlotlyThreadedBinderTest.cs: -------------------------------------------------------------------------------- 1 | using BlazorWorker.BackgroundServiceFactory; 2 | using BlazorWorker.Core; 3 | using BlazorWorker.WorkerBackgroundService; 4 | using Jtc.Optimization.Objects; 5 | using Jtc.Optimization.Transformation; 6 | using Moq; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.IO; 10 | using System.Linq; 11 | using System.Reflection; 12 | using System.Threading.Tasks; 13 | using Xunit; 14 | 15 | namespace Jtc.Optimization.Tests 16 | { 17 | public class PlotlyThreadedBinderTest : PlotlyBinderTest 18 | { 19 | 20 | private const int ExpectedLines = 1397; 21 | protected override IPlotlyBinder CreateUnit() 22 | { 23 | var lineSplitter = new PlotlyLineSplitter(); 24 | var wrapper = new Mock(); 25 | wrapper.Setup(w => w.Split(It.IsAny())).Returns(c => Task.FromResult(lineSplitter.Split(c))); 26 | 27 | return new PlotlyThreadedBinder(wrapper.Object); 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/IActivityLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | //todo: namespaces 5 | namespace Jtc.Optimization.Transformation 6 | { 7 | public interface IActivityLogger 8 | { 9 | string Status { get; } 10 | string Log { get; } 11 | 12 | void Add(string message, DateTime data); 13 | void Add(string message, double data); 14 | void Add(string message, double[] data); 15 | void Add(string message, int data); 16 | void Add(string message, TimeSpan data); 17 | void Add(string id, IEnumerable keys, double[] parameters, double cost); 18 | void StateHasChanged(); 19 | void ShowMessageAlways(); 20 | void ResetLog(); 21 | } 22 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/ICSharpCompiler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading.Tasks; 5 | 6 | namespace Jtc.Optimization.Transformation 7 | { 8 | public interface ICSharpCompiler 9 | { 10 | Task CreateAssembly(string code); 11 | Task GetStream(string code); 12 | Func> GetDelegate(Assembly assembly); 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/IMscorlibProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Jtc.Optimization.Transformation 4 | { 5 | public interface IMscorlibProvider 6 | { 7 | Task Get(); 8 | } 9 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/IPlotlyBinder.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.BlazorClient.Objects; 2 | using Jtc.Optimization.Objects; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.Transformation 8 | { 9 | public interface IPlotlyBinder 10 | { 11 | Task> Read(SwitchReader reader, int sampleRate = 1, bool disableNormalization = false, DateTime? minimumDate = null, 12 | double? minimumFitness = null, IActivityLogger activityLogger = null); 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/IPlotlyLineSplitter.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.BlazorClient.Objects; 2 | using Jtc.Optimization.Objects; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Jtc.Optimization.Transformation 7 | { 8 | public interface IPlotlyLineSplitter 9 | { 10 | Dictionary Split(string[] line); 11 | } 12 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Interfaces/IPlotlyLineSplitterBackgroundWrapper.cs: -------------------------------------------------------------------------------- 1 | using BlazorWorker.Core; 2 | using BlazorWorker.WorkerBackgroundService; 3 | using Jtc.Optimization.BlazorClient.Objects; 4 | using Jtc.Optimization.Objects; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | namespace Jtc.Optimization.Transformation 9 | { 10 | public interface IPlotlyLineSplitterBackgroundWrapper 11 | { 12 | Task> Split(string[] chunk); 13 | } 14 | } -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/Jtc.Optimization.Transformation.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | false 6 | false 7 | AnyCPU;x64 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/MscorlibRemoteProvider.cs: -------------------------------------------------------------------------------- 1 | using Jtc.Optimization.BlazorClient.Objects; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Jtc.Optimization.Transformation 10 | { 11 | public class MscorlibRemoteProvider : IMscorlibProvider 12 | { 13 | 14 | private readonly IBlazorClientConfiguration _blazorClientConfiguration; 15 | protected HttpClient HttpClient { get; } 16 | 17 | public MscorlibRemoteProvider(HttpClient httpClient, IBlazorClientConfiguration blazorClientConfiguration) 18 | { 19 | HttpClient = httpClient; 20 | _blazorClientConfiguration = blazorClientConfiguration; 21 | } 22 | 23 | public async Task Get() 24 | { 25 | var uri = new Uri(HttpClient.BaseAddress.Scheme + "://" + _blazorClientConfiguration.ApiUrl + "/api/mscorlib"); 26 | var response = await HttpClient.GetAsync(uri); 27 | 28 | 29 | return await response.Content.ReadAsByteArrayAsync(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/PlotlyLineSplitterBackgroundWrapper.cs: -------------------------------------------------------------------------------- 1 | using BlazorWorker.BackgroundServiceFactory; 2 | using BlazorWorker.Core; 3 | using BlazorWorker.WorkerBackgroundService; 4 | using Jtc.Optimization.BlazorClient.Objects; 5 | using Jtc.Optimization.Objects; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace Jtc.Optimization.Transformation 12 | { 13 | public class PlotlyLineSplitterBackgroundWrapper : IPlotlyLineSplitterBackgroundWrapper 14 | { 15 | private readonly IWorkerFactory _workerFactory; 16 | private IWorkerBackgroundService _backgroundService; 17 | 18 | public PlotlyLineSplitterBackgroundWrapper(IWorkerFactory workerFactory) 19 | { 20 | _workerFactory = workerFactory; 21 | } 22 | 23 | public async Task> Split(string[] chunk) 24 | { 25 | if (_backgroundService == null) 26 | { 27 | var worker = await _workerFactory.CreateAsync(); 28 | _backgroundService = await worker.CreateBackgroundServiceAsync(new WorkerInitOptions 29 | { 30 | DependentAssemblyFilenames = new[] { "Jtc.Optimization.Transformation.dll", "System.Text.Json.dll", 31 | "Jtc.Optimization.BlazorClient.Objects.dll" } 32 | }); 33 | } 34 | 35 | return await _backgroundService.RunAsync(s => s.Split(chunk)); 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/RangeWithPrecision.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Jtc.Optimization.Transformation 7 | { 8 | public class RangeWithPrecision 9 | { 10 | 11 | 12 | public static IEnumerable Range(double min, double max, int? precision) 13 | { 14 | if ((precision ?? 0) == 0) 15 | { 16 | return Enumerable.Range((int)min, (int)max - (int)min).Select(s => (double)s); 17 | } 18 | 19 | return Range(min, max, precision.Value); 20 | } 21 | 22 | private static IEnumerable Range(double min, double max, int precision) 23 | { 24 | var stepSize = Math.Pow(0.1, precision); 25 | var decimalModifier = Math.Pow(10, precision); 26 | for (double i = min; i < max + stepSize; i += stepSize) 27 | { 28 | var item = Math.Truncate(i * decimalModifier) / decimalModifier; 29 | yield return item; 30 | } 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Jtc.Optimization.Transformation/SwitchReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Jtc.Optimization.Transformation 8 | { 9 | public class SwitchReader : IDisposable 10 | { 11 | private readonly StreamReader _streamReader; 12 | private readonly StringReader _stringReader; 13 | 14 | public SwitchReader(StreamReader streamReader) 15 | { 16 | _streamReader = streamReader; 17 | } 18 | 19 | public SwitchReader(StringReader stringReader) 20 | { 21 | _stringReader = stringReader; 22 | } 23 | 24 | public async Task ReadLineAsync() 25 | { 26 | return _streamReader != null ? await _streamReader.ReadLineAsync() : await _stringReader.ReadLineAsync(); 27 | } 28 | 29 | public void Dispose() 30 | { 31 | _stringReader?.Dispose(); 32 | _streamReader?.Dispose(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | namespace AlgoChart 4 | { 5 | /// 6 | /// Interaction logic for App.xaml 7 | /// 8 | public partial class App : Application 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace AlgoChart.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.4.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Jtc.Optimization.WpfClient/running.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/Jtc.Optimization.WpfClient/running.ico -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/IIndexedLearner.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Containers.Matrices; 2 | 3 | namespace SharpLearning.Common.Interfaces 4 | { 5 | /// 6 | /// Interface for indexed learner. 7 | /// Only the observations from the provided indices in the index array will be used for training 8 | /// 9 | /// The prediction type of the resulting model. 10 | public interface IIndexedLearner 11 | { 12 | /// 13 | /// Only the observations from the provided indices in the index array will be used for training 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | IPredictorModel Learn(F64Matrix observations, double[] targets, int[] indices); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/ILearner.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Containers.Matrices; 2 | 3 | namespace SharpLearning.Common.Interfaces 4 | { 5 | /// 6 | /// General interface for learner. 7 | /// 8 | /// 9 | public interface ILearner 10 | { 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | IPredictorModel Learn(F64Matrix observations, double[] targets); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/IMetric.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace SharpLearning.Common.Interfaces 3 | { 4 | /// 5 | /// General metric interface 6 | /// 7 | /// 8 | /// 9 | public interface IMetric 10 | { 11 | /// 12 | /// Returns an error metric based on the targets and predictions 13 | /// 14 | /// 15 | /// 16 | /// 17 | double Error(TTarget[] targets, TPrediction[] predictions); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/IModelVariableImportance.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace SharpLearning.Common.Interfaces 4 | { 5 | /// 6 | /// Interface for variable importance 7 | /// 8 | public interface IModelVariableImportance 9 | { 10 | /// 11 | /// Gets the raw unsorted variable importance scores 12 | /// 13 | /// 14 | double[] GetRawVariableImportance(); 15 | 16 | /// 17 | /// Returns the rescaled (0-100) and sorted variable importance scores with corresponding name 18 | /// 19 | /// 20 | /// 21 | Dictionary GetVariableImportance(Dictionary featureNameToIndex); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/IPredictor.cs: -------------------------------------------------------------------------------- 1 |  2 | using SharpLearning.Containers.Matrices; 3 | 4 | namespace SharpLearning.Common.Interfaces 5 | { 6 | /// 7 | /// General interface for predictor. 8 | /// 9 | /// The prediction type of the resulting model. 10 | public interface IPredictor 11 | { 12 | /// 13 | /// Predicts a single observation 14 | /// 15 | /// 16 | /// 17 | TPrediction Predict(double[] observation); 18 | 19 | /// 20 | /// Predicts a set of observations 21 | /// 22 | /// 23 | /// 24 | TPrediction[] Predict(F64Matrix observations); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SharpLearning.Common.Interfaces/IPredictorModel.cs: -------------------------------------------------------------------------------- 1 | namespace SharpLearning.Common.Interfaces 2 | { 3 | /// 4 | /// Interface for predictor models. Supports prediction and variable importance. 5 | /// 6 | /// 7 | public interface IPredictorModel : IPredictor, IModelVariableImportance 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /SharpLearning.Containers/Views/F64VectorPinnedPtr.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace SharpLearning.Containers.Views 5 | { 6 | /// 7 | /// Pinned pointer to F64Vector. Proper disposal required. Preferably use this in a Using statement 8 | /// 9 | /// Using(var pinned = vector.GetPinnedPointer()) 10 | /// { 11 | /// var view = pinned.View(); 12 | /// } 13 | /// 14 | /// 15 | public unsafe struct F64VectorPinnedPtr : IDisposable 16 | { 17 | readonly int m_length; 18 | readonly GCHandle m_handle; 19 | double* m_ptr; 20 | 21 | /// 22 | /// 23 | /// 24 | /// 25 | public F64VectorPinnedPtr(double[] v) 26 | { 27 | m_length = v.Length; 28 | m_handle = GCHandle.Alloc(v, GCHandleType.Pinned); 29 | m_ptr = (double*)m_handle.AddrOfPinnedObject().ToPointer(); 30 | } 31 | 32 | /// 33 | /// Creates a view over the pinned F64Vector 34 | /// 35 | /// 36 | public F64VectorView View() 37 | { 38 | return new F64VectorView(m_ptr, m_length); 39 | } 40 | 41 | /// 42 | /// 43 | /// 44 | public void Dispose() 45 | { 46 | if (m_ptr != null) 47 | { 48 | m_ptr = null; 49 | m_handle.Free(); 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SharpLearning.DecisionTrees/Nodes/DecisionNodeCreationItem.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Containers.Views; 2 | 3 | namespace SharpLearning.DecisionTrees.Nodes 4 | { 5 | /// 6 | /// Structure used for decision tree learning 7 | /// 8 | public struct DecisionNodeCreationItem 9 | { 10 | /// 11 | /// 12 | /// 13 | public readonly int ParentIndex; 14 | 15 | /// 16 | /// 17 | /// 18 | public readonly NodePositionType NodeType; 19 | 20 | /// 21 | /// 22 | /// 23 | public readonly Interval1D Interval; 24 | 25 | /// 26 | /// 27 | /// 28 | public readonly double Impurity; 29 | 30 | /// 31 | /// 32 | /// 33 | public readonly int NodeDepth; 34 | 35 | /// 36 | /// 37 | /// 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | public DecisionNodeCreationItem(int parentIndex, NodePositionType nodeType, Interval1D interval, 44 | double impurity, int nodeDepth) 45 | { 46 | ParentIndex = parentIndex; 47 | NodeType = nodeType; 48 | Interval = interval; 49 | Impurity = impurity; 50 | NodeDepth = nodeDepth; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /SharpLearning.DecisionTrees/Nodes/NodeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SharpLearning.DecisionTrees.Nodes 5 | { 6 | /// 7 | /// Extension methods for node 8 | /// 9 | public static class NodeExtensions 10 | { 11 | /// 12 | /// Updates the parent node with the new child 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | public static void UpdateParent(this List nodes, Node parent, Node child, NodePositionType type) 19 | { 20 | switch (type) 21 | { 22 | case NodePositionType.Root: 23 | break; 24 | case NodePositionType.Left: 25 | nodes[parent.NodeIndex] = new Node(parent.FeatureIndex, parent.Value, 26 | child.NodeIndex, parent.RightIndex, parent.NodeIndex, parent.LeafProbabilityIndex); 27 | break; 28 | case NodePositionType.Right: 29 | nodes[parent.NodeIndex] = new Node(parent.FeatureIndex, parent.Value, 30 | parent.LeftIndex, child.NodeIndex, parent.NodeIndex, parent.LeafProbabilityIndex); 31 | break; 32 | default: 33 | throw new InvalidOperationException("Unsupported position type"); 34 | } 35 | 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /SharpLearning.DecisionTrees/Nodes/NodePositionType.cs: -------------------------------------------------------------------------------- 1 | namespace SharpLearning.DecisionTrees.Nodes 2 | { 3 | /// 4 | /// 5 | /// 6 | public enum NodePositionType 7 | { 8 | /// 9 | /// 10 | /// 11 | Root, 12 | 13 | /// 14 | /// 15 | /// 16 | Left, 17 | 18 | /// 19 | /// 20 | /// 21 | Right 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SharpLearning.DecisionTrees/SplitSearchers/ISplitSearcher.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Containers.Views; 2 | using SharpLearning.DecisionTrees.ImpurityCalculators; 3 | 4 | namespace SharpLearning.DecisionTrees.SplitSearchers 5 | { 6 | /// 7 | /// A SplitSearcher seeks to find the most optimal split for the given feature and targets 8 | /// 9 | public interface ISplitSearcher 10 | { 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | /// 20 | SplitResult FindBestSplit(IImpurityCalculator impurityCalculator, double[] feature, double[] targets, 21 | Interval1D parentInterval, double parentImpurity); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SharpLearning.DecisionTrees/TreeBuilders/ITreeBuilder.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Containers.Views; 2 | using SharpLearning.DecisionTrees.Nodes; 3 | 4 | namespace SharpLearning.DecisionTrees.TreeBuilders 5 | { 6 | /// 7 | /// Tree builder interface 8 | /// 9 | public interface ITreeBuilder 10 | { 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | BinaryTree Build(F64MatrixView observations, double[] targets, int[] indices, double[] weights); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /SharpLearning.InputOutput/Csv/DictionaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace SharpLearning.InputOutput.Csv 5 | { 6 | /// 7 | /// Extension methods for dictionary 8 | /// 9 | public static class DictionaryExtensions 10 | { 11 | /// 12 | /// Gets the set of values corresponding to the set of keys 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | public static T2[] GetValues(this Dictionary dictionary, T1[] keys) 20 | { 21 | return keys.Select(key => dictionary[key]).ToArray(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SharpLearning.InputOutput/Serialization/IGenericSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace SharpLearning.InputOutput.Serialization 5 | { 6 | /// 7 | /// Generic serializer interface 8 | /// 9 | public interface IGenericSerializer 10 | { 11 | /// 12 | /// Serialize data to the provided writer 13 | /// 14 | /// 15 | /// 16 | /// 17 | void Serialize(T data, Func writer); 18 | 19 | /// 20 | /// Deserialize data from the provided reader 21 | /// 22 | /// 23 | /// 24 | /// 25 | T Deserialize(Func reader); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/IOptimizer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace SharpLearning.Optimization 6 | { 7 | /// 8 | /// 9 | /// 10 | public interface IOptimizer 11 | { 12 | /// 13 | /// Returns the result which best minimises the provided function. 14 | /// 15 | /// 16 | /// 17 | Task OptimizeBest(Func> functionToMinimize); 18 | 19 | /// 20 | /// Returns all results ordered from best to worst (minimized). 21 | /// 22 | /// 23 | /// 24 | Task> Optimize(Func> functionToMinimize); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/OptimizerResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SharpLearning.Optimization 4 | { 5 | /// 6 | /// Optimization result 7 | /// 8 | [Serializable] 9 | public sealed class OptimizerResult 10 | { 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | public OptimizerResult(double[] parameterSet, double error) 17 | { 18 | ParameterSet = parameterSet ?? throw new ArgumentException(nameof(parameterSet)); 19 | Error = error; 20 | } 21 | 22 | /// 23 | /// Resulting error using the parameter set. 24 | /// 25 | public double Error { get; } 26 | 27 | /// 28 | /// The parameter set. 29 | /// 30 | public double[] ParameterSet { get; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/ParameterSamplers/IParameterSampler.cs: -------------------------------------------------------------------------------- 1 | namespace SharpLearning.Optimization.ParameterSamplers 2 | { 3 | /// 4 | /// Defines the interface for a parameter samplers. 5 | /// 6 | public interface IParameterSampler 7 | { 8 | /// 9 | /// Returns a sample within in the specified min/max boundaries. 10 | /// 11 | /// Minimum bound 12 | /// Maximum bound 13 | /// Selects the type of parameter. Should the parameter be sampled as discrete values, or as continuous values. 14 | /// 15 | double Sample(double min, double max, ParameterType parameterType); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/ParameterSpecs/IParameterSpec.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Optimization.ParameterSamplers; 2 | 3 | namespace SharpLearning.Optimization 4 | { 5 | /// 6 | /// Interface for parameter specs. 7 | /// 8 | public interface IParameterSpec 9 | { 10 | /// 11 | /// Minimum bound. 12 | /// 13 | double Min { get; } 14 | 15 | /// 16 | /// Maximum bound. 17 | /// 18 | double Max { get; } 19 | 20 | /// 21 | /// samples a value. 22 | /// 23 | /// 24 | /// 25 | double SampleValue(IParameterSampler sampler); 26 | 27 | /// 28 | /// Returns all available values. 29 | /// Primarily used for grid search. 30 | /// 31 | /// 32 | double[] GetAllValues(); 33 | } 34 | } -------------------------------------------------------------------------------- /SharpLearning.Optimization/ParameterType.cs: -------------------------------------------------------------------------------- 1 | namespace SharpLearning.Optimization 2 | { 3 | /// 4 | /// Type of the parameter 5 | /// 6 | public enum ParameterType 7 | { 8 | /// 9 | /// Discrete parameter, represented by integer values. 10 | /// 11 | Discrete, 12 | 13 | /// 14 | /// Continuous parameter, represented by floating point numbers. 15 | /// 16 | Continuous, 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transform.cs: -------------------------------------------------------------------------------- 1 | namespace SharpLearning.Optimization 2 | { 3 | /// 4 | /// Enum for specifying predefined parameter samplers 5 | /// 6 | public enum Transform 7 | { 8 | /// 9 | /// Linear scale. For ranges with a small difference in numerical scale, like min: 64 and max: 256. 10 | /// 11 | Linear, 12 | 13 | /// 14 | /// Logarithmic scale. For ranges with a large difference in numerical scale, like min: 0.0001 and max: 1.0. 15 | /// 16 | Log10, 17 | 18 | /// 19 | /// ExponentialAverage scale. For ranges close to one, like min: 0.9 and max: 0.999. 20 | /// 21 | ExponentialAverage 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transforms/ExponentialAverageTransform.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SharpLearning.Optimization.ParameterSamplers; 3 | 4 | namespace SharpLearning.Optimization.Transforms 5 | { 6 | /// 7 | /// ExponentialAverage scale. For ranges close to one, like min: 0.9 and max: 0.999. 8 | /// Note that the min and max must be smaller than 1 for this transform. 9 | /// 10 | public class ExponentialAverageTransform : ITransform 11 | { 12 | /// 13 | /// ExponentialAverage scale. For ranges close to one, like min: 0.9 and max: 0.999. 14 | /// Note that the min and max values must be smaller than 1 for this transform. 15 | /// 16 | /// 17 | /// 18 | /// 19 | /// Selects the type of parameter. Should the parameter be sampled as discrete values, or as continous values. 20 | /// 21 | public double Transform(double min, double max, ParameterType parameterType, IParameterSampler sampler) 22 | { 23 | if (min >= 1 || max >= 1) 24 | { 25 | throw new ArgumentException("ExponentialAverage scale requires min: " + 26 | $" {min} and max: {max} to be smaller than one"); 27 | } 28 | 29 | var a = Math.Log10(1 - max); 30 | var b = Math.Log10(1 - min); 31 | 32 | var r = sampler.Sample(a, b, parameterType); 33 | return 1.0 - Math.Pow(10, r); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transforms/ITransform.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Optimization.ParameterSamplers; 2 | 3 | namespace SharpLearning.Optimization.Transforms 4 | { 5 | /// 6 | /// Interface for transforms. 7 | /// 8 | public interface ITransform 9 | { 10 | /// 11 | /// Adds a transform to the values used in the sampler. 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// Selects the type of parameter. Should the parameter be sampled as discrete values, or as continous values. 17 | /// 18 | double Transform(double min, double max, ParameterType parameterType, IParameterSampler sampler); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transforms/LinearTransform.cs: -------------------------------------------------------------------------------- 1 | using SharpLearning.Optimization.ParameterSamplers; 2 | 3 | namespace SharpLearning.Optimization.Transforms 4 | { 5 | /// 6 | /// Linear scale. For ranges with a small difference in numerical scale, like min: 64 and max: 256. 7 | /// 8 | public class LinearTransform : ITransform 9 | { 10 | /// 11 | /// Linear scale. For ranges with a small difference in numerical scale, like min: 64 and max: 256. 12 | /// Returns the samplers value directly. 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// Selects the type of parameter. Should the parameter be sampled as discrete values, or as continous values. 18 | /// 19 | public double Transform(double min, double max, ParameterType parameterType, IParameterSampler sampler) 20 | { 21 | return sampler.Sample(min, max, parameterType); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transforms/Log10Transform.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SharpLearning.Optimization.ParameterSamplers; 3 | 4 | namespace SharpLearning.Optimization.Transforms 5 | { 6 | /// 7 | /// Transform to Log10 scale. For ranges with a large difference in numerical scale, like min: 0.0001 and max: 1.0. 8 | /// 9 | public class Log10Transform : ITransform 10 | { 11 | /// 12 | /// Transform to Log10 scale. For ranges with a large difference in numerical scale, like min: 0.0001 and max: 1.0. 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// Selects the type of parameter. Should the parameter be sampled as discrete values, or as continous values. 18 | /// 19 | public double Transform(double min, double max, ParameterType parameterType, IParameterSampler sampler) 20 | { 21 | if (min <= 0 || max <= 0) 22 | { 23 | throw new ArgumentException("logarithmic scale requires min: " + 24 | $"{min} and max: {max} to be larger than zero"); 25 | } 26 | var a = Math.Log10(min); 27 | var b = Math.Log10(max); 28 | 29 | var r = sampler.Sample(a, b, parameterType); 30 | return Math.Pow(10, r); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /SharpLearning.Optimization/Transforms/TransformFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SharpLearning.Optimization.Transforms 4 | { 5 | /// 6 | /// Return a transform from predefined selections. 7 | /// 8 | public static class TransformFactory 9 | { 10 | /// 11 | /// Return a transform from predefined selections. 12 | /// 13 | /// 14 | /// 15 | public static ITransform Create(Transform transform) 16 | { 17 | switch (transform) 18 | { 19 | case Transform.Linear: 20 | return new LinearTransform(); 21 | case Transform.Log10: 22 | return new Log10Transform(); 23 | case Transform.ExponentialAverage: 24 | return new ExponentialAverageTransform(); 25 | default: 26 | throw new ArgumentException("Unsupported transform: " + transform); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/chart.png -------------------------------------------------------------------------------- /config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jameschch/LeanParameterOptimization/c00fc9a5dc0dc0f50e088e62214b7d481e6c9a19/config.png -------------------------------------------------------------------------------- /run_blazor.bat: -------------------------------------------------------------------------------- 1 | rem Bypass "Terminate Batch Job" prompt. 2 | if "%~1"=="-FIXED_CTRL_C" ( 3 | REM Remove the -FIXED_CTRL_C parameter 4 | SHIFT 5 | ) ELSE ( 6 | REM Run the batch with