Data membership consistency

Explains the use of the with keyword to ensure data consistency.

The keyword with enables you to indicate that a given element of a tuple must be contained in a given set. If you use it, OPL checks the consistency of the tuple set at run time when initializing the set. The syntax is:


{tupletype} tupleset with cell1 in set1, cell2 in set = ...; 

Let's take an example. You have a set of arcs between nodes. Nodes are defined by a tuple set of tuples consisting of an origin node and a destination node. The with syntax enables you to ensure that the origin and destination nodes do belong to a given set of nodes. Compare Data found inconsistent (keyword with) and Data found consistent (keyword with):

Data found inconsistent (keyword with)

{int} nodes = {1, 5, 7};
 
tuple arc  {
  int origin;
  int destination;
}
 
{arc} arcs2 with origin in nodes, destination in nodes = 
  {<1,4>, <5,7>};
 
execute {
  writeln(arcs2);
};

Data found consistent (keyword with)

{int} nodes = {1, 5, 7};
 
tuple arc  {
  int origin;
  int destination;
}
 
{arc} arcs1 with origin in nodes, destination in nodes = 
  {<1,5>, <5,7>};
 
execute {
  writeln(arcs1);
};

If you write Data found inconsistent (keyword with), an error will be raised when the set arcs2 is initialized because the with syntax will detect that the statement


(int) nodes = (1, 5, 7);

is not consistent with the statement


with origin in nodes, destination in nodes = 
  {<1,4>, <5,7>}

If you write Data found consistent (keyword with), the initialization of the set arcs1 will work properly because the with syntax will find that the statement


(int) nodes = (1, 5, 7);

is consistent with the statement


with origin in nodes, destination in nodes = 
  {<1,5>, <5,7>}

Initializing tuple sets referring to other sets

To initialize tuple sets that refer to other sets with keys for data consistency, you must use initialization expressions that provide only those key values, as shown in Initializing tuple sets referring to other sets. This is true if you initialize those tuple sets as internal data or as external data in .dat files, databases, or spreadsheets.

Initializing tuple sets referring to other sets

tuple node
{
  key int node_id;
  string city;
  string country;  
}

{node} nodes = {<1,"Paris","France">,<5,"Madrid","Spain">, <7,"New York","USA">};
 
tuple arc  {
  node origin;
  node destination;
}
 
{arc} arcs1 with origin in nodes, destination in nodes=...;

execute {
  writeln(arcs1);
};