public AgentsGroup(ProblemInstance instance, AgentState[] allAgentsState, ISolver singleAgentSolver, ISolver groupSolver)
 {
     this.allAgentsState    = allAgentsState;
     this.instance          = instance.Subproblem(allAgentsState);
     this.singleAgentSolver = singleAgentSolver;
     this.groupSolver       = groupSolver;
 }
        protected override void UpdateInner(ISolver caller, SolverState state, SolverStatistics global, string txt)
        {
            var l = Render(caller, state, global, txt);

            a.WriteLine(l);
            UpdateConsoleInPlace(l);
        }
 private async void Solve(ISolver solver)
 {
     _countOfSolversRunning++;
     SolvingProgressBarCheck();
     /*When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the 
      * exception and display an error message that says "exception not handled by user code." This error 
      * is benign. You can press F5 to continue and see the exception-handling behavior that is demonstrated 
      * in these examples. To prevent Visual Studio from breaking on the first error, just uncheck the Enable 
      * Just My Code checkbox under Tools, Options, Debugging, General.*/
     var solverTask = Task.Factory.StartNew(() =>
         solver.Solve(_nodeCollectionStorage.GetStartNode(), _nodeCollectionStorage.GetEndNode()));
     try
     {
         await solverTask;
         _render.DrawResults(solver.LastResult);
         _resultsWindow.DrawResults(solver.LastResult);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         Log.Error(e);
     }
     finally
     {
         _countOfSolversRunning--;
         SolvingProgressBarCheck();
     }
 }
Example #4
0
        private void RunSolverWith(ISolver solver)
        {
            SolverException = null;
            SolverState     = null;

            Solver        = solver;
            SolverCommand = new SolverCommand()
            {
                Puzzle         = Puzzle,
                ExitConditions = ExitConditions.Default3Min(),
            };

            SolverTask = Task.Run(() =>
            {
                try
                {
                    SolverState = Solver.Init(SolverCommand);
                    Solver.Solve(SolverState);
                }
                catch (Exception e)
                {
                    SolverException = e;
                }
            });
        }
Example #5
0
        private static string SolveQuestion(ISolver[] solvers, Context context)
        {
            StringBuilder output = new StringBuilder();

            context.Questions.ForEach(question =>
            {
                bool solved = false;
                string answer = null;

                foreach (var solver in solvers)
                {
                    try
                    {
                        solved = solver.Solve(question, context, out answer);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                    }

                    if (solved)
                    {
                        break;
                    }
                }

                output.AppendLine(solved ? answer : Constants.NotKnow);
            });

            return output.ToString();
        }
Example #6
0
        public MainWindow()
        {
            InitializeComponent();

            _input = JsonConvert.DeserializeObject<Input>(File.ReadAllText("input.json"));

            var options = JsonConvert.DeserializeObject<ExecutionOptions>(File.ReadAllText("options.json"));
            //new ExecutionOptions
            //{
            //	MaxWidth = 4,
            //	MaxHeight = 6,
            //	MinEstimation = double.MinValue,
            //	AttractorRatio = 10,
            //	DepthPenaltyRatio = 10,
            //	//HiddenHolesPenalty = 10,
            //	AdjacencyDownRatio = 5
            //}
            _execution = new ExecutionRequest
            {
                Snapshot = new Snapshot(_input, _input.SourceSeeds.First()),
                Options = options
            };

            _solver = new IterativeSearchSolver(4000); //new TraverseSolver();

            SizeChanged += (s, e) => Update();

            commandBar.SpawnEvent += commandBarSpawnEvent;
            commandBar.Move += commandBarMove;
            commandBar.StartSolver += commandBarStartSolver;
        }
Example #7
0
 private static void SetupPlugins()
 {
     _display = PluginLoader.Displays.First(d => d.PluginName == Settings.Default.DisplayPluginName);
     _configurationGenerator = PluginLoader.ConfigurationGenerators.First(g => g.PluginName == Settings.Default.GeneratorPluginName);
     _solver = PluginLoader.Solvers.First(s => s.PluginName == Settings.Default.SolverPluginName);
     _celebrator = PluginLoader.Celebrators.First(c => c.PluginName == Settings.Default.CelebratorPluginName);
 }
