public FrameData(IGraphSolver <Position> solver, ICollection <Position> checkedPositions, double frameSeconds, double overallSeconds) { CheckedPositions = checkedPositions; State = solver.State; OpenCount = solver.OpenCount; ClosedCount = solver.ClosedCount; CurrentBestPath = solver.CurrentBestPath; Path = solver.Path; PathCost = solver.PathCost; FrameSeconds = frameSeconds; OverallSeconds = overallSeconds; }
/// <summary> /// Take a snapshot of the Solver state. /// </summary> /// <returns>The Solver state snapshot is returned.</returns> protected override byte[] SnapshotSolverState() { SolverState state = new SolverState(); state.iter = m_nIter; state.current_step = m_nCurrentStep; foreach (Blob <T> blob in m_colHistory) { state.history.Add(blob.ToProto()); } return(m_persist.SaveSolverState(state)); }
public virtual void Stop() { bool isSolverStopLocked = Monitor.TryEnter(solverStopLock, SOLVER_STOP_LOCK_TIMEOUT); try { #if DEBUG if (!isSolverStopLocked) { System.Diagnostics.Debug.WriteLine("Lock timeout with solver stop lock"); } #endif if (SolverState == SolverState.Running) { SolverState = SolverState.Stopping; } } finally { if (isSolverStopLocked) { Monitor.Exit(solverStopLock); } } if (delegatedSolver != null) { bool isDelegatedSolverLocked = Monitor.TryEnter(delegatedSolverLock, DELEGATED_SOLVER_LOCK_TIMEOUT); try { #if DEBUG if (!isDelegatedSolverLocked) { System.Diagnostics.Debug.WriteLine("Lock timeout with delegated solver lock"); } #endif if (delegatedSolver != null) { delegatedSolver.Stop(); } } finally { if (isDelegatedSolverLocked) { Monitor.Exit(delegatedSolverLock); } } } }
/// <summary> /// Restore the state of the Solver. /// </summary> /// <param name="rgState">Specifies the state of the Solver.</param> protected override void RestoreSolverState(byte[] rgState) { SolverState state = m_persist.LoadSolverState(rgState); m_nIter = state.iter; m_nCurrentStep = state.current_step; m_log.CHECK_EQ(state.history.Count, m_colHistory.Count, "Incorrect length of state history blobs."); m_log.WriteLine("SGDSolver: restoring state history."); for (int i = 0; i < m_colHistory.Count; i++) { m_colHistory[i].FromProto(state.history[i]); } }
/// <summary> 计算完成,开始后处理 </summary> private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { OnSdCalculationFinished(); AnsysSolver solver = _bcParameters.Solver; // if (e.Cancelled) // 判断是否是手动退出线程 { // 说明 // solver.State = SolverState.FailedInCs; } // 后处理 StringBuilder sb = new StringBuilder(); _PostProcessor = new PostProcessor(Model, solver); if (_PostProcessor.CheckFinishState(errorMessage: ref sb)) { SolverState ss = _PostProcessor.CheckOutputFiles(errorMessage: ref sb); if (ss == SolverState.Succeeded) { if (Options.DirectlyReport) { ReadAndShowResults(); } else { var res = MessageBox.Show(@"计算结束且成功,是否直接生成报告?", @"Congratulations", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); if (res == DialogResult.OK) { ReadAndShowResults(); } } } else if (ss == SolverState.FailedWithError) { var res = MessageBox.Show("Ansys 计算结束!\r\n" + sb.ToString(), @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { var res = MessageBox.Show("Ansys 计算过程未正常结束!\r\n" + sb.ToString(), @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary>Override; see base.</summary> public override ConstraintResult Process(SolverState state) { if (state.LastPlacedCell != null) { var i = AffectedCells.IndexOf(state.LastPlacedCell.Value); var v = state.LastPlacedValue; state.MarkImpossible(AffectedCells[((i + v) % AffectedCells.Length + AffectedCells.Length) % AffectedCells.Length], v); state.MarkImpossible(AffectedCells[((i - v) % AffectedCells.Length + AffectedCells.Length) % AffectedCells.Length], v); } else { for (var i = 0; i < AffectedCells.Length; i++) { state.MarkImpossible(AffectedCells[i], v => (i + v) % AffectedCells.Length == i); } } return(null); }
/// <summary> 开始计算 </summary> private void _bgw_Solver_DoWork(object sender, DoWorkEventArgs e) { try { BgwParameters para = e.Argument as BgwParameters; // _Solver.CalculationTimerElapsed += SolverOnCalculationTimerElapsed; // SolverState state = para.Solver.Execute( waitingSeconds: Options.WaitingSeconds, errorMessage: out para.ErrorMessage ); } catch (Exception ex) { e.Cancel = true; e.Result = ex; // ignored } }
public override ConstraintResult Process(SolverState state) { if (state.LastPlacedCell == null) { // The focus cell cannot be so large that it points outside the grid, // nor can it have a value that points at a cell that already contains something other than a 9 state.MarkImpossible(AffectedCells[0], v => v > AffectedCells.Length - 1 || state.IsImpossible(AffectedCells[v], 9)); } else if (state.LastPlacedCell.Value == AffectedCells[0]) { // The focus cell has been set, therefore place the 9 in the correct position state.MustBe(AffectedCells[state.LastPlacedValue], 9); for (var i = 1; i < AffectedCells.Length; i++) { if (i != state.LastPlacedValue) { state.MarkImpossible(AffectedCells[i], 9); } } } else if (AffectedCells.Contains(state.LastPlacedCell.Value)) { var index = AffectedCells.IndexOf(state.LastPlacedCell.Value); if (state.LastPlacedValue == 9) { // A 9 has been placed somewhere, therefore set the focus cell to the correct value // (This is the main difference with FindTheValueConstraint; it’s an optimization that assumes uniqueness) state.MustBe(AffectedCells[0], index); } else { // A value other than 9 has been placed somewhere, therefore the focus cell cannot point at it anymore state.MarkImpossible(AffectedCells[0], index); } } return(null); }
/// <summary> /// Restore a previously saved solver state. /// </summary> /// <param name="rgState">Specifies the solver state to restore.</param> protected override void RestoreSolverState(byte[] rgState) { SolverState state = m_persist.LoadSolverState(rgState, m_param.type); m_nIter = state.iter; m_nCurrentStep = state.current_step; m_nStart = state.start; m_nEnd = state.end; List <int> rgIndices = lbfgs_history_indices(m_nStart, m_nEnd, m_param.lbgfs_corrections); for (int i = 0; i < rgIndices.Count; i++) { int nIdx = rgIndices[i]; m_colBlobHistoryS[i].FromProto(state.history[nIdx]); m_colBlobHistoryY[i].FromProto(state.s_history[nIdx]); m_rgRhoHistory[i] = state.rho_history[i]; } m_blobGradients.FromProto(state.gradients); m_blobDirection.FromProto(state.direction); }
public virtual void Solve() { if (Coordinator == null) { throw new ApplicationException("The solver has no coordinator"); } try { SolverState = SolverState.Running; try { DoSolve(); } finally { SolverState = SolverState.NotRunning; } } catch (ThreadAbortException tax) { // Swallow this - it's only for when the stopping method doesn't work timeously Thread.ResetAbort(); } }
public void StartChoosingMoves() { SolverState = SolverState.CanChooseMoves; }
public override ConstraintResult Process(SolverState state) { throw new NotImplementedException(); }
public static Model?Solve(ClauseSet initialClauses, Variables variablesMap) { if (initialClauses == null) { throw new ArgumentNullException(nameof(initialClauses)); } if (variablesMap == null) { throw new ArgumentNullException(nameof(variablesMap)); } const int INITIAL_LEVEL = 0; var solverStack = ImmutableStack <SolverState> .Empty; var initialSolverState = new SolverState(initialClauses, variablesMap, INITIAL_LEVEL, true); solverStack = solverStack.Push(initialSolverState); while (!solverStack.IsEmpty) { solverStack = solverStack.Pop(out var currentState); #if PROGRESS_TRACE Trace.WriteLine($"Iteration depth: {currentState.Depth}"); #endif var clauses = currentState.Clauses; var variables = currentState.VariablesMap; if (isConsistentSetOfLiterals(clauses)) { #if PROGRESS_TRACE Trace.WriteLine("Found model..."); #endif return(new Model(0, generateModelValues(clauses, variables))); } if (hasEmptyClause(clauses)) { #if PROGRESS_TRACE Trace.WriteLine("Empty clause found. Backtracking..."); #endif continue; } var unitClauseRuleResult = propagateUnitClauses(clauses, variables); if (unitClauseRuleResult == ClauseSet.ClauseOperationResult.MinOneEmptyClausuleFound) { #if PROGRESS_TRACE Trace.WriteLine("Empty clause (after unit rule) found. Backtracking..."); #endif continue; } handlePureLiterals(clauses, variables); var chosenLiteral = chooseNewLiteral(clauses, variables); if (chosenLiteral == null) { if (hasEmptyClause(clauses)) { #if PROGRESS_TRACE Trace.WriteLine("Empty clause found. Backtracking..."); #endif continue; } #if PROGRESS_TRACE Trace.WriteLine("Found model..."); #endif return(new Model(0, generateModelValues(clauses, variables))); } #if PROGRESS_TRACE Trace.WriteLine($"Chosen literal {chosenLiteral.Name}"); #endif var newClauseNeg = clauses.CloneWithClause(new Clause(new List <Literal> { ~chosenLiteral })); var newClausePos = clauses.CloneWithClause(new Clause(new List <Literal> { chosenLiteral })); solverStack = solverStack.Push(new SolverState(newClauseNeg, variablesMap.Clone(), currentState.Depth + 1, true)); solverStack = solverStack.Push(new SolverState(newClausePos, variablesMap.Clone(), currentState.Depth + 1, true)); } return(null); }
private VoxelOptionSolver(VoxelVisualComponent component, SolverState state) { }
public void Stop() { SolverState = SolverState.Stopping; }
public static bool isLegalState(SolverState s) { return((s.p >= 0 && s.p <= 3) && (s.d >= 0 && s.d <= 3) && (s.p == 0 || s.p == 3 || s.p == s.d)); }
public virtual void Start() { if (Coordinator == null) { throw new ApplicationException("The solver has no coordinator"); } Initialize(); while (SolverState != SolverState.Stopping) { // Wait for the solver state to change: while ((SolverState != SolverState.CanChooseMoves) && (SolverState != SolverState.Stopping)) { Thread.Sleep(10); } bool replayingMoves = false; int currentTick = Game.Current.CurrentTurn.Tick; SolverState = SolverState.ChoosingMoves; try { if (GameToReplay != null && currentTick <= TickToReplayTo && GameToReplay.Turns[currentTick].TankActionsTakenAfterPreviousTurn != null) { replayingMoves = true; LogDebugMessage("Replaying saved moves on turn {0}", currentTick); TankActionSet tankActionSet = new TankActionSet(YourPlayerIndex, currentTick); TankAction[] tankActionsTaken = GameToReplay.Turns[currentTick].TankActionsTakenAfterPreviousTurn; for (int tNum = 0; tNum < Constants.TANKS_PER_PLAYER; tNum++) { Tank tank = You.Tanks[tNum]; TankAction actionToTake = tankActionsTaken[tank.Index]; tankActionSet.Actions[tNum] = actionToTake; } Coordinator.SetBestMoveSoFar(tankActionSet); } else { LogDebugMessage("Choosing moves on turn {0}", currentTick); #if DEBUG Stopwatch swatch = Stopwatch.StartNew(); #endif ChooseMoves(); #if DEBUG swatch.Stop(); LogDebugMessage("Finished choosing moves. Duration: {0}", swatch.Elapsed); #endif } } catch (Exception exc) { LogDebugError(exc, exc.Message); System.Diagnostics.Debug.WriteLine( "Error while choosing moves: {0}", exc); System.Diagnostics.Debug.WriteLine("Stack trace:"); System.Diagnostics.Debug.WriteLine(exc.StackTrace); } if (SolverState == SolverState.Stopping) { break; } SolverState = SolverState.Thinking; try { if (!replayingMoves) { LogDebugMessage("Thinking on turn {0}", currentTick); #if DEBUG Stopwatch swatch = Stopwatch.StartNew(); #endif Think(); // If this method returns due to finishing its work, then the next state can be set to WaitingToChooseMoves. // Otherwise it must return when the state is changed to CanChooseMoves or Stopping. #if DEBUG swatch.Stop(); LogDebugMessage("Finished thinking. Duration: {0}", swatch.Elapsed); #endif } } catch (Exception exc) { System.Diagnostics.Debug.WriteLine( "Error while thinking: {0}", exc); System.Diagnostics.Debug.WriteLine("Stack trace:"); System.Diagnostics.Debug.WriteLine(exc.StackTrace); } if (SolverState == SolverState.Stopping) { break; } if (SolverState != SolverState.CanChooseMoves) { SolverState = SolverState.WaitingToChooseMoves; // The SolverState setter will ignore this if in a CanChooseMoves state, // thus preventing a nasty race condition that would lead to an endless loop. } } SolverState = SolverState.Stopped; }