Ejemplo n.º 1
0
        /// <summary>
        /// Создание пошагового метода ветвей и границ
        /// </summary>
        /// <param name="graph">орг. граф</param>
        public BranchAndBound(Digraph graph)
        {
            // метод ветвей и границ для указанного графа
            Graph = graph;

            // переход в следующее состояние
            next = IterationState.Start;

            // создание пустого маршрута коммивояжера
            TsPath = new Digraph.Path(Graph);

            if (Graph.CountVertex() == 0)
            {
                // пустой маршрут
                // окончание метода
                next = IterationState.Stop;
            }
            else if (Graph.CountVertex() == 1)
            {
                // маршрут из одной вершины
                TsPath.Append(new Digraph.Edge(0, 0, 0));
                // окончание метода
                next = IterationState.Stop;
            }
            else if (Graph.CountVertex() == 2)
            {
                // маршрут из двух вершин
                TsPath.Append(new Digraph.Edge(0, 1, Graph[0, 1]));
                TsPath.Append(new Digraph.Edge(1, 0, Graph[1, 0]));
                // окончание метода
                next = IterationState.Stop;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Coroutine for iterating the tree. The leaves of each node are returned as we iterate towards the deepest level and then backward.
        /// </summary>
        /// <param name="rootNode">The node to start from.</param>
        /// <returns>The leaf values along the tree.</returns>
        public IEnumerator <T2> TreeEnumeratorCoroutine(Tree <T, T2> rootNode)
        {
            var list = new List <IterationState>
            {
                new IterationState {
                    Branch = rootNode, BranchIdx = 0
                }
            };

            while (list.Count > 0)
            {
                IterationState branch    = list[^ 1];
Ejemplo n.º 3
0
        public ActionResult ChangeIterationState(long iterationId, IterationState state)
        {
            using (var context = new TenantContext(WebSecurity.CurrentUserSubscriptionId))
            {
                var db = context.Database;

                Iteration iteration;
                if (!db.Iterations.TryGetById(iterationId, out iteration))
                {
                    //TODO: Log
                    return Json(false);
                }

                iteration.State = state;
                db.SaveChanges();

                return Json(true);
            }
        }
        private static string GetStateQueryValue(IterationState state)
        {
            switch (state)
            {
            case IterationState.Opened:
                return("opened");

            case IterationState.Upcoming:
                return("upcoming");

            case IterationState.Current:
                return("current");

            case IterationState.Closed:
                return("closed");

            case IterationState.All:
                return("all");

            default:
                throw new NotSupportedException($"State {state} is not supported");
            }
        }
Ejemplo n.º 5
0
        Act[] ReadActs()
        {
            List <Act> listAct = new List <Act>();

            for (int i = 0; i < dgvAct.Rows.Count - 1; i++)
            {
                DataGridViewRow r = dgvAct.Rows[i];
                string          mark = (string)(r.Cells["Название"] as DataGridViewCell).Value;
                float           durMin = 0, durMax = 0, costMin = 0, costMax = 0;
                object          val = (r.Cells["МинДлительность"] as DataGridViewCell).Value;
                if (val != null)
                {
                    durMin = (float)val;
                }
                val = (r.Cells["МаксДлительность"] as DataGridViewCell).Value;
                if (val != null)
                {
                    durMax = (float)val;
                }
                val = (r.Cells["МинСтоимость"] as DataGridViewCell).Value;
                if (val != null)
                {
                    costMin = (float)val;
                }
                val = (r.Cells["МаксСтоимость"] as DataGridViewCell).Value;
                if (val != null)
                {
                    costMax = (float)val;
                }
                string   prev = (string)(r.Cells["ПредРаботы"] as DataGridViewCell).Value;
                string[] arrPrev;
                if (prev != null)
                {
                    arrPrev = prev.Split(new char[] { ' ', ',' });
                }
                else
                {
                    arrPrev = new string[] { }
                };
                listAct.Add(new Act(mark, durMin, durMax, costMin, costMax, arrPrev));
            }
            return(listAct.ToArray());
        }

        void Calculate()
        {
            try
            {
                lbResult.Items.Clear();
                listArrState = new List <IterationState[]>();
                Act[] arrAct = ReadActs(), arrActAll = arrAct;
                an = new ActNet(arrAct);
                an.BuildActNet();
                an.SetMaxActCost();
                string strAn = an.ToString(), strAnOld = "";
                //while (strAn != strAnOld)
                {
                    an.CalcStaticTimeParams();
                    lbResult.Items.Add(an);
                    arrAct = an.critPath;
                    int      n = arrAct.Length + 1, m = arrAct.Length + n; // кол. ур. и пер.
                    ExMatrix mP = new ExMatrix(n, m);
                    ExMatrix mB = new ExMatrix(n, 1);
                    ExMatrix mC = new ExMatrix(1, m);
                    double   cCoeff = 0, sumDurMin = 0, sumDurMinB = 0;
                    for (int i = 0; i < arrAct.Length; i++)
                    {
                        mP.Elements[i, i] = 1;
                        mP.Elements[i, i + arrAct.Length] = 1;
                        mB.Elements[i, 0]             = arrAct[i].durMax - arrAct[i].durMin;
                        mP.Elements[arrAct.Length, i] = 1; // строка для Sum(dur)
                        mC.Elements[0, i]             = -arrAct[i].b;
                        sumDurMin  += arrAct[i].durMin;
                        sumDurMinB += arrAct[i].durMin * arrAct[i].b;
                        cCoeff     += arrAct[i].a;
                    }
                    mB.Elements[arrAct.Length, 0]     = float.Parse(tbTime.Text) - sumDurMin;
                    mP.Elements[arrAct.Length, m - 1] = 1;
                    cCoeff -= sumDurMinB;
                    ExMatrix[] arrMP = new ExMatrix[m];
                    for (int i = 0; i < arrMP.Length; i++)
                    {
                        arrMP[i] = new ExMatrix(n, 1);
                    }
                    for (int i = 0; i < n; i++)
                    {
                        for (int j = 0; j < m; j++)
                        {
                            arrMP[j].Elements[i, 0] = mP.Elements[i, j];
                        }
                    }
                    for (int i = 0; i < mC.N; i++)
                    {
                        mC.Elements[0, i] *= -1;
                    }
                    MsMethod method   = new MsMethod(arrMP, mB, mC, 0);
                    int[]    arrIndex = new int[n];
                    for (int i = 0; i < n; i++)
                    {
                        arrIndex[i] = arrAct.Length + i;
                    }
                    method.SetBasis(arrIndex);
                    while (method.DoIteration())
                    {
                        ;
                    }
                    listArrState.Add((IterationState[])method.states.ToArray(typeof(IterationState)));
                    IterationState stateLast = (IterationState)method.states[method.states.Count - 1];
                    for (int i = 0; i < arrAct.Length; i++)
                    {
                        arrAct[i].dur = (float)stateLast.GetVarValue(i) + arrAct[i].durMin;
                    }
                    an.CalcStaticTimeParams();
                    foreach (Act a in arrActAll)
                    {
                        if (a.TReserv <= a.durMax - a.dur)
                        {
                            a.dur += a.TReserv;
                            an.ShiftActTime(a.mark, 0);
                            an.CalcStaticTimeParams();
                        }
                        else
                        {
                            a.dur = a.durMax;
                            an.ShiftActTime(a.mark, 0);
                            an.CalcStaticTimeParams();
                        }
                    }
                    strAnOld = strAn;
                    strAn    = an.ToString();
                    an       = new ActNet(an, true);
                    lbResult.Items.Add(an);
                }
            }
            catch { }
        }

        void CalculateOptRes()
        {
            ArrayList listAn = new ArrayList();

            try
            {
                /*float Treal, Tdir = float.Parse(tbTime.Text);
                 * ActNet anCur = an;
                 * float[] arrRes = ReadRes();
                 * Treal = an.OptimizeTime(arrRes);
                 * while (Treal <= Tdir)
                 * {
                 *  Treal = float.MaxValue;
                 *  listAn.Add(anCur);
                 *  float[] arrCrit = anCur.GetCriterions();
                 *  ArrayList listCrit = new ArrayList(arrCrit);
                 *  listCrit.Sort();
                 *  listCrit.Reverse();
                 *  foreach (float crit in listCrit)
                 *  {
                 *      int i;
                 *      for (i = 0; i < arrCrit.Length; i++)
                 *          if (crit == arrCrit[i])
                 *              break;
                 *      float step = (float)dgvRes.Rows[i].Cells["Шаг"].Value;
                 *      anCur = new ActNet(anCur);
                 *      arrRes[i] -= step;
                 *      try
                 *      {
                 *          Treal = anCur.OptimizeTime(arrRes);
                 *          if (Treal > Tdir)
                 *              throw new Exception();
                 *          break;
                 *      }
                 *      catch
                 *      {
                 *          Treal = float.MaxValue;
                 *          arrRes[i] += step;
                 *      }
                 *  }
                 * }*/
            }
            catch { }
            //ActNet[] arrAn = (ActNet[])listAn.ToArray(typeof(ActNet));
            //lbResult.Items.Clear();
            //lbResult.Items.AddRange(arrAn);
        }

        void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            Calculate();
            if (tc.SelectedTab == tc.TabPages["tpOptRes"])
            {
                CalculateOptRes();
            }
            SetBitmaps();
        }

        void tc_TabIndexChanged(object sender, EventArgs e)
        {
            if (tc.SelectedTab == tc.TabPages["tpOptRes"])
            {
                CalculateOptRes();
            }
            SetBitmaps();
        }

        void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.None)
            {
                isBmpSizing = false;
                return;
            }
            if (isBmpSizing == false)
            {
                prevLocation = e.Location;
                isBmpSizing  = true;
                return;
            }
            int xDelta = e.Location.X - prevLocation.X;
            int yDelta = e.Location.Y - prevLocation.Y;

            prevLocation = e.Location;

            if (e.Button == MouseButtons.Left)
            {
                xDist      += xDelta;
                yAmplitude += yDelta;
                if (xDist > 100)
                {
                    xDist = 100;
                }
                if (xDist < 10)
                {
                    xDist = 10;
                }
                if (yAmplitude > 400)
                {
                    yAmplitude = 400;
                }
                if (yAmplitude < 10)
                {
                    yAmplitude = 10;
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                mult     += xDelta * 0.02f;
                fontSize += yDelta;
                if (mult < 0.5)
                {
                    mult = 0.5f;
                }
                if (mult > 5)
                {
                    mult = 5;
                }
                if (fontSize < 4)
                {
                    fontSize = 4;
                }
                if (fontSize > 25)
                {
                    fontSize = 25;
                }
                nodeDiam = 20 * fontSize / 9;
            }
            SetBitmaps();
        }

        void pbMain_SizeChanged(object sender, EventArgs e)
        {
            SetBitmaps();
        }

        void SetBitmaps()
        {
            try
            {
                if (tc.SelectedTab == tc.TabPages["tpData"])
                {
                    pbMain.Image = an.GetGraph(yAmplitude, xDist,
                                               mult, nodeDiam, fontSize);
                }
                else if (tc.SelectedTab == tc.TabPages["tpOptRes"])
                {
                    lbResult_SelectedValueChanged(null, null);
                }
            }
            catch { }
        }

        void lbResult_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                ActNet anSel = (ActNet)lbResult.SelectedItem;
                anSel.OptimizeTime(new float[] { });
                pbMain.Image = anSel.GetHuntDiagram(pbMain.Width, pbMain.Height);
                lbIter.Items.Clear();
                foreach (IterationState s in listArrState[lbResult.SelectedIndex - 1])
                {
                    lbIter.Items.Add(string.Format("F = {0}", s.GetFuncValue()));
                }
            }
            catch { }
        }

        void lbIter_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                wb.DocumentText =
                    listArrState[lbResult.SelectedIndex - 1][lbIter.SelectedIndex].GetSimplexTablePart();
            }
            catch { }
        }

        void tbTime_TextChanged(object sender, EventArgs e)
        {
            Calculate();
        }

        void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                /*saveFileDialog1.Filter = "Файлы отчетов|*.htm";
                 * if (saveFileDialog1.ShowDialog() != DialogResult.OK)
                 *  return;
                 * FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
                 * StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
                 * string s = "<P>Задача сетевого планирования проекта с учетом " +
                 *  "нескладируемых ресурсов при минимизации максимальных " +
                 *  "значений потребления ресурсов и ограничениях на сроки " +
                 *  "выполнения проекта и используемые ресурсы.</P>";
                 * s += "<P><IMG SRC = \"graph.bmp\"></IMG></P>";
                 * s += "<P>Количество ресурсов: " + nudRes.Value.ToString() + "</P>";
                 * s += "<P>Минимальное время завершения проекта: " +
                 *  an.OptimizeTime(ReadRes()).ToString() + "</P>";
                 * s += "<P><IMG SRC = \"huntrestime.bmp\"</IMG></P>";
                 * for (int i = 0; i < lbResult.Items.Count; i++)
                 * {
                 *  ActNet anCur = (ActNet)lbResult.Items[i];
                 *  s += "<P>" + anCur.ToString() + "</P>";
                 *  s += "<P><IMG SRC = \"iter" + i.ToString() + ".bmp\"></IMG></P>";
                 * }
                 * sw.Write(s);
                 * sw.Close();
                 *
                 * Bitmap bmp;
                 * bmp = an.GetGraph(yAmplitude, xDist, mult, nodeDiam, fontSize);
                 * bmp.Save("graph.bmp");
                 * bmp = an.GetHuntRes(600, 600);
                 * bmp.Save("huntrestime.bmp");
                 * for (int i = 0; i < lbResult.Items.Count; i++)
                 * {
                 *  ActNet anCur = (ActNet)lbResult.Items[i];
                 *  anCur.GetHuntRes(600, 600).Save("iter" + i.ToString() + ".bmp");
                 * }*/
            }
            catch { }
        }

        void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Автор: Васильев Д., группа АС-05-1");
        }

        void exampleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tbTime.Text = "10";
            dgvAct.Rows.Clear();
            dgvAct.Rows.Add(new object[] { "a", null, 2.0f, 5.0f, 1.0f, 6.0f });
            dgvAct.Rows.Add(new object[] { "b", null, 3.0f, 5.0f, 2.0f, 7.0f });
            dgvAct.Rows.Add(new object[] { "c", "a", 3.0f, 6.0f, 2.0f, 7.0f });
            dgvAct.Rows.Add(new object[] { "d", "b", 2.0f, 6.0f, 3.0f, 5.0f });
            dgvAct.Rows.Add(new object[] { "e", "b", 2.0f, 4.0f, 1.0f, 5.0f });
            dgvAct.Rows.Add(new object[] { "f", "d", 1.0f, 5.0f, 1.0f, 6.0f });


            Calculate();
            SetBitmaps();
        }
    }