Example #8
0
 public override void Accept(ISolver solver)
 {
     if (solver.Solve(this).HasValue)
     {
         TryMarkAsSolved(Computation());
     }
 }
        /// <summary>
        /// Solve the group of agents together.
        /// </summary>
        /// <param name="runner"></param>
        /// <returns>true if optimal solution for the group of agents were found, false otherwise</returns>
        public bool Solve(Run runner)
        {
            ISolver relevantSolver = this.groupSolver;

            if (this.allAgentsState.Length == 1)
            {
                relevantSolver = this.singleAgentSolver; // TODO: Consider using CBS's root trick to really get single agent paths fast. Though it won't respect illegal moves and such.
            }
            relevantSolver.Setup(this.instance, runner);
            bool solved = relevantSolver.Solve();

            this.solutionCost = relevantSolver.GetSolutionCost();
            if (solved == false)
            {
                return(false);
            }

            // Store the plan found by the solver
            this.plan            = relevantSolver.GetPlan();
            this.expanded        = relevantSolver.GetExpanded();
            this.generated       = relevantSolver.GetGenerated();
            this.depthOfSolution = relevantSolver.GetSolutionDepth();

            // Clear memory
            relevantSolver.Clear();
            return(true);
        }
Example #10
0
 /// <summary>
 /// Creates a new solver objective wrapper.
 /// </summary>
 public SolverObjectiveWrapper(ISolver <TWeight, TProblem, TObjectiveUsed, TSolution, TFitness> solver, TObjectiveUsed objective, Func <TProblem, TObjective, TSolution, TFitness> calculateFitness)
 {
     _solver = solver;
     _solver.IntermidiateResult += _solver_IntermidiateResult;
     _objective        = objective;
     _calculateFitness = calculateFitness;
 }
Example #11
0
        public List <ResultModel> Run(int iterations, IProblem problem, ISolver solver, int searchIterations, int minTabu, int extraTabu, int timeLimitInSeconds)
        {
            var results = new List <ResultModel>();

            solver.MaxIterations = searchIterations;
            solver.MinTabu       = minTabu;
            solver.ExtraTabu     = extraTabu;
            var stopWatch = new Stopwatch();

            for (var i = 0; i < iterations; i++)
            {
                stopWatch.Start();
                Console.WriteLine($"Algorithm run number {i}");
                var bestResult    = new ResultModel();
                var numberOfTries = 0;
                while (stopWatch.Elapsed.TotalSeconds < timeLimitInSeconds)
                {
                    numberOfTries++;
                    var result = solver.Solve(new LADS(problem));
                    if (result > bestResult)
                    {
                        bestResult = result;
                    }
                }
                stopWatch.Stop();
                stopWatch.Restart();
                Console.WriteLine($"Number of tries {numberOfTries} for max iterations {searchIterations}");
                results.Add(bestResult);
            }

            return(results);
        }
Example #12
0
        private static void RunSolver(ISolver solver, IInput input)
        {
            var solution = solver.GetSolution(input);

            Console.WriteLine("Part one solution: " + solution.FirstPart);
            Console.WriteLine("Part two solution: " + solution.SecondPart);
        }
Example #13
0
 public MazeFactory(string[] arguments, string loaderOption, string solverOption, string displayerOption)
 {
     this.arguments = arguments;
     loader = GetLoader(loaderOption);
     solver = GetSolver(solverOption);
     displayer = GetDisplayer(displayerOption);
 }
 public void initial()
 {
     try
     {
         solver = (ISolver)(Activator.CreateInstance(Type.GetType("LP.Solver" + this.solverType)));
         if (this.solverType == "GLPK")
         {
             prob = new ProblemGLPK(this.directedGraph1, this.directedGraph2);
         }
         else
         {
             if (this.graph1.IsDirected == true)
             {
                 prob = new ProblemCPLEX(this.directedGraph1, this.directedGraph2);
             }
             else
             {
                 prob = new ProblemCPLEXUndirected(this.directedGraph1, this.directedGraph2);
             }
             // prob = new ProblemCPLEX(this.directedGraph1, this.directedGraph2);
         }
         matchingResult = new MatchingResult();
     }
     catch (Exception e)
     {
         Console.Write(e.ToString());
     }
 }
Example #15
0
 private LoadControlAnalyzer(IStructuralModel model, ISolver solver, INonLinearProvider provider,
                             IReadOnlyDictionary <int, INonLinearSubdomainUpdater> subdomainUpdaters,
                             int numIncrements, int maxIterationsPerIncrement, int numIterationsForMatrixRebuild, double residualTolerance) :
     base(model, solver, provider, subdomainUpdaters, numIncrements, maxIterationsPerIncrement,
          numIterationsForMatrixRebuild, residualTolerance)
 {
 }
Example #16
0
 public SeparationOfDataSet(ISolver solver, LearningScenario learnignScenario, float [][] x, float [] y)
 {
     ISolver    = solver;
     LS         = learnignScenario;
     InputData  = x;
     OutputData = y;
 }
 public ExpressionSolve(
     ISolver <string, decimal> expSolver,
     IParser <string, string> expParser)
 {
     this.expSolver = expSolver;
     this.expParser = expParser;
 }
