Beispiel #1
0
   internal static void PopulateByRow (IMPModeler  model,
                                       INumVar[][] var,
                                       IRange[][]  rng) {
      //  First define the variables, three continuous and one integer
      double[]        xlb = {0.0, 0.0, 0.0, 2.0};
      double[]        xub = {40.0, System.Double.MaxValue,
                                   System.Double.MaxValue, 3.0};
      NumVarType[] xt  = {NumVarType.Float, NumVarType.Float,
                          NumVarType.Float, NumVarType.Int};
      INumVar[]     x  = model.NumVarArray(4, xlb, xub, xt);
      var[0] = x;

      // Objective Function:  maximize x0 + 2*x1 + 3*x2 + x3
      double[] objvals = {1.0, 2.0, 3.0, 1.0};
      model.AddMaximize(model.ScalProd(x, objvals));

      // Three constraints
      rng[0] = new IRange[3];
      // - x0 + x1 + x2 + 10*x3 <= 20
      rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]),
                                        model.Prod( 1.0, x[1]),
                                        model.Prod( 1.0, x[2]),
                                        model.Prod(10.0, x[3])), 20.0);
      // x0 - 3*x1 + x2 <= 30
      rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, x[0]),
                                        model.Prod(-3.0, x[1]),
                                        model.Prod( 1.0, x[2])), 30.0);
      // x1 - 3.5*x3 = 0
      rng[0][2] = model.AddEq(model.Sum(model.Prod( 1.0, x[1]),
                                        model.Prod(-3.5, x[3])), 0.0);
   }
Beispiel #2
0
    // Step 7
    public static void Main(string[] args)
    {
        if ( args.Length != 1 || args[0].ToCharArray()[0] != '-' ) {
         Usage();
         return;
          }

          try {
        //Step 3

         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];

        // Step 8

        // Step 11

        // Step 9

        // Step 10

         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
          }
    }
 public Match(string content, IRange range)
 {
     Contract.Requires(content != null);
     Contract.Requires(range != null);
     Content = content;
     Range = range;
 }
 public override void Setup(IRange range)
 {
     base.Setup(range);
     builder.Setup(range);
     foreach (var decorator in decorators)
         decorator.Setup(range);
 }
        public override Cell ExtractExcelCellProperty(IRange excelCell)
        {
            Cell cell = ExcelReader.ExtractExcelCellProperty(excelCell);

              cell.Borders = GetBorders(excelCell);
              return cell;
        }
        public override Cell ExtractExcelCellProperty(IRange excelCell)
        {
            Cell cell = ExcelReader.ExtractExcelCellProperty(excelCell);

              cell.TextColor = System.Drawing.ColorTranslator.FromOle(excelCell.Font.OleColor);
              return cell;
        }
Beispiel #7
0
 public IEnumerable<Month> MonthsOverAvailableCapacity(IRange<Month> months)
 {
     return months.Collect( month =>
       {
     return IsOverCapacity(month);
       });
 }
Beispiel #8
0
    internal static INumVar[] populateByRow(IMPModeler model,
                                           IRange[]     row)
    {
        double[]  lb = {0.0, 0.0, 0.0};
          double[]  ub = {40.0, System.Double.MaxValue, System.Double.MaxValue};
          INumVar[] x  = model.NumVarArray(3, lb, ub);

          // - x0 +   x1 + x2 <= 20
          //   x0 - 3*x1 + x2 <= 30
          double[][] val = {new double[]{-1.0,  1.0,  1.0},
                        new double[]{ 1.0, -3.0,  1.0}};
          row[0] = model.AddLe(model.ScalProd(val[0], x), 20.0);
          row[1] = model.AddLe(model.ScalProd(val[1], x), 30.0);

          // x0*x0 + x1*x1 + x2*x2 <= 1.0
          row[2] = model.AddLe(model.Sum(model.Prod(x[0], x[0]),
                                     model.Prod(x[1], x[1]),
                                     model.Prod(x[2], x[2])), 1.0);

          // Q = 0.5 ( 33*x0*x0 + 22*x1*x1 + 11*x2*x2 - 12*x0*x1 - 23*x1*x2 )
          INumExpr x00 = model.Prod( 33.0, x[0], x[0]);
          INumExpr x11 = model.Prod( 22.0, x[1], x[1]);
          INumExpr x22 = model.Prod( 11.0, x[2], x[2]);
          INumExpr x01 = model.Prod(-12.0, x[0], x[1]);
          INumExpr x12 = model.Prod(-23.0, x[1], x[2]);
          INumExpr Q   = model.Prod(0.5, model.Sum(x00, x11, x22, x01, x12));

          // maximize x0 + 2*x1 + 3*x2 + Q
          double[] objvals = {1.0, 2.0, 3.0};
          model.Add(model.Maximize(model.Diff(model.ScalProd(x, objvals), Q)));

          return x;
    }
Beispiel #9
0
    public static void Main(string[] args)
    {
        try {
         Cplex   cplex = new Cplex();
         IRange[]  row = new IRange[3];
         INumVar[] var = populateByRow(cplex, row);

         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(var);
            double[] slack = cplex.GetSlacks(row);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            int ncols = x.Length;
            for (int j = 0; j < ncols; ++j)
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j]);

            int nrows = slack.Length;
            for (int i = 0; i < nrows; ++i)
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i]);

            cplex.ExportModel("qcpex1.lp");
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
          }
    }
        public void SetUp()
        {
            var rangesInWorksheet = new IRange[3][];
              for (int i = 0; i < rangesInWorksheet.Length; i++)
              {
            rangesInWorksheet[i] = A.CollectionOfFake<IRange>(4).ToArray();
            for (int j = 0; j < rangesInWorksheet[i].Length; j++)
            {
              A.CallTo(() => rangesInWorksheet[i][j].Text).Returns(string.Format("{0} {1}", i+1, j+1));
            }
              }

              var range = A.Fake<IRange>();
              for (int i = 0; i < rangesInWorksheet.Length; i++)
              {
            for (int j = 0; j < rangesInWorksheet[i].Length; j++)
            {
              A.CallTo(() => range[i+1, j+1]).Returns(rangesInWorksheet[i][j]);
            }
              }

              _worksheet = A.Fake<IWorksheet>();
              A.CallTo(() => _worksheet.Name).Returns("WorksheetName");
              A.CallTo(() => _worksheet.Cells).Returns(range);

              _sut = ExcelReaderFactory.CreateExcelReader();
        }
Beispiel #11
0
 public virtual void Setup(IRange range)
 {
     Result = null;
     Range = range;
     isBuild = false;
     isSetup = true;
 }
        internal static bool Includes(IRange range, IRange maybeIncludedRange)
        {
            Contract.Requires(range != null);
            Contract.Requires(maybeIncludedRange != null);

            return range.Start <= maybeIncludedRange.Start && maybeIncludedRange.End <= range.End;
        }
