Decision Optimization

Decision Optimization

Delivers prescriptive analytics capabilities and decision intelligence to improve decision-making.

 View Only
  • 1.  How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Tue June 13, 2023 09:35 AM

    Hi, 

    I have been trying to write an application where I have a model (.mod file) and I have data (.dat file), where my goal is, to populate the model with the data and get solution in text file. 

    Here's what I am trying to do:

           try
            {
        
    
                Cplex cplex = new Cplex();
                cplex.ImportModel(mfile);
                cplex.ReadParam(sfile);         
    
                SolutionData sol = new SolutionData();
                if (cplex.Solve())
                {
                    sol.obj = cplex.ObjValue;
                    sol.vals = cplex.GetValues(data.vars);
                }
                System.Console.WriteLine("Sol Status > {0}", cplex.GetCplexStatus());
                sol.status = cplex.GetCplexStatus();
    
                
    
                cplex.End();
            }
            catch (System.Exception t)
            {
                System.Console.WriteLine("server terminates due to " + t);
            }

    It seems exceptions are always thrown in this case and I do not know how to progress from here.

    Any help would be appreciated.



    ------------------------------
    Mohannad Mostafa
    ------------------------------


  • 2.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Tue June 13, 2023 11:34 AM

    Hi,

    Can you confirm that the 'mfile' variable in your code is referring to a file whose format is readable by Cplex ImportModel method (lp, sav or mps).
    The ImportModel cannot read ".mod" files.

    Could you also provide the details of the exceptions that were raised ?

    Best regards,



    ------------------------------
    Hugues Juille
    ------------------------------



  • 3.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Tue June 13, 2023 02:21 PM
    Edited by Mohannad Mostafa Tue June 13, 2023 02:21 PM

    Hello Hugues, 

    .mod file contains IBM CPLEX program

    Here's a snippet of the file, note that when I test on IBM CPLEX IDE, I use the below code to test.

    /*********************************************
     * OPL 12.8.0.0 Model
     * Author: 
     * Creation Date: Feb 25, 2023 at 6:38:33 AM
     *********************************************/
    
    using CP;
    
    int   NbTasks = ...;
    int   NbRsrcs = ...;
    float IndirectCost = ...;
    float Deadline = ...;
    float Penalty = ...;
    float Incentive = ...;
    
    range RsrcIds = 0..NbRsrcs-1; 
    int CapRsrc [RsrcIds] = ...;
    
    tuple Task {
      key int id;
      int     nmodes;
      {int}   FSSuccs; 
      {int}   FSLags;   
      {int}   SSSuccs;
      {int}   SSLags;                 
      {int}   FFSuccs; 
      {int}   FFLags; 
      {int}   SFSuccs;     
      {int}   SFLags; 
      int     mile;         
      float   milecost;
      float   milebonus;
      int     intialstart;
      int     intialdur;            
    }
    {Task} Tasks = ...;
    
    tuple Mode {
      key int taskId;
      key int id;
      int     duration;
      int     dmd [RsrcIds];
      float cost;
    }
    {Mode} Modes = ...;
    
    //task mode is correlated with another task mode
    tuple Correlation {
      int taskId1;
      int taskId2;
      int id1;  
      int id2;
    }
    {Correlation} Correlations = ...;
    
    
    //Decision Variables
    dvar interval task[t in Tasks];
    dvar interval mode[m in Modes] optional  size m.duration;
    
    //Accumulated Resources
    cumulFunction RsrcUsage[r in RsrcIds] = 
      sum (m in Modes: m.dmd[r]>0) pulse(mode[m], m.dmd[r]);
    
    // Model parameters
    execute {
      cp.param.FailLimit = 100000;
       cp.param.timeLimit=600;
    }

    Then, I have .dat file which basically should populate the information in the model, it's in this format:

    NbTasks = 37;
    NbRsrcs = 2;
    IndirectCost = 1000;
    Deadline = 55;
    Penalty = 20000;
    Incentive = 5000;
    CapRsrc = [40, 20];
    
    Tasks = {
    < 1 , 1 , {} , {} , {} , {} , {} , {} , {} , {} , 0 , 0, 0, 0, 0 >
    ....
    };
    
    Modes = {
    < 1, 1, 0, [ 0,0 ], 0 >
    ....
    };
    
    Correlations ={
    <0,0,0,0>
    };
    
    

    What method allows me to use the program I have in .mod file and then populate the program with data, and send it to CPLEX and getting back the solution on text file?

    For your information, I have seen a solution in VB where someone was able to do that and test it, here's the code for reference, I want to do the same thing in C#. Note that ModelPath refers to same .mod file and dataPath refers to .dat file which includes the data for the model.

            Dim oplF As OplFactory = New OplFactory()
            Dim errorHandler As OplErrorHandler = oplF.CreateOplErrorHandler()
    
            Dim modelSource As OplModelSource = oplF.CreateOplModelSource(ModelPath)
            Dim settings As OplSettings = oplF.CreateOplSettings(errorHandler)
            settings.IsWithNames = True
            settings.IsWithLocations = True
            Dim def As OplModelDefinition = oplF.CreateOplModelDefinition(modelSource, settings)
    
    
    
    
            Dim CPLEX As Cplex = oplF.CreateCplex()
            CPLEX.SetOut(Nothing)
    
    
            Dim opl As OplModel = oplF.CreateOplModel(def, CPLEX)
    
            'Dim dataSource As OplDataSource = New MyParams(oplF, sheet)
            Dim dataSource As OplDataSource = oplF.CreateOplDataSource(DataPath)
            opl.AddDataSource(dataSource)
            Console.Out.WriteLine("......Genertaing CPLEX Mode") 
            opl.Generate() : Console.Out.WriteLine("......Solving Problem") 
    
            If (CPLEX.Solve()) Then
    
    
                SolutionToFile(opl, "C:\123.txt") ' save solution to Text File 
    
            Else
                Console.Out.WriteLine("No solution!")
                MsgBox("No solution exists. You may change CPLEX settings and try again!", MsgBoxStyle.Information)
            End If
            oplF.End()
    
            Response.Write("Done")



    ------------------------------
    Mohannad Mostafa
    ------------------------------



  • 4.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Tue June 13, 2023 02:31 PM

    Dear Mohannad,

    The first thing that hits me is that your OPL file is a model for CP optimizer (it contains the statement: 

    using CP;

    and uses some constructs that are specific to the CP solver (like: "interval", or "cumulFunction").
    Therefore, this model cannot be exported and re-imported as a Cplex model.

    You'll have to reformulate your problem as a Cplex model first.

    Indeed, Cplex Studio embeds 2 solvers. A constraints-based solver (CP optimizer) and a Mathematical Programming solver (Cplex).
    The "using CP" statement indicates that the following model formulation is for a CP solver (and allows the use of specific constructs for the model formulation).

    Best regards,



    ------------------------------
    Hugues Juille
    ------------------------------



  • 5.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Tue June 13, 2023 10:38 PM
    Edited by Mohannad Mostafa Wed June 14, 2023 01:31 AM

    Hi Hugues,

    thank you for getting back to me fast. Can you point me to documentation where I can reformulate my problem as a cplex model?

    Why does the VB program work this way? I am sure it's working because i can run it as is on my machine. Is there similer function for C#?

    is there an example that I can look at which can help me getting started on this?

    also, how can I import the data to the model after reformulating the model as a cplex model?

    thank you,

    Mohannad



    ------------------------------
    Mohannad Mostafa
    ------------------------------



  • 6.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Wed June 14, 2023 05:00 AM

    Hi Mohannad,

    Unfortunately, there are no single methodology I'm aware of to re-formulate a CP scheduling problem into a Cplex model.

    Documentation about CP and Cplex is delivered with COS installation and many resources are available on the net.

    I don't know all your technical requirements, but I was wondering whether you have to use Cplex for your C# implementation ?

    Indeed, the CP engine also provides a C# API for importing a ".mod" file (using the same "public void importModel(const char * filename) const" method...

    Also, if your goal is to integrate the call to CP or Cplex for solving an OPL model (serialized as ".mod" and ".dat" files) in an application, you might be interested to have a look at the sample delivered with Cplex Optimization Studio, in the folder: "CPLEX_Studio2211\opl\examples\opl_interfaces\dotnet\x64_windows_msvc14\CSharp\OplRunSample"

    I'm not sure I've understood exactly what you want to do... I hope this helps.

    Best regards,



    ------------------------------
    Hugues Juille
    ------------------------------



  • 7.  RE: How to send model file and data file to CPLEX and get solution in a text file in C#

    Posted Wed June 14, 2023 12:16 PM

    Thank you Hugues, The example you have posted is exactly what I was looking for. I really appreciate your quick response on this thread.



    ------------------------------
    Mohannad Mostafa
    ------------------------------