Example #18
0
        private static void Solve(Grid grid, ISolver[] solvers, bool useBruteForceFallback)
        {
            var unsolvedSquares = 81;
            var retryCount = 0;

            // Whilst having an effect on the grid i.e. solving at least one square each iteration
            // - not checking for the effect of removing possibilities so give it a retry
            while (retryCount < 2)
            {
                while (grid.UnsolvedSquareCount > 0 && grid.UnsolvedSquareCount < unsolvedSquares)
                {
                    unsolvedSquares = grid.UnsolvedSquareCount;
                    foreach (var solver in solvers)
                    {
                        solver.Solve(grid);
                        grid.Tidy();
                    }
                }

                retryCount++;
            }

            if (grid.IsSolved) return;

            if (!useBruteForceFallback) return;

            var bruteForceSolver = new BruteForceSolver();
            bruteForceSolver.Solve(grid);
        }
Example #19
0
        public Sorter()
        {
            parseStatistics = true;
            checkFirstLevelOnly = true;
            verbose = 0;
            reuseSolver = true;
            moveLimit = 0;
            changeLimit = 0;
            pushLimit = 0;
            boxMoveLimit = 0;
            rejectSokobanOnTarget = false;
            rejectDeadEnds = false;
            rejectCapturedTargets = false;
            normalizeLevels = true;
            validateNormalization = true;
            nodes = 20000000;
            outputFile = "LevelSorter.xsb";

            persistentSolver = reuseSolver ? Solver.CreateInstance() : null;
            set = new TransformationInvariantLevelSet();
            results = new List<LevelInfo>();

            // Don't include the sokoban in the set.
            set.IncludeSokoban = false;
        }
 public TspMultipleStartLocalSearchSolver(IGraph completeGraph, ISolver internalSolver,
                                          IAlgorithm internalAlgorithm) : base(completeGraph)
 {
     _internalSolver    = internalSolver;
     _internalAlgorithm = internalAlgorithm;
     _randomGenerator   = new Random();
 }
Example #21
0
        public static int Multiply(this ISolver solver, int a, int b)
        {
            bool sameSign = Math.Sign(a) == Math.Sign(b);
            int  product  = Table[Math.Abs(a), Math.Abs(b)];

            return(sameSign ? product : -product);
        }
Example #22
0
        static void Process(TextReader txtIn, TextWriter txtOut, ISolver solver)
        {
            long timeStart = DateTime.Now.Ticks;

            int numCases = int.Parse(txtIn.ReadLine());

            for (int i = 1; i <= numCases; i++)
            {
                // Reads input
                var line1 = ReadLine(txtIn).Split(' ').Select(s => long.Parse(s)).ToArray();
                var line2 = ReadLine(txtIn).Split(' ').Select(s => long.Parse(s)).ToArray();

                // Calls solver to solve
                Console.WriteLine("{0} Doing case #{1}", DateTime.Now.ToLongTimeString(), i);
                var ans = solver.Solve((int)line1[0], line2, line1[2]);

                // Prints output
                txtOut.WriteLine("Case #{0}: {1}", i, ans);
            }

            long timeEnd = DateTime.Now.Ticks;
            var  elapsed = TimeSpan.FromTicks(timeEnd - timeStart);

            Console.WriteLine("Elapsed time: {0} min {1} sec", elapsed.Minutes, elapsed.Seconds);
        }
Example #23
0
        public static void Solve(this Circuit circuit, ISolver solver)
        {
            var component = (IComponent)circuit;
            var equations = component.Equations;
            var variables = component.Variables;

            void SetState(IReadOnlyList <Complex> values)
            {
                variables.Zip(
                    values,
                    (variable, value) =>
                {
                    variable.Setter(value);
                    return(value);
                }).ToList();
            }

            var solvedState = solver.Solve(
                equations.Select(equation => new Func <IReadOnlyList <Complex>, Complex>(
                                     values =>
            {
                SetState(values);
                return(equation());
            })).ToList());

            SetState(solvedState);

            //TODO: Insert a separate method to set all variables in a circuit.
            //TODO: Finish solver class/interface.
            //TODO: Create a ground component.
            //TODO: Create unit tests.
        }
        public void AddingEventBackToQueueOnRetryExceptionInSolverAndIncrementRetryCounter()
        {
            var localDetection  = new Mock <ISituationDetection <AbstractFolderEvent> >();
            var remoteDetection = new Mock <ISituationDetection <AbstractFolderEvent> >();
            int numberOfSolver  = Enum.GetNames(typeof(SituationType)).Length;

            ISolver[,] solver = new ISolver[numberOfSolver, numberOfSolver];
            var retryProducer = new Mock <ISolver>();

            retryProducer.Setup(
                r =>
                r.Solve(
                    It.IsAny <IFileSystemInfo>(),
                    It.IsAny <IObjectId>(),
                    It.IsAny <ContentChangeType>(),
                    It.IsAny <ContentChangeType>())).Throws(new RetryException("reason"));
            solver[(int)SituationType.NOCHANGE, (int)SituationType.NOCHANGE] = retryProducer.Object;
            var mechanism = this.CreateMechanism(localDetection.Object, remoteDetection.Object, solver);

            localDetection.Setup(d => d.Analyse(this.storage.Object, It.IsAny <AbstractFolderEvent>())).Returns(SituationType.NOCHANGE);
            remoteDetection.Setup(d => d.Analyse(this.storage.Object, It.IsAny <AbstractFolderEvent>())).Returns(SituationType.NOCHANGE);
            var folderEvent = new FolderEvent(Mock.Of <IDirectoryInfo>(), Mock.Of <IFolder>())
            {
                Local = MetaDataChangeType.NONE, Remote = MetaDataChangeType.NONE
            };

            Assert.That(mechanism.Handle(folderEvent), Is.True);

            this.queue.Verify(q => q.AddEvent(folderEvent), Times.Once());
            Assert.That(folderEvent.RetryCount, Is.EqualTo(1));
        }