Ejemplo n.º 6
0
        public bool MoveNext()
        {
            // если текущий индекс не находиться в конце списка
            if (index < iterations.Count)
            {
                // текущее изображения берется из списка уже
                // пройденных на итерациях изображений
                Current = iterations[index++];
                return true;
            }
            // иначе определение следующего изображения
            else
            {
                // определение действий на текущей итерациии
                switch (next)
                {
                    // остановка метода ветвей и границ
                    case IterationState.Stop:
                        {
                            return false;
                        }
                    // начало метода ветвей и границ
                    case IterationState.Start:
                        {
                            // иницилизация данных
                            dsu = new Dsu(Graph.CountVertex());
                            min = new Branch(float.PositiveInfinity, null);
                            matrix = new ReductionMatrix(Graph.Adjacency);
                            parent = new Branch(matrix.Reduce(), null);
                            tree = new TreeBranch(Graph, parent);

                            // создание и добавление нового изображения ветвления
                            Current = Painter.Drawing(tree);
                            iterations.Add(Current);
                            // перемещение текущего индекса на конец списка
                            index = iterations.Count;

                            // переход в следующее состояние - левое ветвление метода
                            next = IterationState.LeftBranching;
                            return true;
                        }
                    // левое ветвление метода ветвей и границ
                    case IterationState.LeftBranching:
                        {
                            // определение ребер с нулевой стоимостью
                            var zeroEdges = new List<Digraph.Edge>();
                            for (int i = 0; i < matrix.Size; i++)
                                for (int j = 0; j < matrix.Size; j++)
                                    if (matrix[i, j] == 0)
                                        zeroEdges.Add(new Digraph.Edge(i, j, matrix.MinInRow(i, j) + matrix.MinInColumn(j, i)));

                            // если нет ребер ветвления - нет маршрута коммивояжера
                            if (zeroEdges.Count == 0)
                            {
                                TsPath = new Digraph.Path(Graph);

                                // остановка метода ветвей и границ
                                next = IterationState.Stop;
                                return false;
                            }

                            // определение ребра ветвления - ребра с максимальным штрафом
                            edge = zeroEdges.OrderByDescending(e => e.Cost).ToList().First();

                            // создание левого потомка для данного родителя
                            left = new Branch(parent.LowerBound + edge.Cost,
                                new Digraph.Edge(-edge.Begin, -edge.End, float.PositiveInfinity));
                            // добавление в дерево ветвлений
                            tree.Add(parent, Branch.Direction.Left, left);

                            // создание и добавление нового изображения ветвления
                            Current = Painter.Drawing(tree);
                            iterations.Add(Current);
                            // перемещение текущего индекса на конец списка
                            index = iterations.Count;

                            // переход в следующее состояние - правое ветвление метода
                            next = IterationState.RightBranching;
                            return true;
                        }
                    // правое ветвление метода
                    case IterationState.RightBranching:
                        {
                            // исключение подмаршрутов для данного ребра
                            ExcludeSubRoute(matrix, dsu, edge);

                            // создание правого потомка для данного родителя
                            right = new Branch(parent.LowerBound + matrix.Reduce(),
                                new Digraph.Edge(edge.Begin, edge.End, Graph[edge.Begin, edge.End]));
                            // добавление в дерево ветвлений
                            tree.Add(parent, Branch.Direction.Right, right);

                            // создание и добавление нового изображения ветвления
                            Current = Painter.Drawing(tree);
                            iterations.Add(Current);
                            // перемещение текущего индекса на конец списка
                            index = iterations.Count;

                            // если размер матрицы достаточно мал
                            if (matrix.RealSize == 2)
                            {
                                // переход в состояние - малый размер матрицы
                                next = IterationState.LittleMatrix;
                                return true;
                            }

                            // выбор новой родительской вершины из еще не подвергшихся ветвлению
                            parent = tree.GetNotGoBranches().OrderBy(b => b.LowerBound).ToList().First();

                            // проверка на нахождения минимального ветвления и остановки
                            if (min.LowerBound <= parent.LowerBound)
                            {
                                // формирование маршрута коммивояжера
                                TsPath = tree.CreatePathFromBranch(min);
                                // остановка метода
                                next = IterationState.Stop;
                                return false;
                            }

                            // корректировка матрицы для данного ветвления и редуцирование
                            if (parent != right)
                            {
                                // новые непересекающиеся множества вершин
                                dsu = new Dsu(Graph.CountVertex());
                                // исходная редуцированная матрица
                                matrix = new ReductionMatrix(Graph.Adjacency);
                                // получение текущих вершин для данного ветвления
                                var currentPath = tree.GetEdgesBranching(parent);

                                // исключение всех подмаршрутов
                                foreach (var e in currentPath)
                                    ExcludeSubRoute(matrix, dsu, e);

                                // редуцирование матрицы
                                matrix.Reduce();
                            }

                            // следующая итерация методав ветвей и границ - левое ветвление
                            next = IterationState.LeftBranching;
                            return true;
                        }
                    // малый рамзер матрицы, включение ребер в маршрут
                    case IterationState.LittleMatrix:
                        {
                            // новый родитель
                            parent = right;
                            for (int i = 0; i < matrix.Size && countAdeddEdgeFromMatrix != 1; i++)
                                for (int j = 0; j < matrix.Size && countAdeddEdgeFromMatrix != 1; j++)
                                {
                                    if (matrix[i, j] == 0)
                                    {
                                        // исключение данного ребра из матрицы
                                        matrix[i, j] = float.PositiveInfinity;
                                        // создание и добавление правого ветвления к родителю
                                        right = new Branch(parent.LowerBound, new Digraph.Edge(i, j, Graph[i, j]));
                                        tree.Add(parent, Branch.Direction.Right, right);
                                        // новый родитель
                                        parent = right;
                                        // продолжать включать ребра в маршрут на следующей итерации
                                        countAdeddEdgeFromMatrix++;
                                    }
                                }

                            // если следующая итерация та же
                            if (countAdeddEdgeFromMatrix == 1)
                            {
                                // создание и добавление нового изображения ветвления
                                Current = Painter.Drawing(tree);
                                iterations.Add(Current);
                                // перемещение текущего индекса на конец списка
                                index = iterations.Count;
                                // на следующей итерации будет включено второе ребро
                                countAdeddEdgeFromMatrix++;
                                return true;
                            }
                            else
                                // все ребра включены для данной матрицы
                                countAdeddEdgeFromMatrix = 0;

                            // иначе проверка на новое минимальное ветвление
                            if (parent.LowerBound < min.LowerBound)
                                min = parent;

                            // создание и добавление нового изображения ветвления
                            Current = Painter.Drawing(tree);
                            iterations.Add(Current);
                            // перемещение текущего индекса на конец списка
                            index = iterations.Count;

                            // выбор новой родительской вершины из еще не подвергшихся ветвлению
                            parent = tree.GetNotGoBranches().OrderBy(b => b.LowerBound).ToList().First();

                            // проверка на нахождения минимального ветвления и остановки
                            if (min.LowerBound <= parent.LowerBound)
                            {
                                // формирование маршрута коммивояжера
                                TsPath = tree.CreatePathFromBranch(min);
                                // остановка метода
                                next = IterationState.Stop;
                                return false;
                            }

                            // корректировка матрицы для данного ветвления и редуцирование
                            if (parent != right)
                            {
                                // новые непересекающиеся множества вершин
                                dsu = new Dsu(Graph.CountVertex());
                                // исходная редуцированная матрица
                                matrix = new ReductionMatrix(Graph.Adjacency);
                                // получение текущих вершин для данного ветвления
                                var currentPath = tree.GetEdgesBranching(parent);

                                // исключение всех подмаршрутов
                                foreach (var e in currentPath)
                                    ExcludeSubRoute(matrix, dsu, e);

                                // редуцирование матрицы
                                matrix.Reduce();
                            }

                            // следующая итерация методав ветвей и границ - левое ветвление
                            next = IterationState.LeftBranching;
                            return true;
                        }
                    default:
                        return false;
                }
            }
        }
