embeddedSplit.gms : Splitting of labels using the embedded code facility

Description

The embedded code facility allows to integrate external code (e.g. Python) during
both compile and execution time of a GAMS program. GAMS symbols are shared with
the external code, so no communication via disk is necessary.

This example demonstrates how to split GAMS labels in Python at GAMS compilation
time to generate new set elements.

Contributor: Lutz Westermann, July 2017


Category : GAMS Data Utilities library


Main file : embeddedSplit.gms   includes :  embeddedSplit.gms

$Title Splitting of labels using the embedded code facility

$ontext
The embedded code facility allows to integrate external code (e.g. Python) during
both compile and execution time of a GAMS program. GAMS symbols are shared with
the external code, so no communication via disk is necessary.

This example demonstrates how to split GAMS labels in Python at GAMS compilation
time to generate new set elements.

Contributor: Lutz Westermann, July 2017
$offtext


* On the major platforms, GMSPYTHONHOME gets set automatically, otherwise the user has to set it
* This condition can also be removed, if one has set up its Python environment appropriately
$escape &
$if "%sysenv.GMSPYTHONHOME%"=="%&sysenv.GMSPYTHONHOME%&" $abort.noError Embedded code Python not ready to be used


Set cc      / "France - Paris", "France - Lille", "France - Toulouse"
              "Spain - Madrid", "Spain - Cordoba", "Spain - Seville", "Spain - Bilbao"
              "USA - Washington DC", "USA - Houston", "USA - New York",
              "Germany - Berlin", "Germany - Munich", "Germany - Bonn" /
    country / system.empty /
    city    / system.empty /
    mccCountry(cc,country)  Mapping between country and related elements in set cc
    mccCity(cc,city)        Mapping between city and related elements in set cc;


* Embedded Python code:
* - GAMS set "cc" is read from GAMS as a list
* - Each element of "cc" is split into two elements stored in "country" and "city"
* - The mappings "mccCountry" and "mccCity" are built up in parallel
* - "Country", "city", "mccCountry" and "mccCity" get written back to GAMS
$onEmbeddedCode Python:
  mccCountry = []
  mccCity = []
  country = set()
  city = set()
  for cc in gams.get("cc"):
    r = str.split(cc, " - ", 1)
    mccCountry.append((cc,r[0]))
    mccCity.append((cc,r[1]))
    country.add(r[0])
    city.add(r[1])
  gams.set("country",country)
  gams.set("city",city)
  gams.set("mccCountry",mccCountry)
  gams.set("mccCity",mccCity)
$offEmbeddedCode country city mccCountry mccCity

option mccCountry:0:0:1, mccCity:0:0:1;
display country, city, mccCountry ,mccCity;