V2_0.java [src/java/m/rhem/rhem01_runmodel] Revision: 58d01245ce44e7dee3d5c5455f63b213facb8488  Date: Mon Oct 24 14:26:24 MDT 2022
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API, and application suite.
 *
 * 2012-2020, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package m.rhem.rhem01_runmodel;

import csip.api.server.Executable;
import csip.ModelDataService;
import csip.api.client.ModelDataServiceCall;
import csip.api.server.ServiceException;
import csip.annotations.Polling;
import csip.annotations.Resource;
import java.io.IOException;
import java.sql.Connection;
import javax.ws.rs.Path;
import m.rhem.model.AoA;
import m.rhem.model.Parameter;
import m.rhem.model.RhemModel;
import csip.annotations.Description;
import csip.annotations.Name;
import csip.utils.Parallel;
import csip.utils.TextParser;
import java.io.File;
import m.rhem.ApplicationResources;
import static m.rhem.ApplicationResources.DEFAULT_MOISTURE_CONTENT;
import static m.rhem.ApplicationResources.RHEM4_INTL_EXE;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import m.rhem.DBResources;
import rhem.utils.RHEMUtils;

/**
 * RHEM-01:Run RHEM Model
 *
 * @version 2.0
 * @author <a href="mailto:shaun.case@colostate.edu">Shaun Case</a>
 */
@Name("RHEM-01:Run RHEM Model")
@Description("Run RHEM Model utilizing parameters including climate station, "
    + "surface soil texture class, slope percent and length, and vegetative "
    + "cover characteristics (bunchgrass, forbs/annual, shrub, and sodgrass "
    + "foliar cover; plant basal cover; rock cover; litter cover; and "
    + "cryptogam cover. This version uses PRISM/cligen")
@Path("m/rhem/runrhem/2.0")
@Polling(first = 10000, next = 2000)
@Resource(from = DBResources.class)
@Resource(from = ApplicationResources.class)
public class V2_0 extends ModelDataService {

  static final String CLIGEN_RECORD_PRISM_PAR = "cligenRecordPrism.par";
  static final String CLIGEN_RECORD_PAR = "cligenRecord.par";
  static final String CLIGEN_TXT = "cligen.txt";

  AoA aoa;
  String parameterFileName;
  String stormFileName;
  String summaryFileName;
  String runFileName;
  String detailedOutputFileName;
  Parameter parameter;

  RhemModel rhemModel;

  double[] latlon;

  ModelDataServiceCall res;


  @Override
  public void preProcess() throws ServiceException {

    int aoaId = parameter().getInt("AoAID", 0);
    int rhemSiteId = parameter().getInt("rhem_site_id", 0);

    latlon = parameter().getDoubleArray("rhem_site_loc");

    String scenarioName = parameter().getString("scenarioname");
    String scenarioDescription = parameter().getString("scenariodescription");

    String soilTexture = parameter().getString("soiltexture");
    String slopeShape = parameter().getString("slopeshape");
    double slopeSteepness = parameter().getDouble("slopesteepness", 0.01);
    double bunchGgrassCanopyCover = parameter().getDouble("bunchgrasscanopycover", 0.0);
    double forbsCanopyCover = parameter().getDouble("forbscanopycover", 0.0);
    double shrubsCanopyCover = parameter().getDouble("shrubscanopycover", 0.0);
    double sodGrassCanopyCover = parameter().getDouble("sodgrasscanopycover", 0.0);
    double basalCover = parameter().getDouble("basalcover", 0.0);
    double rockCover = parameter().getDouble("rockcover", 0.0);
    double litterCover = parameter().getDouble("littercover", 0.0);
    double cryptogamsCover = parameter().getDouble("cryptogamscover", 0.0);
    double sar = parameter().getDouble("sar", 0.0);

    ///////////////////////////////
    //  BEGIN  Validations of input 
    //The values allowed for the field unit in the request are 1 and 2. 1 is for metric units and 2 is for English units
    if (latlon.length != 2) 
      throw new ServiceException("Invalid rhem_site_loc, array expected [lat,lon]");
    

    if (sar < 0.0 || sar > 50.0) 
      throw new ServiceException("Invalid sar (0.0 ... 50.0): " + sar);
    

    double slopeLength = RHEMUtils.getSlopelength(parameter());

    if (slopeSteepness <= 0.0) 
      throw new ServiceException("'slopesteepness' parameter must be greater than 0.");
    

    //  END Validations
    ///////////////////////////////
    aoa = new AoA(aoaId, rhemSiteId, scenarioName,
        scenarioDescription,
        soilTexture, slopeShape, slopeSteepness,
        bunchGgrassCanopyCover, forbsCanopyCover, shrubsCanopyCover,
        sodGrassCanopyCover, basalCover, rockCover, litterCover,
        cryptogamsCover, DEFAULT_MOISTURE_CONTENT, sar);

    parameter = new Parameter(slopeLength);
  }