Example #25
0
 public LinearAnalyzer(IStructuralModel model, ISolver solver, IAnalyzerProvider provider)
 {
     this.model         = model;
     this.solver        = solver;
     this.linearSystems = solver.LinearSystems;
     this.provider      = provider;
 }
Example #26
0
 public ContinousSystem(IContinousModel model, ISolver solver, Vector initialState, double delay)
 {
     this.model        = model;
     this.solver       = solver;
     this.initialState = initialState;
     this.delay        = delay;
 }
Example #27
0
 public ProblemStructural(IStructuralModel model, ISolver solver)
 {
     this.model                   = model;
     this.linearSystems           = solver.LinearSystems;
     this.solver                  = solver;
     this.DirichletLoadsAssembler = new DirichletEquivalentLoadsStructural(stiffnessProvider);
 }
Example #28
0
            internal void Refine(ISolver <TSet> solver, TSet other)
            {
                if (!StackHelper.TryEnsureSufficientExecutionStack())
                {
                    StackHelper.CallOnEmptyStack(Refine, solver, other);
                    return;
                }

                TSet thisAndOther = solver.And(_set, other);

                if (!solver.IsEmpty(thisAndOther))
                {
                    // The sets overlap, now check if this is contained in other
                    TSet thisMinusOther = solver.And(_set, solver.Not(other));
                    if (!solver.IsEmpty(thisMinusOther))
                    {
                        // This is not contained in other, minterms may need to be split
                        if (_left is null)
                        {
                            Debug.Assert(_right is null);
                            _left  = new PartitionTree(thisAndOther);
                            _right = new PartitionTree(thisMinusOther);
                        }
                        else
                        {
                            Debug.Assert(_right is not null);
                            _left.Refine(solver, other);
                            _right.Refine(solver, other);
                        }
                    }
                }
            }
 public ProblemConvectionDiffusion2(Model model, ISolver solver)
 {
     this.model                   = model;
     this.linearSystems           = solver.LinearSystems;
     this.solver                  = solver;
     this.DirichletLoadsAssembler = new DirichletEquivalentLoadsStructural(conductivityProvider);
 }
Example #30
0
        static ISolver CreateSolver(IDictionary <string, string> options)
        {
            ISolver solver = null;

            if (options.ContainsKey("solver"))
            {
                string solverName = options["solver"];
                if (solverName == "brute")
                {
                    solver = new BruteSolver();
                }
                else if (solverName == "smart")
                {
                    solver = new SmartSolver();
                }
            }

            if (solver == null)
            {
                Console.WriteLine("Defaulting to brute solver");
                solver = new BruteSolver();
            }

            return(solver);
        }
Example #31
0
 public Task(ISolver Solver, SolverParams SolParams, ExtraParams Params)
 {
     this.Solver    = Solver;
     this.SolParams = SolParams;
     this.Params    = Params;
     //this.CurrentCorrelation = CurrentCorrelation;
 }
Example #32
0
 public FrisiaSyntaxRewriter(
     IList <ExpressionSyntax> conditions,
     SeparatedSyntaxList <ParameterSyntax> parameters,
     SymbolicMemoryState sms,
     ISolver solver,
     ILogger logger,
     uint loopIterations,
     bool visitUnsatPaths,
     bool visitTimeoutPaths,
     bool logFoundBranches,
     int timeout)
 {
     this.solver       = solver;
     SuccessConditions = new List <ExpressionSyntax>(conditions);
     FailureConditions = new List <ExpressionSyntax>(conditions);
     Parameters        = parameters;
     SMS               = new SymbolicMemoryState(sms);
     results           = new List <string[]>();
     LoopIterations    = loopIterations > 0 ? loopIterations : 1;
     VisitUnsatPaths   = visitUnsatPaths;
     VisitTimeoutPaths = visitTimeoutPaths;
     LogFoundBranches  = logFoundBranches;
     Timeout           = timeout;
     if (LogFoundBranches)
     {
         this.logger = logger;
     }
 }
