Newer
Older
import com.gams.api.GAMSDatabase;
import com.gams.api.GAMSGlobals;
import com.gams.api.GAMSJob;
import com.gams.api.GAMSOptions;
import com.gams.api.GAMSParameter;
import com.gams.api.GAMSSet;
import com.gams.api.GAMSVariable;
import com.gams.api.GAMSVariableRecord;
import com.gams.api.GAMSWorkspace;
import com.gams.api.GAMSWorkspaceInfo;
public class GamsLocationOptimiser {
private GamsLocationInput inputData;
public GamsLocationOptimiser(GamsLocationInput inputData) {
public GamsLocationOutput run() {
File workingDirectory = new File(ModelConfig.TEMP_DIR, "GamsTest");
workingDirectory.mkdir();
GAMSWorkspaceInfo wsInfo = new GAMSWorkspaceInfo();
wsInfo.setWorkingDirectory(workingDirectory.getAbsolutePath());
GAMSDatabase inDB = ws.addDatabase();
setupInDB(inDB);
GAMSJob gamsJob = ws.addJobFromFile(ModelConfig.GAMS_MODEL);
GAMSOptions opt = ws.addOptions();
opt.defines("gdxincname", inDB.getName());
long startTime = System.currentTimeMillis();
gamsJob.run(opt, inDB);
LogWriter.println("Took " + (System.currentTimeMillis() - startTime) + " ms to run");
return handleResults(gamsJob.OutDB());
}
private void setupInDB(GAMSDatabase inDB) {
LogWriter.println("\nLocation set");
GAMSSet locationSet = inDB.addSet("location", 1);
for (Integer locId : inputData.getPreviousAreas().keySet()) {
LogWriter.println(" " + locId);
locationSet.addRecord(locId.toString());
}
addItemMapParm(param, inputData.getCountryInput().getProjectedDemand());
GAMSParameter yNoneP = inDB.addParameter("yieldNone", 2);
GAMSParameter y_fert = inDB.addParameter("yieldFertOnly", 2);
GAMSParameter y_irrig = inDB.addParameter("yieldIrrigOnly", 2);
GAMSParameter y_both = inDB.addParameter("yieldBoth", 2);
GAMSParameter fert_p = inDB.addParameter("fertParam", 2);
GAMSParameter irrig_p = inDB.addParameter("irrigParam", 2);
for (Entry<Integer, ? extends YieldResponsesItem> cropsForALocation : inputData.getYields().entrySet()) {
String locString = Integer.toString(locationId);
YieldResponsesItem yresp = cropsForALocation.getValue();
for (CropType crop : CropType.values()) {
LogWriter.println(String.format(" %15s,\t %.1f", crop.getGamsName(), yresp.getYieldNone(crop)));
yNoneP.addRecord(v).setValue(yresp.getYieldNone(crop));
y_fert.addRecord(v).setValue(yresp.getYieldFertOnly(crop));
y_irrig.addRecord(v).setValue(yresp.getYieldIrrigOnly(crop));
y_both.addRecord(v).setValue(yresp.getYieldMax(crop));
fert_p.addRecord(v).setValue(yresp.getFertParam(crop));
irrig_p.addRecord(v).setValue(yresp.getIrrigParam(crop));
param = inDB.addParameter("world_input_energy", 1, "average input energy from world exports used to determine if we should import or export energy per t");
addItemMapParm(param, inputData.getCountryInput().getWorldInputEnergy());
param = inDB.addParameter("maxNetImport", 1, "max net imports for each crop based on world market");
addItemMapParm(param, inputData.getCountryInput().getMaxNetImport());
param = inDB.addParameter("minNetImport", 1, "min net imports for each crop based on world market");
addItemMapParm(param, inputData.getCountryInput().getMinNetImport());
addScalar(inDB.addParameter("meatEfficency", 0, "efficency of converting feed and pasture into animal products"), inputData.getCountryInput().getMeatEfficiency());
addScalar(inDB.addParameter("maxLandUseChange", 0, "max rate of land use change"), inputData.getCountryInput().getMaxLandUseChange());
addScalar(inDB.addParameter("tradeBarrier", 0, "trade barrier which adjust energy cost of imports"), inputData.getCountryInput().getTradeBarrier());
addScalar(inDB.addParameter("landChangeEnergy", 0, "energy required to add ha of agricultural land"), inputData.getCountryInput().getLandChangeEnergy());
addScalar(inDB.addParameter("minFeedRate", 0, "minimum rate of feed for producing animal products"), inputData.getCountryInput().getMinFeedRate());
private GamsLocationOutput handleResults(GAMSDatabase outDB) {
int modelStatus = (int) outDB.getParameter("ms").findRecord().getValue();
System.out.println(
"\nModelstatus: " + GAMSGlobals.ModelStat.lookup( modelStatus ) +
", Solvestatus: " + GAMSGlobals.SolveStat.lookup((int) outDB.getParameter("ss").findRecord().getValue()) );
GAMSVariable varAreas = outDB.getVariable("area");
GAMSVariable varFertIntensities = outDB.getVariable("fertI");
GAMSVariable varIrrigIntensities = outDB.getVariable("irrigI");
GAMSVariable varOtherIntensities = outDB.getVariable("otherIntensity");
GAMSVariable varFeedAmount = outDB.getVariable("feedAmount");
GAMSVariable varNetImports = outDB.getVariable("netImportAmount");
double area, fertIntensity, irrigIntensity, otherIntensity, feedAmount, netImport;
Map<Integer, IntensitiesItem> intensities = new HashMap<Integer, IntensitiesItem>();
Map<Integer, AreasItem> cropAreas = new HashMap<Integer, AreasItem>();
Map<CropType, CommodityData> commoditiesData = new HashMap<CropType, CommodityData>();
CropType prevCropType = null;
String locationName = rec.getKeys()[1];
fertIntensity = varFertIntensities.findRecord(itemName, locationName).getLevel();
irrigIntensity = varIrrigIntensities.findRecord(itemName, locationName).getLevel();
otherIntensity = varOtherIntensities.findRecord(itemName, locationName).getLevel();
int locId = Integer.parseInt(locationName);
CropType cropType = CropType.getForGamsName(itemName);
if (!cropType.equals(prevCropType)) {
feedAmount = varFeedAmount.findRecord(itemName).getLevel();
netImport = varNetImports.findRecord(itemName).getLevel();
commoditiesData.put(cropType, new CommodityData(feedAmount, netImport));
LogWriter.println(String.format("\n%s:\tfeedAmount= %.1f,\tnetImports= %.3f", itemName, feedAmount, netImport));
}
if (area > 0) {
LogWriter.println(String.format("\t location %s, %s:\tarea= %.1f,\tfert= %.3f,\tirrg= %.3f,\tintensity= %.3f",
locationName, itemName, area, fertIntensity, irrigIntensity, otherIntensity));
intensityItem.setIntensity(cropType, new Intensity(fertIntensity, irrigIntensity, otherIntensity));
cropAreas.put(locId, areaItem);
}
areaItem.setCropArea(cropType, area);
prevCropType = cropType;
LogWriter.println(String.format("\nTotal area= %.1f", totalArea));
GamsLocationOutput results = new GamsLocationOutput(modelStatus, intensities, cropAreas, commoditiesData);
}
private void addScalar(GAMSParameter param, double val) {
param.addRecord().setValue(val);
}
private void addItemMapParm(GAMSParameter parm, Map<CropType, Double> itemMap) {
for (Map.Entry<CropType, Double> entry : itemMap.entrySet()) {
LogWriter.println(String.format(" %15s,\t %.1f", entry.getKey().getGamsName(), entry.getValue()));
parm.addRecord(entry.getKey().getGamsName()).setValue(entry.getValue());
}
}
private void addAreaParms(GAMSDatabase inDB, Map<Integer, ? extends AreasItem> locationItemMap) {
GAMSParameter prevCropP = inDB.addParameter("previous_area", 2);
GAMSParameter landP = inDB.addParameter("landArea", 1);
for (Map.Entry<Integer, ? extends AreasItem> cropsForALocation : locationItemMap.entrySet()) {
String locString = Integer.toString(locationId);
AreasItem areasItem = cropsForALocation.getValue();
LogWriter.println(String.format(" %d %15s,\t %.1f", locationId, cropType.getGamsName(), d));
landP.addRecord(locString).setValue(areasItem.getLandCoverArea(LandDataType.LAND));
@SuppressWarnings("unused")
private void cleanup(String directory) {
File directoryToDelete = new File(directory);
String files[] = directoryToDelete.list();
for (String file : files) {
File fileToDelete = new File(directoryToDelete, file);
try {
fileToDelete.delete();
} catch(Exception e){
e.printStackTrace();
}
}
try {
directoryToDelete.delete();
} catch(Exception e) {
e.printStackTrace();
}
}