  @Override
  public void doProcess() throws Exception {
    String fileName = aoa.getScenarioName();
    if (fileName.length() > 15) 
      fileName = fileName.substring(0, 15);
    
    fileName = fileName.replace(' ', '_');

    parameterFileName = "scenario_input_" + fileName + ".par";
    stormFileName = "storm_input_" + fileName + ".pre";
    summaryFileName = "scenario_output_summary_" + fileName + ".sum";
    detailedOutputFileName = "scenario_output_summary_" + fileName + ".out";
    runFileName = fileName + ".run";

    Parallel.run(
        () -> {
          try (Connection con = resources().getJDBC(DBResources.CRDB)) {
            parameter.computeParameters(con, aoa);
          }
          rhemModel = new RhemModel(aoa.getScenarioName(), workspace().getDir(), parameterFileName,
              stormFileName, runFileName, summaryFileName);

          rhemModel.generateParamFile(parameter);
          rhemModel.generateRunFile();
        },
        () -> {
          res = fetchClimate(stormFileName);
        }
    );

    runModel();
  }


  private ModelDataServiceCall fetchClimate(String stormfileName) throws JSONException, Exception {
    ModelDataServiceCall res = new ModelDataServiceCall()
        .put("duration", 300)
        .put("outputFile", CLIGEN_TXT)
        .put("usePRISM", true)
        .put("returnParFiles", true)
        .put("input_zone_features", new JSONObject(
            "{     'type': 'FeatureCollection',"
            + "        'features': [{"
            + "          'type': 'Feature',"
            + "          'properties': {"
            + "            'name': 'pt one',"
            + "            'gid': 1"
            + "          },"
            + "          'geometry': {"
            + "            'type': 'Point',"
            + "            'coordinates': [" + latlon[1] + "," + latlon[0] + "]"
            + "          }"
            + "        }]"
            + "}"))
        .url(ApplicationResources.cligenUrl)
        .withDefaultLogger()
        .call();

    if (res.serviceFinished()) {
      res.download(CLIGEN_TXT, workspace().getFile(stormfileName));
      res.download(CLIGEN_RECORD_PAR, workspace().getFile(CLIGEN_RECORD_PAR));
      res.download(CLIGEN_RECORD_PRISM_PAR, workspace().getFile(CLIGEN_RECORD_PRISM_PAR));
      return res;
    } else {
      throw new ServiceException("Climate service error: " + res.getError());
    }
  }


  private void runModel() throws ServiceException, IOException {
    Executable rh = resources().getExe(RHEM4_INTL_EXE);
    rh.setArguments("-b", workspace().getFile(runFileName));
    int run = rh.exec();
    if (run != 0) {
      throw new ServiceException("Error running rhem: " + run);
    }
  }


  @Override
  public void postProcess() throws Exception {
    File sumFile = workspace().getFile(summaryFileName);

    results().put("AoAID", aoa.getAoaId(), "Area of Analysis Identifier");
    results().put("rhem_site_id", aoa.getRhemSiteId(), "RHEM Evaluation Site Identifier");
    results().put("CLEN", parameter.getClen(), "characteristic length of hillsope");
    results().put("DIAMS", parameter.getDiams(), "list of representative soil particle diameters for up to 5 particle classes");
    results().put("DENSITY", parameter.getDensity(), "list of densities corresponding to the DIAMS particle classes");
    results().put("CHEZY", parameter.getChezy(), "overland flow Chezy coefficient");
    results().put("RCHEZY", parameter.getRchezy(), "concentrated flow Chezy coefficient");
    results().put("SL", parameter.getSl(), "slope expressed as fractional rise/run");
    results().put("SX", parameter.getSx(), "normalized distance");
    results().put("KSS", parameter.getKss(), "splash and sheet erodibility coefficient");
    results().put("KE", parameter.getKe(), "effective hydraulic conductivity");
    results().put("G", parameter.getG(), "mean capillary drive");
    results().put("DIST", parameter.getDist(), "pore size distribution index");
    results().put("POR", parameter.getPor(), "porosity");
    results().put("FRACT", parameter.getFract(), "list of particle class fractions");

    double asl = new TextParser(sumFile).toLineContaining("Avg-Soil-Loss").rightOfFirst("=").asDouble();
    results().put("TDS", Double.parseDouble(rhemModel.getTDS(asl)), "total dissolved solids");

    results().put("cli_station_id", res.getInt("stationId", 0));
    results().put("cli_station_name", res.getString("name", "?"));
    results().put("cli_station_state", res.getInt("state"));
    results().put("cli_station_elevation", res.getDouble("elevation"));
    results().put("cli_station_lon", res.getDouble("stationX"));
    results().put("cli_station_lat", res.getDouble("stationY"));

    TextParser e = new TextParser(workspace().getFile(stormFileName));
    double[] mavg = e.toLineContaining("ave precipitation").nextLine().tokens().asDoubleArray();
    results().put("monthly_avg_precip", mavg, "monthly average precip", "mm");

    e = new TextParser(workspace().getFile(summaryFileName));
    double yavg = e.toLineContaining("Avg. Precipitation").rightOfFirst("=").asDouble();
    results().put("yearly_avg_precip", yavg, "yearly average precip", "mm");

    results().put(workspace().getFile(parameterFileName), "Parameter input file");
    results().put(workspace().getFile(stormFileName), "Storm input file");
    results().put(workspace().getFile(summaryFileName), "Summary file");
    results().put(workspace().getFile(detailedOutputFileName), "Detailed summary file");
    results().put(workspace().getFile(CLIGEN_RECORD_PAR), "Cligen Par file");
    results().put(workspace().getFile(CLIGEN_RECORD_PRISM_PAR), "Cligen Prism Par file");

//    results().put(getWorkspaceFile("temp_" + summaryFileName), "Temp Summary file");
  }

}