Example #33
0
 public Builder(IStructuralModel model, ISolver solver, INonLinearProvider provider, int numIncrements) :
     base(model, solver, provider, numIncrements)
 {
     MaxIterationsPerIncrement     = 1000;
     NumIterationsForMatrixRebuild = 1;
     ResidualTolerance             = 1E-3;
 }
        public void AddingInteractionNeededEventToQueueOnInteractionNeededException()
        {
            var localDetection  = new Mock <ISituationDetection <AbstractFolderEvent> >();
            var remoteDetection = new Mock <ISituationDetection <AbstractFolderEvent> >();
            int numberOfSolver  = Enum.GetNames(typeof(SituationType)).Length;

            ISolver[,] solver = new ISolver[numberOfSolver, numberOfSolver];
            var interactionNeededProducer = new Mock <ISolver>();
            var exception = new InteractionNeededException("reason");

            interactionNeededProducer.Setup(
                r =>
                r.Solve(
                    It.IsAny <IFileSystemInfo>(),
                    It.IsAny <IObjectId>(),
                    It.IsAny <ContentChangeType>(),
                    It.IsAny <ContentChangeType>())).Throws(exception);
            solver[(int)SituationType.NOCHANGE, (int)SituationType.NOCHANGE] = interactionNeededProducer.Object;
            var mechanism = this.CreateMechanism(localDetection.Object, remoteDetection.Object, solver);

            localDetection.Setup(d => d.Analyse(this.storage.Object, It.IsAny <AbstractFolderEvent>())).Returns(SituationType.NOCHANGE);
            remoteDetection.Setup(d => d.Analyse(this.storage.Object, It.IsAny <AbstractFolderEvent>())).Returns(SituationType.NOCHANGE);
            var folderEvent = new FolderEvent(Mock.Of <IDirectoryInfo>(), Mock.Of <IFolder>())
            {
                Local = MetaDataChangeType.NONE, Remote = MetaDataChangeType.NONE
            };

            Assert.That(mechanism.Handle(folderEvent), Is.True);

            this.queue.Verify(q => q.AddEvent(It.Is <InteractionNeededEvent>(e => e.Exception == exception)), Times.Once());
            this.queue.VerifyThatNoOtherEventIsAddedThan <InteractionNeededEvent>();
        }
Example #35
0
        public NewtonSystem(QpProblem data, Variables initialPoint)
        {
            this.Q = data.Q;
            this.A = data.A;

            this.initialCholeskyFactor = this.Factorize(initialPoint);
        }
Example #36
0
 public Runner(ParserBase <TInput> parser, ISolver <TInput, TOutput> solver, PrinterBase <TOutput> printer, ScoreCalculatorBase <TInput, TOutput> calculator = null)
 {
     m_Parser     = parser;
     m_Solver     = solver;
     m_Printer    = printer;
     m_Calculator = calculator;
 }
Example #37
0
 public void AddSolver(ISolver solver)
 {
     Solvers = new List <ISolver>()
     {
         solver
     };
 }
        private static void SolveLinearStatic(Model model)
        {
            // Choose linear equation system solver
            var     solverBuilder = new SkylineSolver.Builder();
            ISolver solver        = solverBuilder.BuildSolver(model);

            // Structural problem provider
            var provider = new ProblemStructural(model, solver);

            // Linear static analysis
            var childAnalyzer  = new LinearAnalyzer(model, solver, provider);
            var parentAnalyzer = new StaticAnalyzer(model, solver, provider, childAnalyzer);

            // Run the analysis
            parentAnalyzer.Initialize();
            parentAnalyzer.Solve();

            // Logging displacement, strain, and stress fields.
            string outputDirectory = workingDirectory + "\\Plots";

            childAnalyzer.LogFactories[0] = new VtkLogFactory(model, outputDirectory)
            {
                LogDisplacements         = true,
                LogStrains               = true,
                LogStresses              = true,
                VonMisesStressCalculator = new PlaneStressVonMises()
            };

            // Run the analysis
            parentAnalyzer.BuildMatrices();
            parentAnalyzer.Initialize();
            parentAnalyzer.Solve();
        }
 public LocalObjectRenamedOrMovedRemoteObjectDeleted(
     ISession session,
     IMetaDataStorage storage,
     IFileTransmissionStorage transmissionStorage,
     TransmissionManager manager,
     ISolver secondSolver = null) : base(session, storage) {
         this.secondSolver = secondSolver ?? new LocalObjectAdded(session, storage, transmissionStorage, manager);
 }