Ejemplo n.º 7
0
        private ISubGridCellPassesDataSegment LocateNextSubGridSegmentInIteration()
        {
            ISubGridCellPassesDataSegment result = null;

            if (IterationState.SubGrid == null)
            {
                Log.LogCritical("No sub grid node assigned to iteration state");
                return(null);
            }

            while (IterationState.NextSegment())
            {
                var segmentInfo = IterationState.Directory.SegmentDirectory[IterationState.Idx];

                if (segmentInfo.Segment != null)
                {
                    result = segmentInfo.Segment;
                }

                // If there is no segment present in the cache then it can't be dirty, so is
                // not a candidate to be returned by the iterator
                // Similarly if the caller is only interested in segments that are present in the cache,
                // we do not need to read it from the persistent store
                if (!ReturnDirtyOnly && !ReturnCachedItemsOnly)
                {
                    // This additional check to determine if the segment is defined
                    // is necessary to check if an earlier thread through this code has
                    // already allocated the new segment
                    if (segmentInfo.Segment == null)
                    {
                        IterationState.SubGrid.AllocateSegment(segmentInfo);
                    }

                    result = segmentInfo.Segment;

                    if (result == null)
                    {
                        throw new TRexSubGridProcessingException("IterationState.SubGrid.Cells.AllocateSegment failed to create a new segment");
                    }
                }

                if (result != null)
                {
                    if (!result.Dirty && ReturnDirtyOnly)
                    {
                        // The segment is not dirty, and the iterator has been instructed only to return
                        // dirty segments, so ignore this one
                        result = null;
                        continue;
                    }

                    if (!result.Dirty && !ReturnCachedItemsOnly &&
                        (RetrieveAllPasses && !result.HasAllPasses || RetrieveLatestData && !result.HasLatestData))
                    {
                        var fsResult = ((IServerSubGridTree)IterationState.SubGrid.Owner).LoadLeafSubGridSegment
                                           (StorageProxyForSubGridSegments,
                                           new SubGridCellAddress(IterationState.SubGrid.OriginX, IterationState.SubGrid.OriginY),
                                           RetrieveLatestData, RetrieveAllPasses,
                                           IterationState.SubGrid,
                                           result);

                        if (fsResult == FileSystemErrorStatus.OK)
                        {
                            // TRex has no separate cache - it is in Ignite
                        }
                        else
                        {
                            // TRex has no separate cache - it is in Ignite

                            // Segment failed to be loaded. Multiple messages will have been posted to the log.
                            // Move to the next item in the iteration

                            // Specific FS failures indicate corruption in the data store that should preclude further iteration and
                            // processir of the contents of this sub grid. These conditions result in the sub grid being blacklisted
                            // and the iterator returning no further information for this subgrid
                            if (fsResult == FileSystemErrorStatus.GranuleDoesNotExist)
                            {
                                SegmentIterationBlackListed = true;
                                Log.LogWarning($"Black listing segment iteration due to file system failure {fsResult} for sub grid {IterationState.SubGrid.Moniker()}");
                            }

                            result = null;
                            continue;
                        }
                    }
                }

                if (result != null) // We have a candidate to return as the next item in the iteration
                {
                    break;
                }
            }
            return(result);
        }