Beispiel #13
0
   public static void Main(string[] args) {
      if ( args.Length != 1 || args[0].ToCharArray()[0] != '-' ) {
         Usage();
         return;
      }

      try {
         // Create the modeler/solver object
         Cplex cplex = new Cplex();

         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];

         // Evaluate command line option and call appropriate populate method.
         // The created ranges and variables are returned as element 0 of arrays
         // var and rng.
         switch ( args[0].ToCharArray()[1] ) {
         case 'r': PopulateByRow(cplex, var, rng);
                   break;
         case 'c': PopulateByColumn(cplex, var, rng);
                   break;
         case 'n': PopulateByNonzero(cplex, var, rng);
                   break;
         default:  Usage();
                   return;
         }

         // write model to file
         cplex.ExportModel("lpex1.lp");

         // solve the model and display the solution if one was found
         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(var[0]);
            double[] dj    = cplex.GetReducedCosts(var[0]);
            double[] pi    = cplex.GetDuals(rng[0]);
            double[] slack = cplex.GetSlacks(rng[0]);

            cplex.Output().WriteLine("Solution status = " + cplex.GetStatus());
            cplex.Output().WriteLine("Solution value  = " + cplex.ObjValue);

            int nvars = x.Length;
            for (int j = 0; j < nvars; ++j) {
               cplex.Output().WriteLine("Variable   " + j +
                                        ": Value = " + x[j] +
                                        " Reduced cost = " + dj[j]);
            }

            int ncons = slack.Length;
            for (int i = 0; i < ncons; ++i) {
               cplex.Output().WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i] +
                                        " Pi = " + pi[i]);
            }
         }
         cplex.End();
      }
      catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
      }
   }
        internal static bool Intersects(IRange range1, IRange range2)
        {
            Contract.Requires(range1 != null);
            Contract.Requires(range2 != null);

            return range2.End > range1.Start && range1.End > range2.Start;
        }
 public Column(IRange constraint, double constrCoef)
 {
     this.objCoef = 0;
     this.objCoefSet = false;
     this.column = new GRBColumn();
     this.column.AddTerm(constrCoef, constraint.GetConstr());
 }
        public IRange OriginalToModifiedRange(IRange originalRange)
        {
            Contract.Requires(originalRange != null);
            Contract.Requires(originalRange.Start >= 0);
            Contract.Requires(originalRange.Start <= originalRange.End);
            Contract.Requires(originalRange.End <= OriginalContent.Length);

            int start = originalRange.Start;
            int end = originalRange.End;

            foreach(Change change in changes){
                int oldStart = start;
                if(change.Range.End <= start){
                    start += change.LengthDifference;
                }
                if(change.Range.End <= end){
                    end += change.LengthDifference;
                    System.Diagnostics.Trace.WriteLineIf(change.Range.End > oldStart,
                        "Warning: text was changed overlapping with the range which had been looked up: " + originalRange + " change: " + change);
                }
                else if(change.Range.Start < end)
                {
                    end = Math.Min(end, change.Range.End);
                    System.Diagnostics.Trace.WriteLine(
                        "Warning: text was changed inside the range which had been looked up: " + originalRange + " change: " + change);
                }
            }

            return new Range(start, start + originalRange.Length);
        }
Beispiel #17
0
   public static void Main(string[] args) {
      try {
         Cplex cplex = new Cplex();

         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];

         PopulateByRow(cplex, var, rng);

         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(var[0]);
            double[] slack = cplex.GetSlacks(rng[0]);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            for (int j = 0; j < x.Length; ++j) {
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j]);
            }

            for (int i = 0; i < slack.Length; ++i) {
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i]);
            }
         }

         cplex.ExportModel("mipex1.lp");
         cplex.End();
      }
      catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception caught '" + e + "' caught");
      }
   }
 private string TryFormatAsRange(SimpleExpression expression, IRange range, string op)
 {
     return (range != null)
                ?
                    string.Format("{0} {1} {2}", FormatObject(expression.LeftOperand, expression.RightOperand), op, FormatRange(range, expression.LeftOperand))
                :
                    null;
 }
 void AddInternal(IRange range)
 {
     var min = double.IsNaN(range.Min) ? Min : range.Min;
     var max = double.IsNaN(range.Max) ? Max : range.Max;
     var realMin = double.IsNaN(Min) ? min : Math.Min(Min, min);
     var realMax = double.IsNaN(Max) ? max : Math.Max(Max, max);
     Update(realMin, realMax);
 }
        protected override void ReplaceRawRange(IRange range, string replacement, Format format)
        {
            System.Diagnostics.Trace.Assert(range.Start >= 0);
            System.Diagnostics.Trace.Assert(range.End <= TextBox.TextLength);

            SelectRawRange(range, format);
            TextBox.SelectedText = replacement;
        }
        private Dictionary<Cell.BorderPositionEnum, BorderInformation> GetBorders(IRange excelCell)
        {
            var borders = new Dictionary<Cell.BorderPositionEnum, BorderInformation>();
              borders[Cell.BorderPositionEnum.Left] = GetBorderInformation(excelCell.Borders[Cell.BorderPositionEnum.Left]);
              borders[Cell.BorderPositionEnum.Top] = GetBorderInformation(excelCell.Borders[Cell.BorderPositionEnum.Top]);
              borders[Cell.BorderPositionEnum.Right] = GetBorderInformation(excelCell.Borders[Cell.BorderPositionEnum.Right]);
              borders[Cell.BorderPositionEnum.Bottom] = GetBorderInformation(excelCell.Borders[Cell.BorderPositionEnum.Bottom]);

              return borders;
        }
Beispiel #22
0
    public static void Main(string[] args)
    {
        try {
         Cplex cplex = new Cplex();

         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];

         PopulateByRow(cplex, var, rng);

         Cplex.BasisStatus[] cstat = {
            Cplex.BasisStatus.AtUpper,
            Cplex.BasisStatus.Basic,
            Cplex.BasisStatus.Basic
         };
         Cplex.BasisStatus[] rstat = {
            Cplex.BasisStatus.AtLower,
            Cplex.BasisStatus.AtLower
         };
         cplex.SetBasisStatuses(var[0], cstat, rng[0], rstat);

         if ( cplex.Solve() ) {
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            System.Console.WriteLine("Iteration count = " + cplex.Niterations);

            double[] x     = cplex.GetValues(var[0]);
            double[] dj    = cplex.GetReducedCosts(var[0]);
            double[] pi    = cplex.GetDuals(rng[0]);
            double[] slack = cplex.GetSlacks(rng[0]);

            int nvars = x.Length;
            for (int j = 0; j < nvars; ++j) {
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j] +
                                        " Reduced cost = " + dj[j]);
            }

            int ncons = slack.Length;
            for (int i = 0; i < ncons; ++i) {
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i] +
                                        " Pi = " + pi[i]);
            }
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
    }
Beispiel #23
0
    public static void Main(string[] args)
    {
        try {
         // create CPLEX optimizer/modeler and turn off presolve to make
         // the output more interesting
         Cplex cplex = new Cplex();
         cplex.SetParam(Cplex.Param.Preprocessing.Presolve, false);

         // build model
         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];
         PopulateByRow (cplex, var, rng);

         // setup branch priorities
         INumVar[] ordvar = {var[0][1], var[0][3]};
         int[]     ordpri = {8, 7};
         cplex.SetPriorities (ordvar, ordpri);

         // setup branch directions
         cplex.SetDirection(ordvar[0], Cplex.BranchDirection.Up);
         cplex.SetDirection(ordvar[1], Cplex.BranchDirection.Down);

         // write priority order to file
         cplex.WriteOrder("mipex3.ord");

         // optimize and output solution information
         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(var[0]);
            double[] slack = cplex.GetSlacks(rng[0]);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            for (int j = 0; j < x.Length; ++j) {
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j]);
            }

            for (int i = 0; i < slack.Length; ++i) {
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i]);
            }
         }
         cplex.ExportModel("mipex3.lp");
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
          System.Console.WriteLine("Concert exception caught: " + e);
          }
    }
        public override Cell ExtractExcelCellProperty(IRange excelCell)
        {
            Cell cell = ExcelReader.ExtractExcelCellProperty(excelCell);
              cell.TextEmphasis = new List<Cell.EmphasisEnum>();

              if (excelCell.Font.Italic)
              {
            cell.TextEmphasis.Add(Cell.EmphasisEnum.Italic);
              }
              if (excelCell.Font.Bold)
              {
            cell.TextEmphasis.Add(Cell.EmphasisEnum.Bold);
              }
              return cell;
        }
Beispiel #25
0
   public static void Main(string[] args)
   {
      try {
         // setup files to transfer model to server
         string mfile = "Model.dat";
         string sfile = "Solution.dat";


         // build model
         INumVar[][] var = new INumVar[1][];
         IRange[][]  rng = new IRange[1][];

         CplexModeler model = new CplexModeler();
         PopulateByRow(model, var, rng);

         FileStream mstream = new FileStream(mfile, FileMode.Create);
         BinaryFormatter formatter = new BinaryFormatter ();
         formatter.Serialize(mstream, new ModelData(model, var[0]));
         mstream.Close();

         // start server
         Server server = new Server(mfile, sfile);

         SolutionData sol = null;
         FileStream sstream = new FileStream(sfile, FileMode.Open);
         sol = (SolutionData) formatter.Deserialize(sstream);
         sstream.Close();

         System.Console.WriteLine("Solution status = " + sol.status);

         if ( sol.status.Equals(Cplex.CplexStatus.Optimal) ) {
            System.Console.WriteLine("Solution value = " + sol.obj);
            int ncols = var[0].Length;
            for (int j = 0; j < ncols; ++j)
               System.Console.WriteLine("Variable " + j + ": Value = " + sol.vals[j]);
         }

      }
      catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
      }
      catch (System.Exception t) {
         System.Console.WriteLine("terminating due to exception " + t);
      }
   }
