Skip to content
Snippets Groups Projects
CalorieManager.java 2.42 KiB
Newer Older
package ac.ed.lurg.demand;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

import ac.ed.lurg.ModelConfig;
import ac.ed.lurg.country.CountryManager;
import ac.ed.lurg.country.SingleCountry;
import ac.ed.lurg.types.CommodityType;
import ac.ed.lurg.utils.LogWriter;

public class CalorieManager {
	private static final int COUNTRY_COL = 0; 
	private static final int COMMODITY_COL = 1; 
	private static final int CALORIE_PER_G_COL = 2; 


	private Map<SingleCountry, Map<CommodityType, Double>> calorieMap = new HashMap<SingleCountry, Map<CommodityType, Double>>();

	public CalorieManager() {
		super();
		read();
	}
	
	public void read() {
		String filename = ModelConfig.CALORIE_PER_T_FILE;
		try {
			BufferedReader fitReader = new BufferedReader(new FileReader(filename)); 
			String line, countryName, commodityName;
			double kcalPerT;
			fitReader.readLine(); // read header

			while ((line=fitReader.readLine()) != null) {
				String[] tokens = line.split(",");
				
				if (tokens.length < 3)
					LogWriter.printlnError("Too few columns in " + filename + ", " + line);
				
				countryName = tokens[COUNTRY_COL];
				commodityName = tokens[COMMODITY_COL];
				kcalPerT = Double.parseDouble(tokens[CALORIE_PER_G_COL]);
			

				SingleCountry country = CountryManager.getForName(countryName);
				if (country == null)
					LogWriter.printlnError("Null country for" + countryName);
				else {
					CommodityType commodity = CommodityType.getForFaoName(commodityName);
					
					Map<CommodityType, Double> commodityMap = calorieMap.get(country);
					if (commodityMap == null) {
						commodityMap = new HashMap<CommodityType, Double>();
						calorieMap.put(country, commodityMap);
					}
					
					commodityMap.put(commodity, kcalPerT);
				}
			} 
			fitReader.close(); 
		
		} catch (Exception e) {
			LogWriter.printlnError("Failed in reading country specific calorie per t values");
			LogWriter.print(e);
		}
		LogWriter.println("Processed " + filename + ", create " + calorieMap.size() + " calorie per t values");
	}
	
	public Map<CommodityType, Double> get(SingleCountry country) {
		Map<CommodityType, Double> commodityMap = calorieMap.get(country);

		if (commodityMap == null) {
				LogWriter.printlnError("CalorieManager: can't calorie get values for " + country);
			return null;
		}

		return commodityMap;
	}
}