Example #40
0
 public ArenaModel RunProblem(ArenaProblem problem, ISolver solver)
 {
     for (int i = 0; i < problem.Problem.sourceSeeds.Count; i++)
     {
         Run(problem, i, solver);
     }
     return new ArenaModel { Problems = Problems };
 }
Example #41
0
 public SolveRun(ICubeConfigurationGenerator generator, ISolver solver, IDisplay display, ICelebrator celebrator, int cubeSize)
 {
     m_display = display;
     m_celebrator = celebrator;
     m_solver = solver;
     m_generator = generator;
     m_cubeSize = cubeSize;
 }
 public async Task<IEnumerable<ushort>> ShowControllerDialogAsync(object context, ISolver solver,
     string generatorName, SkillTree tree)
 {
     var vm = new ControllerViewModel(solver, generatorName, tree, this);
     var view = new ControllerWindow();
     Task<IEnumerable<ushort>> task = null;
     await ShowDialogAsync(context, vm, view, () => task = vm.RunSolverAsync());
     return await task;
 }
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="CmisSync.Lib.Consumer.SituationSolver.LocalObjectRenamedRemoteObjectRenamed"/> class.
        /// </summary>
        /// <param name="session">Cmis session.</param>
        /// <param name="storage">Meta data storage.</param>
        /// <param name="changeChangeSolver">Fallback solver for local and remote change situation after renaming is done.</param>
        public LocalObjectRenamedRemoteObjectRenamed(
            ISession session,
            IMetaDataStorage storage,
            ISolver changeChangeSolver) : base(session, storage) {
            if (changeChangeSolver == null) {
                throw new ArgumentNullException("changeChangeSolver", "Given solver for the situation of local and remote object changed is null");
            }

            this.changeChangeSolver = changeChangeSolver;
        }
        public void Update(ISolver caller, SolverCommandResult state, SolverStatistics global)
        {
            if (global != null)
            {
                var d = global.DurationInSec;

                Console.WriteLine("\t{0:#,###,##0} nodes at {1:0.0} nodes/sec after {2:#} sec. Depth: {3}/{4}/{5} (Completed/Curr/Max)",
                    global.TotalNodes, global.TotalNodes / d, d, global.DepthCompleted, global.DepthCurrent, global.DepthMax);
            }
        }
Example #45
0
 public ArenaModel RunAllProblems(ISolver solver)
 {
     foreach (var arenaProblem in Problems)
     {
         Console.WriteLine(arenaProblem.Problem.id + " w=" + arenaProblem.Problem.width);
         var sw = Stopwatch.StartNew();
         RunProblem(arenaProblem, solver);
         Console.WriteLine(" " + sw.Elapsed);
     }
     return new ArenaModel { Problems = Problems, SolverName = solver.Name };
 }
Example #46
0
 public static void EvaluateSolver(ISolver solver, params int[] maps)
 {
     var ps = Problems.LoadProblems();
     if (maps.Length == 0)
         maps = Enumerable.Range(0, ps.Count).ToArray();
     var arena = new Arena(maps.Select(i => ps[i]).ToArray());
     ArenaModel res = arena.RunAllProblems(solver);
     File.WriteAllText("arena.json", JsonConvert.SerializeObject(res, Formatting.Indented));
     File.WriteAllText("solutions.json", JsonConvert.SerializeObject(GetSubmissions(res), Formatting.Indented));
     Approvals.Verify(res);
 }
 public TspViewModel(ISolver solver, Dispatcher dispatcher)
 {
     this.Nodes = new ObservableCollection<Node>();
     this.Edges = new Dictionary<int, Edge>();
     this.EdgeLineMap = new Dictionary<Edge, Line>();
     this.dispatcher = dispatcher;
     this.Solver = solver;
     this.Graphs = new ObservableCollection<TspGraph>();
     this.Graphs.Add(this.Solver.Graph);
     this.SubscribeToEvents();
 }
 private ISolver GetSolver(ISolver solver, AbstractSolverBuilder builder)
 {
     if (!IsNecessaryToCreateSolver(solver, builder)) return solver;
     if (_storageChanged[builder]) builder.SetGraph(_storage.GetNodeCollection());
     if (solver != null) solver.Solved -= OnSolved;
     solver = builder.GetResult();
     solver.Solved += OnSolved;
     _storageChanged[builder] = false;
     _optionsChanged[builder] = false;
     return solver;
 }