Beispiel #26
0
        public CronExpression(IRange nanoseconds, IRange microseconds, IRange milliseconds, IRange seconds, IRange minutes, IRange hours, IDayRange daysOfMonth, IRange months, IDayRange daysOfWeek, IRange years, TimeSpan offset)
        {
            if (daysOfMonth != null && daysOfWeek != null)
            {
                throw new NotSupportedException();
            }

            _nanoseconds = nanoseconds;
            _microseconds = microseconds;
            _milliseconds = milliseconds;
            _seconds = seconds;
            _minutes = minutes;
            _hours = hours;
            _days = daysOfMonth ?? daysOfWeek;
            _months = months;
            _years = years;
            _offset = offset;
        }
Beispiel #27
0
 internal static void Report1(Cplex cutSolver,
                              System.Collections.ArrayList Cut,
                              IRange[] Fill) {
    System.Console.WriteLine();
    System.Console.WriteLine("Using " + cutSolver.ObjValue + " rolls");
  
    System.Console.WriteLine();
    for (int j = 0; j < Cut.Count; j++) {
       System.Console.WriteLine("  Cut" + j + " = " +
                                cutSolver.GetValue((INumVar)Cut[j]));
    }
    System.Console.WriteLine();
    
    for (int i = 0; i < Fill.Length; i++) 
       System.Console.WriteLine("  Fill" + i + " = " + 
                                cutSolver.GetDual(Fill[i]));
    System.Console.WriteLine();
 }
Beispiel #28
0
 internal static void PopulateByRow(IMPModeler  model,
                                    INumVar[][] var,
                                    IRange[][]  rng) {
    double[] lb = {0.0, 0.0, 0.0};
    double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue};
    var[0] = model.NumVarArray(3, lb, ub);
  
    double[] objvals = {1.0, 2.0, 3.0};
    model.AddMaximize(model.ScalProd(var[0], objvals));
  
    rng[0] = new IRange[2];
    rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, var[0][0]),
                                      model.Prod( 1.0, var[0][1]),
                                      model.Prod( 1.0, var[0][2])), 20.0);
    rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, var[0][0]),
                                      model.Prod(-3.0, var[0][1]),
                                      model.Prod( 1.0, var[0][2])), 30.0);
 }
        public PromptsViewModel(string cutxFilePath,
                                string globalFilePath,
                                string cutpartsFilePath,
                                string edgebandFilePath,
                                string hardwareFilePath,
                                string doorstyleFilePath,
                                string name,
                                string imagePath,
                                double width,
                                double height,
                                double depth)
            : this()
        {
            this.Width = width;
            this.Height = height;
            this.Depth = depth;
            this.Name = name;
            this.ProductImagePath = imagePath + ".jpg";

            BookSet = SpreadHelper.GetProductBaseicBookSet(cutxFilePath, globalFilePath,
                cutpartsFilePath, hardwareFilePath, doorstyleFilePath, edgebandFilePath);

            Book = BookSet.Workbooks["L"];
            var sheet = Book.Worksheets["Prompts"];
            PromptCells = sheet.Cells;

            loadCellPrompts();

            if (PromptTabs.Count == 0)
            {
                PromptTabs.Add("主标签");
            }

            //this.SpecificationGroups = project.SpecificationGroups;
            //this.SelectedSGroup = this.SpecificationGroups[0];
            //this.Qty = 1;

            //var fi = new FileInfo(cutxFilePath);
            //this.Description = fi.Name.Replace(fi.Extension, "");

            //this.ProductHandle = (new Random()).Next(1000000000, 1999999999).ToString();
        }
        /// <summary>
        /// Create a new instance of a test case
        /// </summary>
        /// <param name="sutXml"></param>
        /// <param name="ctrXml"></param>
        /// <returns></returns>
        public IEnumerable<string> Instantiate(IRange range)
        {
            if (range == null)
                throw new ArgumentNullException("range");

            IRangeMembersBuilder builder = null;

            //Look for registration ...
            var registration = registrations.FirstOrDefault(reg => reg.Match(range.GetType()));
            if (registration == null)
                throw new ArgumentException(string.Format("'{0}' has no builder registred.", range.GetType().Name, "range"));

            //Get Builder and initiate it
            builder = registration.Builder;
            builder.Setup(range);

            //Build
            builder.Build();
            var list = builder.GetResult();

            return list;
        }
Beispiel #31
0
 public virtual TSpectrum FilterByMZ(IRange <double> mzRange)
 {
     return(FilterByMZ(mzRange.Minimum, mzRange.Maximum));
 }
        //
        // GET: /Sparklines/

        public ActionResult Sparklines(string button)
        {
            string basePath = _hostingEnvironment.WebRootPath;

            if (button == null)
            {
                return(View());
            }

            //Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;
            //A new workbook is created.[Equivalent to creating a new workbook in Microsoft Excel]
            //Open workbook with Data
            FileStream inputStream = new FileStream(basePath + @"/XlsIO/Sparkline.xlsx", FileMode.Open, FileAccess.Read);
            IWorkbook  workbook    = application.Workbooks.Open(inputStream);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];

            #region WholeSale Report

            //A new Sparkline group is added to the sheet sparklinegroups
            ISparklineGroup sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as line
            sparklineGroup.SparklineType = SparklineType.Line;

            //Set to display the empty cell as line
            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Line;

            //Sparkline group style properties
            sparklineGroup.ShowFirstPoint     = true;
            sparklineGroup.FirstPointColor    = Color.Green;
            sparklineGroup.ShowLastPoint      = true;
            sparklineGroup.LastPointColor     = Color.DarkOrange;
            sparklineGroup.ShowHighPoint      = true;
            sparklineGroup.HighPointColor     = Color.DarkBlue;
            sparklineGroup.ShowLowPoint       = true;
            sparklineGroup.LowPointColor      = Color.DarkViolet;
            sparklineGroup.ShowMarkers        = true;
            sparklineGroup.MarkersColor       = Color.Black;
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.Red;

            //set the line weight
            sparklineGroup.LineWeight = 0.3;

            //The sparklines are added to the sparklinegroup.
            ISparklines sparklines = sparklineGroup.Add();

            //Set the Sparkline Datarange .
            IRange dataRange = sheet.Range["D6:G17"];
            //Set the Sparkline Reference range.
            IRange referenceRange = sheet.Range["H6:H17"];

            //Create a sparkline with the datarange and reference range.
            sparklines.Add(dataRange, referenceRange);
            #endregion

            #region Retail Trade

            //A new Sparkline group is added to the sheet sparklinegroups
            sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as column
            sparklineGroup.SparklineType = SparklineType.Column;

            //Set to display the empty cell as zero
            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Zero;

            //Sparkline group style properties
            sparklineGroup.ShowHighPoint      = true;
            sparklineGroup.HighPointColor     = Color.Green;
            sparklineGroup.ShowLowPoint       = true;
            sparklineGroup.LowPointColor      = Color.Red;
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.Black;

            //The sparklines are added to the sparklinegroup.
            sparklines = sparklineGroup.Add();

            //Set the Sparkline Datarange .
            dataRange = sheet.Range["D21:G32"];
            //Set the Sparkline Reference range.
            referenceRange = sheet.Range["H21:H32"];

            //Create a sparkline with the datarange and reference range.
            sparklines.Add(dataRange, referenceRange);

            #endregion

            #region Manufacturing Trade

            //A new Sparkline group is added to the sheet sparklinegroups
            sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as win/loss
            sparklineGroup.SparklineType = SparklineType.ColumnStacked100;

            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Zero;

            sparklineGroup.DisplayAxis        = true;
            sparklineGroup.AxisColor          = Color.Black;
            sparklineGroup.ShowFirstPoint     = true;
            sparklineGroup.FirstPointColor    = Color.Green;
            sparklineGroup.ShowLastPoint      = true;
            sparklineGroup.LastPointColor     = Color.Orange;
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.Red;

            sparklines = sparklineGroup.Add();

            dataRange      = sheet.Range["D36:G46"];
            referenceRange = sheet.Range["H36:H46"];

            sparklines.Add(dataRange, referenceRange);

            #endregion

            try
            {
                MemoryStream ms = new MemoryStream();
                workbook.SaveAs(ms);
                ms.Position = 0;

                return(File(ms, "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Sparklines.xlsx"));
            }
            catch (Exception)
            {
            }

            // Close the workbook
            workbook.Close();
            excelEngine.Dispose();
            return(View());
        }