Example #49
0
 public BackPropagation(INetwork network, ITrainingSetProvider trainingSet,
     ISolver solver = null)
 {
     Network = network;
     TrainingSetProvider = trainingSet;
     CurrentEpoch = 0;
     MinError = 1e-6;
     MaxEpoch = 1e6;
     BatchSize = trainingSet.TrainInputs.Length;
     Solver = solver ?? new GD(network);
 }
Example #50
0
 private void solve (ISolver solver) {
     if (tree.SelectedNode == null) { return; }
     object tag = tree.SelectedNode.Tag;
     Chart chart = tag as Chart;
     if (chart == null) { return; }
     CalculatePlayArgs args = new CalculatePlayArgs();
     args.solver = solver;
     args.chart = chart;
     args.node = tree.SelectedNode;
     args.start_measure = (int)num_start_measure.Value;
     args.end_measure = (int)num_end_measure.Value;
     bg_worker.RunWorkerAsync(args);
 }
Example #51
0
 public HomeController(IKernel kernel, ISolver solver)
 {
     this.Kernel = kernel;
     this.Solver = solver;
     this.Solver.OnSolved += Solver_OnSolved;
     /*var v = CutModel;
     if (v.IsNull())
     {
         var cutModel = new CutModel();
         CreateTempStock(cutModel);
         CreateTempToCut(cutModel);
         CutModel = cutModel;
     }*/
 }
Example #52
0
 public void Run(ArenaProblem problem, int seedIndex, ISolver solver)
 {
     try
     {
         var prob = problem.Problem;
         var result = solver.Solve(prob.ToMap(prob.sourceSeeds[seedIndex]));
         problem.MapResults[seedIndex].Result = result;
         Console.Write(result.Score + " ");
     }
     catch (Exception exception)
     {
         throw new Exception($"problemId: {problem.Problem.id}, seed: {seedIndex}. {exception.Message}", exception);
     }
 }
Example #53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SyncMechanism"/> class.
        /// </summary>
        /// <param name="localSituation">Local situation.</param>
        /// <param name="remoteSituation">Remote situation.</param>
        /// <param name="queue">Sync event queue.</param>
        /// <param name="session">CMIS Session.</param>
        /// <param name="storage">Meta data storage.</param>
        /// <param name="transmissionStorage">File transmission storage.</param>
        /// <param name="activityListener">Active sync progress listener.</param>
        /// <param name="filters">Ignore filter.</param>
        /// <param name="solver">Solver for custom solver matrix.</param>
        public SyncMechanism(
            ISituationDetection<AbstractFolderEvent> localSituation,
            ISituationDetection<AbstractFolderEvent> remoteSituation,
            ISyncEventQueue queue,
            ISession session,
            IMetaDataStorage storage,
            IFileTransmissionStorage transmissionStorage,
            ActivityListenerAggregator activityListener,
            IFilterAggregator filters,
            ISolver[,] solver = null) : base(queue)
        {
            if (session == null) {
                throw new ArgumentNullException("session");
            }

            if (storage == null) {
                throw new ArgumentNullException("storage");
            }

            if (transmissionStorage == null) {
                throw new ArgumentNullException("transmissionStorage");
            }

            if (localSituation == null) {
                throw new ArgumentNullException("localSituation");
            }

            if (remoteSituation == null) {
                throw new ArgumentNullException("remoteSituation");
            }

            if (activityListener == null) {
                throw new ArgumentNullException("activityListener");
            }

            if (filters == null) {
                throw new ArgumentNullException("filters");
            }

            this.session = session;
            this.storage = storage;
            this.transmissionStorage = transmissionStorage;
            this.LocalSituation = localSituation;
            this.RemoteSituation = remoteSituation;
            this.activityListener = activityListener;
            this.filters = filters;
            this.Solver = solver == null ? this.CreateSolver() : solver;
        }
        public LocalObjectMovedRemoteObjectChanged(
            ISession session,
            IMetaDataStorage storage,
            ISolver renameChangeSolver,
            ISolver changeChangeSolver) : base(session, storage) {
            if (renameChangeSolver == null) {
                throw new ArgumentNullException("renameChangeSolver", "Given sitation solver for local rename and remote change is null");
            }

            if (changeChangeSolver == null) {
                throw new ArgumentNullException("changeChangeSolver", "Given situation solver for local and remote changes is null");
            }

            this.renameChangeSolver = renameChangeSolver;
            this.changeChangeSolver = changeChangeSolver;
        }