Beispiel #33
0
        /// <summary>
        /// Create an Excel document with formatting applied to the cells
        /// </summary>
        /// <returns>Return the created excel document as stream</returns>
        public MemoryStream FormatCellsXlsIO(string version)
        {
            //New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                //Step 2 : Instantiate the excel application object
                IApplication application = excelEngine.Excel;

                //Set the default version
                if (version == "XLSX")
                {
                    application.DefaultVersion = ExcelVersion.Xlsx;
                }
                else
                {
                    application.DefaultVersion = ExcelVersion.Excel97to2003;
                }

                //A new workbook is created.[Equivalent to creating a new workbook in Microsoft Excel]
                //The new workbook will have 3 worksheets
                IWorkbook workbook = application.Workbooks.Create(3);

                //The first worksheet object in the worksheets collection is accessed
                IWorksheet sheet = workbook.Worksheets[0];
                sheet.IsGridLinesVisible = false;

                #region RTF
                //Insert Rich Text
                IRange range = sheet.Range["D3"];
                range.Text = "Employee Report";
                IRichTextString rtf = range.RichText;

                //Formatting the text
                IFont redFont = workbook.CreateFont();
                redFont.Size     = 16;
                redFont.Bold     = true;
                redFont.Italic   = true;
                redFont.RGBColor = Color.FromArgb(0x82, 0x2e, 0x1b);
                rtf.SetFont(0, 14, redFont);
                #endregion

                #region Number Formatting
                sheet.Range["H24"].Number       = 5000;
                sheet.Range["H24"].NumberFormat = "$#,##0.00";
                sheet.Range["H14"].NumberFormat = "dd/mm/yyyy";
                sheet.Range["H14"].DateTime     = DateTime.Parse(" 8/3/1963", CultureInfo.InvariantCulture);
                sheet.Range["H16"].NumberFormat = "mm/dd/yyyy";
                sheet.Range["H16"].DateTime     = DateTime.Parse(" 4/1/1992", CultureInfo.InvariantCulture);
                #endregion

                #region Alignment settings
                #region Text alignment
                sheet.Range["F10:F24"].HorizontalAlignment = ExcelHAlign.HAlignRight;
                sheet.Range["D3"].HorizontalAlignment      = ExcelHAlign.HAlignCenter;
                sheet.Range["H10:H24"].HorizontalAlignment = ExcelHAlign.HAlignLeft;
                sheet.Range["F10:F24"].VerticalAlignment   = ExcelVAlign.VAlignCenter;
                #endregion

                #region Text Control
                sheet.Range["F27"].WrapText = true;
                sheet.Range["F27"].Text     = "Antony Jose graduated from St. Andrews University, Scotland, with a BSC degree in 1976.  Upon joining the company as a sales representative in 1992, he spent 6 months in an orientation program at the Seattle office and then returned to his permanent post in London.  He was promoted to sales manager in March 1993.";
                #endregion

                #region Cell merging
                sheet.Range["F27:H28"].Merge();
                sheet.Range["D3:F3"].Merge();
                sheet.Range["B7:J8"].Merge();
                sheet.Range["F27"].RowHeight       = 66;
                sheet.Range["H10:H24"].ColumnWidth = 25;
                sheet.Range["C10:D28"].Merge();
                sheet.Range["B10:C28"].ColumnWidth = 1;
                sheet.Range["E10:E28"].ColumnWidth = 5;
                sheet.Range["D10:D28"].ColumnWidth = 15;
                #endregion

                #region Text Direction
                sheet.Range["B7"].Text = "Antony Jose";
                sheet.Range["B7"].CellStyle.ReadingOrder        = Syncfusion.XlsIO.ExcelReadingOrderType.LeftToRight;
                sheet.Range["B7"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignLeft;
                sheet.Range["B7"].CellStyle.VerticalAlignment   = ExcelVAlign.VAlignCenter;
                #endregion

                #region Text Indent
                sheet.Range["D7"].CellStyle.IndentLevel = 6;
                #endregion
                #endregion

                #region Font settings
                //Setting Font Type
                sheet.Range["F10:F24"].CellStyle.Font.FontName = "Arial";
                sheet.Range["D3"].CellStyle.Font.FontName      = "Arial";
                sheet.Range["B7"].CellStyle.Font.FontName      = "Arial";
                sheet.Range["B7"].CellStyle.Font.Size          = 12f;
                sheet.Range["B7"].CellStyle.Font.Bold          = true;

                //Setting Font Styles
                sheet.Range["F10:F24"].CellStyle.Font.Bold = true;
                sheet.Range["D3"].CellStyle.Font.Bold      = true;

                //Setting Font Size
                sheet.Range["F10:F24"].CellStyle.Font.Size = 10;
                sheet.Range["D3"].CellStyle.Font.Size      = 14;
                sheet.Range["F27:H28"].CellStyle.Font.Size = 9f;

                //Setting Font Color
                sheet.Range["B7"].CellStyle.Font.RGBColor  = Color.White;
                sheet.Range["D28"].CellStyle.Font.RGBColor = Color.White;

                //Setting UnderLine
                sheet.Range["D3"].CellStyle.Font.Underline = ExcelUnderline.Double;

                sheet.Range["F10"].Text = "Name";
                sheet.Range["F12"].Text = "Title";
                sheet.Range["F14"].Text = "Birth Date";
                sheet.Range["F16"].Text = "Hire date";
                sheet.Range["F18"].Text = "Home phone";
                sheet.Range["F20"].Text = "Extension";
                sheet.Range["F22"].Text = "Home address";
                sheet.Range["F24"].Text = "Salary";

                sheet.Range["H10"].Text   = "Antony Jose";
                sheet.Range["H12"].Text   = "Sales Manager";
                sheet.Range["H18"].Text   = "(206) 555-3412";
                sheet.Range["H20"].Number = 3355;
                sheet.Range["H22"].Text   = "722 Moss Bay Blvd";
                #endregion

                #region Insert Image
                FileStream imageStream = new FileStream(ResolveApplicationImagePath("EMPID1.png"), FileMode.Open, FileAccess.Read);
                sheet.Pictures.AddPicture(11, 4, imageStream, 55, 65);
                #endregion

                #region Border setting
                sheet.Range["H10"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H10"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H10"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H12"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H12"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H12"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H14"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H14"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H14"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H16"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H16"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H16"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H18"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H18"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H18"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H20"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H20"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H20"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H22"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H22"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H22"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["H24"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["H24"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["H24"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["F27:H28"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
                sheet.Range["F27:H28"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["F27:H28"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

                sheet.Range["C10:D28"].CellStyle.Borders.LineStyle = ExcelLineStyle.Thin;
                sheet.Range["C10:D28"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
                sheet.Range["C10:D28"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;
                #endregion

                #region Pattern settings
                sheet.Range["B9:I29"].CellStyle.Color = Color.FromArgb(198, 215, 239);
                sheet.Range["A7:J8"].CellStyle.Color  = Color.FromArgb(57, 93, 148);

                sheet.Range["A7:A30"].CellStyle.Color = Color.FromArgb(57, 93, 148);
                sheet.Range["A7:A30"].ColumnWidth     = 2.29;

                sheet.Range["J7:J30"].CellStyle.Color = Color.FromArgb(57, 93, 148);
                sheet.Range["J7:J30"].ColumnWidth     = 2.29;

                sheet.Range["A30:J30"].CellStyle.Color = Color.FromArgb(57, 93, 148);

                sheet.Range["C10:D28"].CellStyle.Color = Color.FromArgb(231, 235, 247);
                sheet.Range["F27:H28"].CellStyle.Color = Color.FromArgb(231, 235, 247);
                #endregion

                //Save the document as a stream and retrun the stream
                using (MemoryStream stream = new MemoryStream())
                {
                    //Save the created Excel document to MemoryStream
                    workbook.SaveAs(stream);
                    return(stream);
                }
            }
        }
Beispiel #34
0
        //
        // GET: /StylesAndFormatting/

        public ActionResult StylesAndFormatting(string button1, string button)
        {
            if (button == null && button1 == null)
            {
                return(View());
            }
            else if (button == "Input Template")
            {
                //Step 1 : Instantiate the spreadsheet creation engine.
                ExcelEngine excelEngine = new ExcelEngine();
                //Step 2 : Instantiate the excel application object.
                IApplication application = excelEngine.Excel;
                IWorkbook    workbook    = application.Workbooks.Open(ResolveApplicationDataPath(@"CalendarTemplate.xlsx"));
                return(excelEngine.SaveAsActionResult(workbook, "Template.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2016));
            }
            else
            {
                //New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
                //The instantiation process consists of two steps.

                //Step 1 : Instantiate the spreadsheet creation engine.
                ExcelEngine excelEngine = new ExcelEngine();
                //Step 2 : Instantiate the excel application object.
                IApplication application = excelEngine.Excel;

                application.DefaultVersion = ExcelVersion.Excel2016;

                //A new workbook is created.[Equivalent to creating a new workbook in Microsoft Excel]
                //The new workbook will have 12 worksheets
                IWorkbook workbook     = application.Workbooks.Create(12);
                IWorkbook tempWorkbook = application.Workbooks.Open(ResolveApplicationDataPath("CalendarTemplate.xlsx"));
                workbook.Worksheets.AddCopyAfter(tempWorkbook.Worksheets[0], workbook.Worksheets[11]);

                //The first worksheet object in the worksheets collection is accessed.
                IWorksheet sheet;

                # region Calendar

                # region Draw Calendar
                String[] monthArray = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
                String[] dateArray  = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
                Color[]  colorArray = new Color[] { Color.FromArgb(149, 55, 53), Color.FromArgb(146, 208, 80), Color.FromArgb(0, 32, 96), Color.FromArgb(0, 176, 80), Color.FromArgb(255, 255, 0), Color.FromArgb(128, 128, 128), Color.FromArgb(255, 0, 0), Color.FromArgb(96, 73, 123), Color.FromArgb(169, 161, 117), Color.FromArgb(0, 176, 240), Color.FromArgb(192, 0, 0), Color.FromArgb(63, 49, 81), Color.FromArgb(192, 0, 0) };

                int cMonth = DateTime.Today.Month - 1;

                for (int monIndex = 1; monIndex < 13; monIndex++)
                {
                    sheet      = workbook.Worksheets[monIndex - 1];
                    sheet.Name = monthArray[monIndex - 1];

                    sheet.Range["B3:H3"].Merge();
                    sheet.Range["B4:H4"].Merge();
                    sheet.IsGridLinesVisible = false;

                    //Write the month as the heading
                    sheet.Range["B3"].Text = monthArray[monIndex - 1];

                    //Apply styles for the month title
                    sheet.Range["B3:H3"].HorizontalAlignment = ExcelHAlign.HAlignCenter;
                    sheet.Range["B3:H3"].VerticalAlignment   = ExcelVAlign.VAlignCenter;
                    sheet.Range["B3:H3"].BorderAround(ExcelLineStyle.Thin, Color.Brown);
                    sheet.Range["B3:H3"].RowHeight = 30;

                    IStyle style = sheet.Range["B3"].CellStyle;
                    style.HorizontalAlignment  = ExcelHAlign.HAlignCenter;
                    style.Interior.FillPattern = ExcelPattern.Gradient;
                    style.Interior.Gradient.TwoColorGradient(ExcelGradientStyle.Diagonl_Up, ExcelGradientVariants.ShadingVariants_3);
                    style.Interior.Gradient.ForeColorIndex = ExcelKnownColors.White;
                    style.Interior.Gradient.BackColor      = colorArray[monIndex - 1];
                    IFont font = style.Font;
                    font.FontName = "Segoe UI";
                    font.Size     = 22;
                    font.Italic   = true;

                    //Write the weekdays
                    for (int i = 2, j = 0; i < 9; i++, j++)
                    {
                        sheet.SetValue(5, i, dateArray[j]);
                        sheet.Range[5, i].HorizontalAlignment = ExcelHAlign.HAlignCenter;
                    }

                    //Get the number of days in the month
                    int days = DateTime.DaysInMonth(DateTime.Today.Year, monIndex);

                    //Write the calendar
                    DateTime firstDay = new DateTime(DateTime.Today.Year, monIndex, 1);
                    IRange   range    = sheet.FindFirst(firstDay.Date.DayOfWeek.ToString(), ExcelFindType.Text);

                    int row    = range.End.Row + 1;
                    int column = range.End.Column;
                    int date   = 1;

                    while (date < days + 1)
                    {
                        for (; column < 9; column++)
                        {
                            sheet.Range[row, column].Number = date;
                            date++;
                            if (date == days + 1)
                            {
                                break;
                            }
                        }
                        column = 2;
                        row++;
                    }

                    //Format Sunday
                    sheet.Range["B5:B11"].BuiltInStyle = BuiltInStyles.WarningText;
                    sheet.Range["B5"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;

                    //Format day title
                    sheet.Range["B5:H5"].BuiltInStyle        = BuiltInStyles.Heading4;
                    sheet.Range["B5:H5"].CellStyle.Font.Size = 10;

                    //Border around the entire calendar
                    sheet.UsedRange.BorderAround(ExcelLineStyle.Double, Color.Black);
                    sheet.UsedRange.BorderInside(ExcelLineStyle.Hair, Color.Black);

                    sheet.Range["B3"].RowHeight     = 35;
                    sheet.Range["B5:H11"].RowHeight = 60;
                    sheet.UsedRange.ColumnWidth     = 15;

                    //Set Legend
                    sheet["K7"].BuiltInStyle = BuiltInStyles.Accent2_20;
                    sheet["K8"].BuiltInStyle = BuiltInStyles.Accent4_20;

                    sheet.Range["L7"].Text = "Holidays";
                    sheet.Range["L8"].Text = "Today";
                    sheet.Range["L7:L8"].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
                }
                # endregion

                # region Styles for today
                foreach (IWorksheet cSheet in workbook.Worksheets)
Beispiel #35
0
 public IAsyncOperation <IEnumerable <FindMatch> > FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches)
 {
     // Default limit results: https://github.com/microsoft/vscode/blob/b2d0292a20c4a012005c94975019a5b572ce6a63/src/vs/editor/common/model/textModel.ts#L117
     return(FindMatchesAsync(searchString, searchScope, isRegex, matchCase, wordSeparators, captureMatches, 999));
 }
        // Step 4 *****************************************************************************************************
        // Step 4 *****************************************************************************************************
        internal static void PopulateByRow(IMPModeler model, out IIntVar[][][] var2, out IIntVar[][][][] var3,
                                           out IIntVar[][][][][] var4, out IRange[][] rng,
                                           CRegion lscrg, CRegion sscrg, double[,] adblTD, string strAreaAggregation)
        {
            var aCph        = lscrg.GetCphCol().ToArray();
            int intCpgCount = lscrg.GetCphCount();
            //double dblILPSmallValue = 0.000000001;
            //double dblILPSmallValue = 0;

            var x = new IIntVar[intCpgCount][][];

            for (int i = 0; i < intCpgCount; i++)
            {
                x[i] = new IIntVar[intCpgCount][];
                for (int j = 0; j < intCpgCount; j++)
                {
                    x[i][j] = model.BoolVarArray(intCpgCount);
                }
            }

            //cost in terms of type change
            var y = Generate4DNumVar(model, intCpgCount - 1, intCpgCount, intCpgCount, intCpgCount);

            //cost in terms of compactness (length of interior boundaries)
            var z = Generate4DNumVar(model, intCpgCount - 2, intCpgCount, intCpgCount, intCpgCount);


            var c = Generate4DNumVar(model, intCpgCount - 2, intCpgCount, intCpgCount, intCpgCount);

            var3    = new IIntVar[1][][][];
            var4    = new IIntVar[3][][][][];
            var3[0] = x;
            var4[0] = y;
            var4[1] = z;
            var4[2] = c;


            //model.AddEq(x[2][0][3], 1.0, "X1");
            //model.AddEq(x[2][1][3], 1.0, "X2");
            //model.AddEq(x[2][2][2], 1.0, "X3");
            //model.AddEq(x[2][3][3], 1.0, "X4");

            //add minimizations
            ILinearNumExpr pTypeCostExpr = model.LinearNumExpr();

            //ILinearNumExpr pTypeCostAssitantExpr = model.LinearNumExpr();
            for (int i = 0; i < intCpgCount - 1; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    for (int k = 0; k < intCpgCount; k++)
                    {
                        for (int l = 0; l < intCpgCount; l++)
                        {
                            double dblCoe = aCph[j].dblArea * adblTD[aCph[k].intTypeIndex, aCph[l].intTypeIndex];
                            pTypeCostExpr.AddTerm(y[i][j][k][l], dblCoe);
                            //pTypeCostAssitantExpr.AddTerm(y[i][j][k][l], dblILPSmallValueMinimization);
                        }
                    }
                }
            }


            //this is actually for t=1, whose compactness is known
            double         dblCompCostFirstPart    = 0;
            ILinearNumExpr pCompCostSecondPartExpr = model.LinearNumExpr();
            var            pAdjCorrCphsSD          = lscrg.AdjCorrCphsSD;
            double         dblConst = Convert.ToDouble(intCpgCount - 1) / Convert.ToDouble(intCpgCount - 2);

            for (int i = 0; i < intCpgCount - 2; i++)   //i represents indices
            {
                double dblNminusT = intCpgCount - i - 2;
                //double dblTemp = (intCpgCount - i) * dblConst;
                dblCompCostFirstPart += 1 / dblNminusT;
                double dblSecondPartDenominator = lscrg.dblInteriorSegLength * dblNminusT * 2;

                //we don't need to divide the value by 2 because every boundary is only counted once
                foreach (var pCorrCphs in pAdjCorrCphsSD.Keys)
                {
                    for (int l = 0; l < intCpgCount; l++)
                    {
                        pCompCostSecondPartExpr.AddTerm(pCorrCphs.dblSharedSegLength / dblSecondPartDenominator,
                                                        z[i][pCorrCphs.FrCph.ID][pCorrCphs.ToCph.ID][l]);
                        pCompCostSecondPartExpr.AddTerm(pCorrCphs.dblSharedSegLength / dblSecondPartDenominator,
                                                        z[i][pCorrCphs.ToCph.ID][pCorrCphs.FrCph.ID][l]);
                    }
                }
                //var pSecondPartExpr =  model.Prod(pCompCostSecondPartExpr, 1 / dblSecondPartDenominator);
            }

            if (intCpgCount == 1)
            {
                model.AddMinimize(pTypeCostExpr);  //we just use an empty expression
            }
            else
            {
                //Our Model***************************************
                var Ftp = model.Prod(pTypeCostExpr, 1 / lscrg.dblArea);
                var Fcp = model.Prod(dblConst, model.Sum(dblCompCostFirstPart, model.Negative(pCompCostSecondPartExpr)));
                //model.AddMinimize(model.Prod(model.Sum(Ftp, Fcp), 0.5));
                model.AddMinimize(model.Sum(
                                      model.Prod(1 - CAreaAgg_Base.dblLamda, Ftp), model.Prod(CAreaAgg_Base.dblLamda, Fcp)));
                //model.AddMinimize(Fcp);
                //model.AddMaximize(Fcp);
                //model.AddObjective()
            }

            //for showing slacks
            var IRangeLt = new List <IRange>();

            //a polygon $p$ is assigned to exactly one polygon at a step $t$
            for (int i = 0; i < intCpgCount; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    ILinearNumExpr pOneCenterExpr = model.LinearNumExpr();
                    for (int l = 0; l < intCpgCount; l++)
                    {
                        pOneCenterExpr.AddTerm(x[i][j][l], 1.0);
                    }
                    model.AddEq(pOneCenterExpr, 1.0, "AssignToOnlyOneCenter");
                }
            }

            //polygon $r$, which is assigned by other polygons, must be a center
            for (int i = 0; i < intCpgCount; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    for (int l = 0; l < intCpgCount; l++)
                    {
                        model.AddLe(x[i][j][l], x[i][l][l], "AssignedIsCenter__" + i + "__" + j + "__" + l);
                    }
                }
            }

            //only one patch is aggregated into another patch at each step
            for (int i = 0; i < intCpgCount; i++)   //i represents indices
            {
                ILinearNumExpr pOneAggregationExpr = model.LinearNumExpr();
                for (int j = 0; j < intCpgCount; j++)
                {
                    pOneAggregationExpr.AddTerm(x[i][j][j], 1.0);
                }
                model.AddEq(pOneAggregationExpr, intCpgCount - i, "CountCenters");
            }

            //a center can disappear, but will never reappear afterwards
            for (int i = 0; i < intCpgCount - 1; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    model.AddGe(x[i][j][j], x[i + 1][j][j], "SteadyCenters");
                }
            }


            //to make sure that the final aggregated polygon has the same color as the target polygon
            ILinearNumExpr pFinalStateExpr  = model.LinearNumExpr();
            int            intTypeIndexGoal = sscrg.GetSoloCphTypeIndex();

            for (int i = 0; i < intCpgCount; i++)
            {
                if (aCph[i].intTypeIndex == intTypeIndexGoal)
                {
                    pFinalStateExpr.AddTerm(x[intCpgCount - 1][i][i], 1.0);
                }
            }
            model.AddEq(pFinalStateExpr, 1.0, "EnsureTarget");


            //to restrict *y*
            for (int i = 0; i < intCpgCount - 1; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    for (int k = 0; k < intCpgCount; k++)
                    {
                        //IRangeLt.Add(model.AddLe(model.Sum(y[i][j][k][k], x[i][j][k], x[i + 1][j][k]), 2.0 , "RestrictY"));

                        for (int l = 0; l < intCpgCount; l++)
                        {
                            var LieYRight = model.LinearIntExpr(-1);
                            LieYRight.AddTerm(x[i][j][k], 1);
                            LieYRight.AddTerm(x[i + 1][j][l], 1);

                            model.AddGe(y[i][j][k][l], LieYRight, "RestrictY1");
                            model.AddLe(y[i][j][k][l], x[i][j][k], "RestrictY2");
                            model.AddLe(y[i][j][k][l], x[i + 1][j][l], "RestrictY3");
                        }
                    }
                }
            }

            //to restrict *z*
            for (int i = 0; i < intCpgCount - 2; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    //for (int k = j; k < intCpgCount; k++)  // pay attention
                    for (int k = 0; k < intCpgCount; k++)
                    {
                        for (int l = 0; l < intCpgCount; l++)
                        {
                            var LieZRight = model.LinearIntExpr(-1);
                            LieZRight.AddTerm(x[i + 1][j][l], 1);
                            LieZRight.AddTerm(x[i + 1][k][l], 1);

                            model.AddGe(z[i][j][k][l], LieZRight, "RestrictZ1");
                            model.AddLe(z[i][j][k][l], x[i + 1][j][l], "RestrictZ2");
                            model.AddLe(z[i][j][k][l], x[i + 1][k][l], "RestrictZ3");
                        }
                    }
                }
            }

            //to restrict *c*
            double dblCpgCountReciprocal = 1 / Convert.ToDouble(intCpgCount);

            for (int i = 0; i < intCpgCount - 2; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    //for (int k = j; k < intCpgCount; k++)  // pay attention
                    for (int k = 0; k < intCpgCount; k++)
                    {
                        for (int l = 0; l < intCpgCount; l++)
                        {
                            if (k == l)
                            {
                                continue;
                            }

                            model.AddLe(c[i][j][k][l], x[i][j][k], "RestrictC1");

                            var pLieContiguityExpr = model.LinearIntExpr();
                            //pContiguityExpr.AddTerm(x[i][j][k], 1.0);  //including polygon j itself
                            foreach (var pAdjacentCph in aCph[j].AdjacentCphSS)
                            {
                                pLieContiguityExpr.AddTerm(x[i][pAdjacentCph.ID][l], 1);
                            }
                            model.AddLe(c[i][j][k][l], pLieContiguityExpr, "Contiguity");


                            foreach (var pAdjacentCph in aCph[j].AdjacentCphSS)
                            {
                                var pContiguityExpr2 = model.LinearNumExpr(-1);
                                pContiguityExpr2.AddTerm(x[i][j][k], 1);
                                pContiguityExpr2.AddTerm(x[i][pAdjacentCph.ID][l], 1);

                                model.AddGe(c[i][j][k][l], pContiguityExpr2, "Contiguity2");
                            }

                            var pContiguityExprRight3 = model.LinearIntExpr();
                            for (int m = 0; m < intCpgCount; m++)
                            {
                                pContiguityExprRight3.AddTerm(c[i][m][k][l], 1);
                            }
                            model.AddLe(y[i][k][k][l], pContiguityExprRight3, "Contiguity3");
                        }
                    }
                }
            }


            //If two polygons have been aggregated into one polygon, then they will
            //be aggregated together in later steps. Our sixth constraint achieve this by requiring
            for (int i = 0; i < intCpgCount - 3; i++)   //i represents indices
            {
                for (int j = 0; j < intCpgCount; j++)
                {
                    for (int k = 0; k < intCpgCount; k++)
                    {
                        var pAssignTogetherExprPre   = model.LinearIntExpr();
                        var pAssignTogetherExprAfter = model.LinearIntExpr();
                        for (int l = 0; l < intCpgCount; l++)
                        {
                            pAssignTogetherExprPre.AddTerm(z[i][j][k][l], 1);
                            pAssignTogetherExprAfter.AddTerm(z[i + 1][j][k][l], 1);
                        }
                        model.AddLe(pAssignTogetherExprPre, pAssignTogetherExprAfter, "AssignTogether");
                    }
                }
            }

            var2 = new IIntVar[1][][];
            if (strAreaAggregation == _strSmallest)
            {
                IIntVar[][] w = new IIntVar[intCpgCount - 1][];
                for (int i = 0; i < intCpgCount - 1; i++)
                {
                    w[i] = model.BoolVarArray(intCpgCount);
                }
                var2[0] = w;

                //there is only one smallest patch will be involved in each aggregation step
                for (int i = 0; i < intCpgCount - 1; i++)   //i represents indices
                {
                    var pOneSmallestExpr = model.LinearIntExpr();
                    for (int j = 0; j < intCpgCount; j++)
                    {
                        pOneSmallestExpr.AddTerm(w[i][j], 1);
                    }

                    model.AddEq(pOneSmallestExpr, 1.0, "OneSmallest");
                }

                //forces that the aggregation must involve the smallest patch.
                for (int i = 0; i < intCpgCount - 1; i++)   //i represents indices
                {
                    for (int j = 0; j < intCpgCount; j++)
                    {
                        var pInvolveSmallestExpr = model.LinearIntExpr();
                        for (int k = 0; k < intCpgCount; k++)
                        {
                            if (j == k) //o != r
                            {
                                continue;
                            }
                            pInvolveSmallestExpr.AddTerm(y[i][j][j][k], 1);
                            pInvolveSmallestExpr.AddTerm(y[i][k][k][j], 1);
                        }
                        model.AddLe(w[i][j], pInvolveSmallestExpr, "InvolveSmallest");
                    }
                }

                //To guarantee that patch $o$ is involved in aggregation is indeed the smallest patch
                double dblM = 1.1 * lscrg.dblArea;        //a very large value
                for (int i = 0; i < intCpgCount - 1; i++) //i represents indices
                {
                    var aAreaExpr = ComputeAreaExpr(model, x[i], aCph);
                    for (int j = 0; j < intCpgCount; j++)
                    {
                        for (int k = 0; k < intCpgCount; k++)
                        {
                            if (j == k) //o != r
                            {
                                continue;
                            }

                            var pSumExpr  = model.Sum(2.0, model.Negative(model.Sum(w[i][j], x[i][k][k]))); //(2-w_{t,o}-x_{t,r,r})
                            var pProdExpr = model.Prod(pSumExpr, dblM);                                     //M(2-w_{t,o}-x_{t,r,r})

                            //A_{t,o}-A_{t,r}<= M(2-w_{t,o}-x_{t,r,r})
                            model.AddLe(model
                                        .Sum(aAreaExpr[j], model.Negative(aAreaExpr[k])), pProdExpr, "IndeedSmallest");
                        }
                    }
                }
            }


            //***************compare with number of constraints counted manually************
            rng    = new IRange[1][];
            rng[0] = new IRange[IRangeLt.Count];
            for (int i = 0; i < IRangeLt.Count; i++)
            {
                rng[0][i] = IRangeLt[i];
            }
        }
Beispiel #37
0
 public bool Includes(IRange <DateTime> range)
 {
     return((Start <= range.Start) && (range.End <= End));
 }
Beispiel #38
0
 ISpectrum <TPeak> ISpectrum <TPeak> .FilterByIntensity(IRange <double> intenistyRange)
 {
     return(FilterByIntensity(intenistyRange));
 }
Beispiel #39
0
 ISpectrum <TPeak> ISpectrum <TPeak> .FilterByMZ(IRange <double> mzRange)
 {
     return(FilterByMZ(mzRange));
 }
Beispiel #40
0
 MZPeak ISpectrum.GetClosestPeak(IRange <double> massRange)
 {
     return(GetClosestPeak(massRange));
 }
Beispiel #41
0
 ISpectrum ISpectrum.FilterByIntensity(IRange <double> intenistyRange)
 {
     return(FilterByIntensity(intenistyRange.Minimum, intenistyRange.Maximum));
 }
Beispiel #42
0
 ISpectrum ISpectrum.FilterByMZ(IRange <double> mzRange)
 {
     return(FilterByMZ(mzRange.Minimum, mzRange.Maximum));
 }
 public bool TryGetSignalToNoise(IRange <double> rangeMZ, out double signalToNoise)
 {
     return(TryGetSignalToNoise(rangeMZ.Minimum, rangeMZ.Maximum, out signalToNoise));
 }
 protected abstract string FormatRange(IRange range, object otherOperand);
Beispiel #45
0
        public IAsyncOperation <IEnumerable <FindMatch> > FindMatchesAsync(string searchString, IRange searchScope, bool isRegex, bool matchCase, string wordSeparators, bool captureMatches, double limitResultCount)
        {
            if (_editor.TryGetTarget(out CodeEditor editor))
            {
                return(editor.InvokeScriptAsync <IEnumerable <FindMatch> >("model.findMatches", new object[] { searchString, searchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount }).AsAsyncOperation());
            }

            return(null);
        }
        static void Main(string[] args)
        {
            double BinCap = 0;
            var    dict   = InputReader.ReadDataFile(ref BinCap);

            Cplex cplex = new Cplex();
            Dictionary <string, INumVar> dictvariables   = new Dictionary <string, INumVar>();
            Dictionary <string, IRange>  dictconstraints = new Dictionary <string, IRange>();
            IObjective objective = cplex.AddMinimize();

            foreach (var vari in dict.Keys)
            {
                var cname = "C" + vari;
                dictconstraints.Add(cname, cplex.AddRange(1, Int32.MaxValue, cname));
            }

            Dictionary <int, Set> InitialSets = new Dictionary <int, Set>();;

            InitialSets.Add(1, new Set(new List <int> {
                1, 5
            }));
            InitialSets.Add(2, new Set(new List <int> {
                2, 5
            }));
            InitialSets.Add(3, new Set(new List <int> {
                3, 5
            }));
            InitialSets.Add(4, new Set(new List <int> {
                4, 5
            }));

            //Add intial sets to the model
            foreach (var vari in InitialSets)
            {
                var    setID  = vari.Key.ToString();
                Column VarSet = cplex.Column(objective, 1);
                foreach (var members in vari.Value.member)
                {
                    var cname = "C" + members;
                    VarSet = VarSet.And(cplex.Column(dictconstraints[cname], 1));
                }

                dictvariables.Add(setID, cplex.NumVar(VarSet, 0, 1, NumVarType.Float));
            }
            cplex.Solve();
            var duals    = getDuals(cplex, dictconstraints);
            var solution = getSolution(cplex, dictvariables);

            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());

            int piter     = 0;
            int fixediter = 0;
            Dictionary <string, INumVar> Fixedvar = new Dictionary <string, INumVar>();

            while (true)
            {
                //Formulate Pricing Problem
                Cplex      pcplex     = new Cplex();
                IObjective pobjective = pcplex.AddMaximize();
                piter++;
                //Add Bin Capacity Constraint
                IRange Knapsack = pcplex.AddRange(0, BinCap, "Bin");
                Dictionary <string, INumVar> pdictvar = new Dictionary <string, INumVar>();
                foreach (var vari in dict.Keys)
                {
                    var    varname  = vari.ToString();
                    var    objcoeff = duals["C" + varname];
                    Column item     = pcplex.Column(pobjective, objcoeff);
                    item = item.And(pcplex.Column(Knapsack, dict[vari]));
                    pdictvar.Add(varname, pcplex.NumVar(item, 0, 1, NumVarType.Int));
                }

                pcplex.Solve();
                if (pcplex.GetObjValue() > 1)
                {
                    Console.WriteLine("Pricing Iteration: {0} and obj value is {1} ", piter, pcplex.GetObjValue());
                    var        psolution = getSolution(pcplex, pdictvar);
                    List <int> sol       = new List <int>();
                    foreach (var vari in psolution.Keys)
                    {
                        sol.Add(Convert.ToInt32(vari));
                    }
                    InitialSets.Add(InitialSets.Count + 1, new Set(sol));

                    var    setID   = (InitialSets.Count).ToString();
                    Column VarSet1 = cplex.Column(objective, 1);
                    foreach (var members in sol)
                    {
                        var cname = "C" + members;
                        VarSet1 = VarSet1.And(cplex.Column(dictconstraints[cname], 1));
                    }

                    dictvariables.Add(setID, cplex.NumVar(VarSet1, 0, 1, NumVarType.Float));

                    cplex.Solve();
                    Console.WriteLine("The objective value of cplex after adding column  is {0}", cplex.GetObjValue());
                    duals    = getDuals(cplex, dictconstraints);
                    solution = getSolution(cplex, dictvariables);
                }
                else
                {
                    fixediter++;
                    bool fixedsomething = false;
                    //fix variables above 0.5
                    foreach (var val in solution)
                    {
                        if (val.Value > 0.5 && !Fixedvar.ContainsKey(val.Key))
                        {
                            Fixedvar.Add(val.Key, dictvariables[val.Key]);
                            dictvariables[val.Key].LB = 1;
                            fixedsomething            = true;
                        }
                    }
                    if (!fixedsomething)
                    {
                        break;
                    }
                    cplex.Solve();
                    Console.WriteLine("The Fixing iterations is {0}", cplex.GetObjValue());
                    duals = getDuals(cplex, dictconstraints);
                }
            }

            foreach (var vari in Fixedvar.Values)
            {
                vari.LB = 0;
            }
            IConversion IP = cplex.Conversion(dictvariables.Values.ToArray(), NumVarType.Int);

            cplex.Add(IP);
            cplex.SetParam(Cplex.DoubleParam.TiLim, 600);
            cplex.Solve();

            solution = getSolution(cplex, dictvariables);
            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());
        }
Beispiel #47
0
 public IAsyncOperation <string> GetValueInRangeAsync(IRange range, EndOfLinePreference eol)
 {
     throw new NotImplementedException();
 }
 public ColorInformation(Color color, IRange range)
 {
     Color = color;
     Range = range;
 }
        /// <summary>
        /// Update source DataTable
        /// </summary>
        /// <param name="rng"></param>
        private void UpdateSourceDataTable(IRange rng)
        {
//            m_suspendUpdates = true;
            try
            {
                IValues values = (IValues)worksheet;

                var errorMessages  = new List <string>();
                int maxRowIndex    = rng.Row + rng.RowCount;
                int maxColumnIndex = rng.Column + rng.ColumnCount;
                for (int r = rng.Row; r < maxRowIndex; r++)
                {
                    for (int c = rng.Column; c < maxColumnIndex; c++)
                    {
                        // source DataTable is offset one row from spreadsheet because of header row
                        // only update where spreasheet and DataTable overlap
                        if (r <= m_dataTable.Rows.Count &&
                            c < m_dataTable.Columns.Count &&
                            r > 0 && // don't change column header
                            c > 0    // don't allow date column
                            )
                        {
                            // TO DO.. append rows to datatable?
                            // TO DO.. allow dates?
                            IValue val = values[r, c];
                            if (val == null)
                            {
                                m_dataTable.Rows[r - 1][c] = DBNull.Value;
                            }
                            else
                            if (m_dataTable.Columns[c].DataType == typeof(double))
                            {
                                double d = Reclamation.TimeSeries.Point.MissingValueFlag;
                                if (SpreadsheetGearExcel.TryReadingValue(val, out d))
                                {
                                    object o = m_dataTable.Rows[r - 1][c];
                                    if (o != DBNull.Value && Convert.ToDouble(o) == d)
                                    {
                                        continue;     // not changed (HACK To fix dragging nub
                                    }
                                    m_dataTable.Rows[r - 1][c] = d;
                                    if (AutoFlagDayFiles && interval == TimeInterval.Irregular &&
                                        rng.ColumnCount == 1)
                                    {
                                        values.SetText(r, c + 1, "e");
                                        //rng[r, c].Value = "e";
                                        m_dataTable.Rows[r - 1][c + 1] = "e";
                                    }
                                }
                                else
                                {
                                    errorMessages.Add("Invalid number on row " + r + " " + val.ToString());
                                }
                            }
                            else
                            if (m_dataTable.Columns[c].DataType == typeof(string))
                            {
                                string txt = val.Text;
                                if (txt == null)
                                {
                                    m_dataTable.Rows[r - 1][c] = DBNull.Value;
                                }
                                else
                                {
                                    m_dataTable.Rows[r - 1][c] = txt;
                                }
                            }
                        }
                    }
                }

                if (errorMessages.Count > 0)
                {
                    MessageBox.Show(String.Join("\n", errorMessages.ToArray()));
                }
            }
            finally
            {
                //  m_suspendUpdates = false;
            }

            // OnUpdateCompleted(EventArgs.Empty);
        }
Beispiel #50
0
 ///<summary>copy constructor</summary>
 public Range(IRange r) : this(r.Start, r.End)
 {
 }
Beispiel #51
0
 public SchemaEntry(string columnName, Type valueType, SchemaEntryType columnType, int columnLength, NullableType nullable, IRange range = null)
 {
     ColumnName     = columnName;
     ValueType      = valueType;
     ColumnType     = columnType;
     ColumnLength   = columnLength;
     ColumnNullable = nullable;
     Range          = range;
 }
Beispiel #52
0
 public virtual TSpectrum FilterByIntensity(IRange <double> intensityRange)
 {
     return(FilterByIntensity(intensityRange.Minimum, intensityRange.Maximum));
 }
        private IRange SearchSheet(IWorksheet xlSheet, string what)
        {
            IRange findedRange = xlSheet.Range.Find(what, null, FindLookIn.Values, LookAt.Whole, SearchOrder.ByColumns, SearchDirection.Next, true);

            return(findedRange);
        }
Beispiel #54
0
 public virtual TSpectrum Extract(IRange <double> mzRange)
 {
     return(Extract(mzRange.Minimum, mzRange.Maximum));
 }
Beispiel #55
0
 public DoubleRange(IRange <double> range)
     : base(range.Minimum, range.Maximum)
 {
 }
Beispiel #56
0
 /// <summary>
 /// Checks if this spectrum contains any peaks within the range
 /// </summary>
 /// <param name="range"></param>
 /// <returns></returns>
 public virtual bool ContainsPeak(IRange <double> range)
 {
     return(ContainsPeak(range.Minimum, range.Maximum));
 }
Beispiel #57
0
 public virtual bool TryGetIntensities(IRange <double> rangeMZ, out double intensity)
 {
     return(TryGetIntensities(rangeMZ.Minimum, rangeMZ.Maximum, out intensity));
 }
Beispiel #58
0
 ISpectrum ISpectrum.Extract(IRange <double> mzRange)
 {
     return(Extract(mzRange.Minimum, mzRange.Maximum));
 }
Beispiel #59
0
 ISpectrum <TPeak> ISpectrum <TPeak> .Extract(IRange <double> mzRange)
 {
     return(Extract(mzRange));
 }
Beispiel #60
0
 public virtual bool TryGetPeaks(IRange <double> rangeMZ, out List <TPeak> peaks)
 {
     return(TryGetPeaks(rangeMZ.Minimum, rangeMZ.Maximum, out peaks));
 }