Example #55
0
 public Simulator(double deltatime, double durationtime,INetwork targetnetwork,ISolver solver,IRecord recorder)
 {
     deltaT = deltatime;
     durationT = durationtime;
     currentT = 0.0;
     t0 = currentT;
     network = targetnetwork;
     this.solver = solver;
     this.recorder = recorder;
     this.recorder.HostSimulator = this;
     runthread = null;
     hpause = new ManualResetEvent(true);
     hstop = new ManualResetEvent(false);
     isrunning = false;
     ispaused = false;
 }
        public LocalObjectChangedWithPWC(
            ISession session,
            IMetaDataStorage storage,
            IFileTransmissionStorage transmissionStorage,
            ITransmissionManager manager,
            ISolver folderOrFileContentUnchangedSolver) : base(session, storage, transmissionStorage) {
            if (folderOrFileContentUnchangedSolver == null) {
                throw new ArgumentNullException("folderOrFileContentUnchangedSolver", "Given solver for folder or unchanged file content situations is null");
            }

            if (!session.ArePrivateWorkingCopySupported()) {
                throw new ArgumentException("The given session does not support private working copies", "session");
            }

            this.folderOrFileContentUnchangedSolver = folderOrFileContentUnchangedSolver;
            this.transmissionManager = manager;
        }
        public ForewardsSubsetSolver(Level level)
            : base(level)
        {
            // Create a solver that won't try to create us recursively.
#if DEBUG_LOWer_BOUND
            solver = Solver.CreateInstance(SolverAlgorithm.BruteForce);
#else
            solver = Solver.CreateInstance(SolverAlgorithm.LowerBound);
#endif
            solver.Level = level;
            solver.CollectSolutions = false;
            solver.OptimizeMoves = false;
            solver.OptimizePushes = true;
            solver.CalculateDeadlocks = false;
            solver.Verbose = false;
            solver.Validate = false;
        }
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="CmisSync.Lib.Consumer.SituationSolver.PWC.LocalObjectChangedRemoteObjectChangedWithPWC"/> class.
        /// </summary>
        /// <param name="session">Cmis session.</param>
        /// <param name="storage">Meta data storage.</param>
        /// <param name="transmissionStorage">Transmission storage.</param>
        /// <param name="manager">Transmission manager.</param>
        /// <param name="localObjectChangedRemoteObjectChangedFallbackSolver">Local object changed remote object changed fallback solver.</param>
        public LocalObjectChangedRemoteObjectChangedWithPWC(
            ISession session,
            IMetaDataStorage storage,
            IFileTransmissionStorage transmissionStorage,
            TransmissionManager manager,
            ISolver localObjectChangedRemoteObjectChangedFallbackSolver) : base(session, storage, transmissionStorage)
        {
            if (localObjectChangedRemoteObjectChangedFallbackSolver == null) {
                throw new ArgumentNullException("localObjectChangedRemoteObjectChangedFallbackSolver", "Given fallback solver is null");
            }

            if (!session.ArePrivateWorkingCopySupported()) {
                throw new ArgumentException("Given session does not support pwc updates", "session");
            }

            this.fallbackSolver = localObjectChangedRemoteObjectChangedFallbackSolver;
            this.transmissionManager = manager;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CmisSync.Lib.Consumer.SituationSolver.PWC.LocalObjectAddedWithPWC"/> class.
        /// </summary>
        /// <param name="session">Cmis session.</param>
        /// <param name="storage">Meta data storage.</param>
        /// <param name="transmissionStorage">Transmission storage.</param>
        /// <param name="manager">Active activities manager.</param>
        /// <param name="localFolderOrEmptyFileAddedSolver">Local folder or empty file added solver.</param>
        public LocalObjectAddedWithPWC(
            ISession session,
            IMetaDataStorage storage,
            IFileTransmissionStorage transmissionStorage,
            ITransmissionManager manager,
            ISolver localFolderOrEmptyFileAddedSolver) : base(session, storage, transmissionStorage)
        {
            if (localFolderOrEmptyFileAddedSolver == null) {
                throw new ArgumentNullException("localFolderOrEmptyFileAddedSolver", "Given solver for locally added folders is null");
            }

            if (!session.ArePrivateWorkingCopySupported()) {
                throw new ArgumentException("Given session doesn't support private working copies", "session");
            }

            this.folderOrEmptyFileAddedSolver = localFolderOrEmptyFileAddedSolver;
            this.transmissionManager = manager;
        }
Example #60
0
        public Tool()
        {
            this.solver = null;

            SolverAlgorithm = SolverAlgorithm.BruteForce;
            ReuseSolver = true;
            Repetitions = 1;
            DeadlocksDirectory = null;
            CollectSolutions = true;
            CalculateDeadlocks = true;
            HardCodedDeadlocks = false;
            MaximumNodes = 40000000;
            InitialCapacity = 20000000;
            OptimizeMoves = true;
            OptimizePushes = true;
            DetectNoInfluencePushes = true;
            Validate = false;
            Verbose = true;
            Level = null;
        }