Beispiel #1
0
/** Deal with any error messages generated by the call to one of the service methods
 */
void reportErrors(OSCommandLine *oscommandline, std::string errormsg, OSnl2OS* nl2OS)
{
        std::string osrl = "";
        OSResult *osresult = NULL;
        OSrLWriter *osrlwriter = NULL;
        //first check to see if we already have OSrL,
        //if so don't create a new osresult object
        std::string::size_type  pos1 = errormsg.find( "<osrl");
        if(pos1 == std::string::npos)
        {
            osrlwriter = new OSrLWriter();
            osresult = new OSResult();
            osresult->setGeneralMessage(errormsg);
            osresult->setGeneralStatusType("error");
            osrl = osrlwriter->writeOSrL(osresult);
        }
        else
        {
            osrl = errormsg;
        }
        reportResults(oscommandline, osrl, nl2OS);
}// reportErrors
bool callServiceMethod(OSCommandLine* oscommandline)
{
	FileUtil *fileUtil = new FileUtil();
	try
    {
		bool result;
		OSServiceMethods *osservicemethods;
		osservicemethods = new OSServiceMethods(oscommandline);

		if (oscommandline->printModel) 
			oscommandline->osinstance->printModel();
		if (oscommandline->printRowNumberAsString != "")
			oscommandline->osinstance->printModel(atoi((oscommandline->printRowNumberAsString).c_str()));

		result = osservicemethods->executeServiceMethod(oscommandline);

		// deal with the output
		if (result == false) 
			throw ErrorClass(osservicemethods->resultString);
		else
		{
			if (oscommandline->serviceMethod == "getJobID")
			{
				std::cout << "The job ID generated by the system is:" << std::endl << std::endl;
				std::cout << osservicemethods->resultString << std::endl << std::endl;
				std::cout << "Be sure to make a record of this job ID for later." << std::endl;
				std::cout << "You will need it to retrieve the job or inquire into its status." << std::endl;
			}
			else if (oscommandline->serviceMethod == "solve" || oscommandline->serviceMethod == "retrieve")
			{
		        if (oscommandline->osrlFile != "")
				{
		            fileUtil->writeFileFromString(oscommandline->osrlFile, osservicemethods->resultString);
					if (oscommandline->browser != "")
					{
			            std::string str = oscommandline->browser + "  "
					                      + oscommandline->osrlFile;
		                const char *ch = &str[0];
				        std::system(ch);
		            }
                    std::cout <<  "\nSolve command executed. Please see " << oscommandline->osrlFile  << " for results." << std::endl;
				}
		        else
				{
		            std::cout << osservicemethods->resultString << std::endl;
				}
			}
			else if (oscommandline->serviceMethod == "kill" || oscommandline->serviceMethod == "knock")
			{
		        if (oscommandline->osplOutputFile != "")
				{
		            fileUtil->writeFileFromString(oscommandline->osplOutputFile, osservicemethods->resultString);
				}
		        else
				{
		            std::cout << osservicemethods->resultString << std::endl;
				}
			}
		}
		return 0;
    }
    catch (const ErrorClass& eclass)
    {
        OSResult *osresult = NULL;
        OSrLWriter *osrlwriter = NULL;
        osrlwriter = new OSrLWriter();
        osresult = new OSResult();
        osresult->setGeneralMessage(eclass.errormsg);
        osresult->setGeneralStatusType("error");
        std::string osrl = osrlwriter->writeOSrL(osresult);
        if (oscommandline->osrlFile != "")
        {
            fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
            if (oscommandline->browser != "")
            {
                std::string str = oscommandline->browser + "  "
                                  + oscommandline->osrlFile;
                const char *ch = &str[0];
                std::system(ch);
            }
        }
        else
        {
            std::cout << osrl << std::endl;
        }
        //catch garbage collection
        delete osresult;
        osresult = NULL;
        delete osrlwriter;
        osrlwriter = NULL;

        delete oscommandline;
        oscommandline = NULL;
        delete fileUtil;
        fileUtil = NULL;
        return 1;
    }
}
int main(int argc, char **argv)
{
    WindowsErrorPopupBlocker();
    char *stub;
    // set AMPL structures
    ASL *asl;
    asl = ASL_alloc(ASL_read_fg);
    stub = argv[1];
    jac0dim((char*)stub, (fint)strlen(stub));
    OSnl2osil *nl2osil = NULL;

    std::ostringstream outStr;
	std::cout << OSAmplClientVersionInfo();
	std::string osss;

	outStr << stub << " " << getenv("OSAmplClient_options");
    osss = outStr.str();

#ifdef DEBUG_AMPL_CLIENT
    std::cout << "Input String = " << osss << std::endl;
#endif

	FileUtil *fileUtil = NULL;
	OSCommandLine *oscommandline;
	oscommandline = new OSCommandLine();
	OSCommandLineReader *clreader;
	clreader = new OSCommandLineReader();

	//parse the command line items into a CommandLine object
    try
    {		
		oscommandline = clreader->readCommandLine(osss);
		if (oscommandline->serviceMethod == "")
			oscommandline->serviceMethod = "solve";
		oscommandline->convertSolverNametoLowerCase();

	}
    catch (const ErrorClass& eclass)
    {
        OSResult *osresult = NULL;
        osresult = new OSResult();
        osresult->setGeneralMessage(eclass.errormsg);
        osresult->setGeneralStatusType("error");
        OSrLWriter *osrlwriter = NULL;
        osrlwriter = new OSrLWriter();
        std::string osrl = osrlwriter->writeOSrL(osresult);
        if (oscommandline->osrlFile != "")
        {
            fileUtil->writeFileFromString(oscommandline->osrlFile, osrl);
            if (oscommandline->browser != "")
            {
                std::string str = oscommandline->browser + "  "
                                  + oscommandline->osrlFile;
                const char *ch = &str[0];
                std::system(ch);
            }
        }
        else
        {
            std::cout << osrl << std::endl;
        }
        //catch garbage collection
        delete osresult;
        osresult = NULL;
        delete osrlwriter;
        osrlwriter = NULL;
        delete fileUtil;
        fileUtil = NULL;
        delete oscommandline;
        oscommandline = NULL;
        delete clreader;
        clreader = NULL;
        return 1;
    }

#ifdef DEBUG_AMPL_CLIENT
	std::cout << oscommandline->list_options() << std::endl;
#endif

	// deal with "action items": help, quit, listOptions
	if (oscommandline->quit || oscommandline->invokeHelp || oscommandline->writeVersion || oscommandline->listOptions)
	{
		if (oscommandline->invokeHelp) 
			std::cout << std::endl << std::endl << get_AmplClient_help() << std::endl;
		if (oscommandline->listOptions) 
			std::cout << std::endl << std::endl << oscommandline->list_options() << std::endl;
        delete oscommandline;
        oscommandline = NULL;
        return 0;
	}

	// call service method
	bool result = callServiceMethod(oscommandline);
	if (result == true)
		return 0;
	else
		return 1;
}
TEST_F(RulesetFixture, UserScript_TestModelUserScript1) {
  TestModelUserScript1 script;
  EXPECT_EQ("TestModelUserScript1", script.name());

  TestOSRunner runner;
  std::map<std::string, OSArgument> user_arguments;

  // test with empty model
  openstudio::model::Model model1;
  EXPECT_EQ(0u, model1.getModelObjects<openstudio::model::Space>().size());
  EXPECT_EQ(0u, script.arguments(model1).size());
  script.run(model1, runner, user_arguments);
  EXPECT_EQ(1u, model1.getModelObjects<openstudio::model::Space>().size());
  OSResult result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  ASSERT_TRUE(result.initialCondition());
  EXPECT_TRUE(result.initialCondition()->logLevel() == Info);
  EXPECT_EQ("openstudio.ruleset." + script.name(),result.initialCondition()->logChannel());
  EXPECT_EQ("Initial model had 0 spaces.",result.initialCondition()->logMessage());
  ASSERT_TRUE(result.finalCondition());
  EXPECT_TRUE(result.finalCondition()->logLevel() == Info);
  EXPECT_EQ("openstudio.ruleset." + script.name(),result.finalCondition()->logChannel());
  EXPECT_EQ("Removed the 0 original spaces, and added one new one named 'Space 1'.",result.finalCondition()->logMessage());

  // test with populated model
  openstudio::model::Model model2;
  openstudio::model::Space space1(model2);
  openstudio::model::Space space2(model2);
  EXPECT_EQ(2u, model2.getModelObjects<openstudio::model::Space>().size());
  EXPECT_EQ(0u, script.arguments(model2).size());
  script.run(model2, runner, user_arguments);
  EXPECT_EQ(1u, model2.getModelObjects<openstudio::model::Space>().size());
  result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  ASSERT_TRUE(result.initialCondition());
  EXPECT_TRUE(result.initialCondition()->logLevel() == Info);
  EXPECT_EQ("openstudio.ruleset." + script.name(),result.initialCondition()->logChannel());
  EXPECT_EQ("Initial model had 2 spaces.",result.initialCondition()->logMessage());
  ASSERT_TRUE(result.finalCondition());
  EXPECT_TRUE(result.finalCondition()->logLevel() == Info);
  EXPECT_EQ("openstudio.ruleset." + script.name(),result.finalCondition()->logChannel());
  EXPECT_EQ("Removed the 2 original spaces, and added one new one named 'Space 1'.",result.finalCondition()->logMessage());
}
TEST_F(RulesetFixture, UserScript_TestModelUserScript2) {
  TestModelUserScript2 script;
  EXPECT_EQ("TestModelUserScript2", script.name());

  Model model;

  // serialize ossrs
  openstudio::path fileDir = toPath("./OSResultOSSRs");
  boost::filesystem::create_directory(fileDir);

  // call with no arguments
  TestOSRunner runner;
  std::map<std::string, OSArgument> user_arguments;
  bool ok = script.run(model,runner,user_arguments);
  EXPECT_FALSE(ok);
  OSResult result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Fail);
  EXPECT_EQ(2u,result.errors().size()); // missing required and defaulted arguments
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());
  EXPECT_TRUE(result.attributes().empty());
  result.save(fileDir / toPath("TestModelUserScript2_1.ossr"),true);

  // call with required argument, but no lights definitions in model
  LightsDefinition lightsDef(model);
  OSArgumentVector definitions = script.arguments(model);
  user_arguments = runner.getUserInput(definitions);
  OSArgument arg = definitions[0];
  arg.setValue(toString(lightsDef.handle()));
  user_arguments["lights_definition"] = arg;
  lightsDef.remove();
  EXPECT_EQ(0u,model.numObjects());
  ok = script.run(model,runner,user_arguments);
  EXPECT_FALSE(ok);
  result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Fail);
  EXPECT_EQ(1u,result.errors().size()); // object not in model
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());
  EXPECT_EQ(2u,result.attributes().size()); // registers argument values
  result.save(fileDir / toPath("TestModelUserScript2_2.ossr"),true);
  // save attributes json for inspection
  saveJSON(result.attributes(),fileDir / toPath("TestModelUserScript2_2.json"),true);

  // call properly using default multiplier, but lights definition not Watts/Area
  lightsDef = LightsDefinition(model);
  lightsDef.setLightingLevel(700.0);
  definitions = script.arguments(model);
  user_arguments = runner.getUserInput(definitions);
  arg = definitions[0];
  arg.setValue(toString(lightsDef.handle()));
  user_arguments["lights_definition"] = arg;
  ok = script.run(model,runner,user_arguments);
  EXPECT_TRUE(ok);
  result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::NA);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(1u,result.info().size()); // Measure not applicable as called
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());
  EXPECT_EQ(3u,result.attributes().size()); // Registers lights definition name, then fails
  result.save(fileDir / toPath("TestModelUserScript2_3.ossr"),true);
  // save attributes json for inspection
  saveJSON(result.attributes(),fileDir / toPath("TestModelUserScript2_3.json"),true);

  // call properly using default multiplier
  lightsDef.setWattsperSpaceFloorArea(10.0);
  ok = script.run(model,runner,user_arguments);
  EXPECT_TRUE(ok);
  result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_TRUE(result.initialCondition()); // describes original state
  EXPECT_TRUE(result.finalCondition());   // describes changes
  EXPECT_EQ(8u,result.attributes().size());
  result.save(fileDir / toPath("TestModelUserScript2_4.ossr"),true);
  EXPECT_DOUBLE_EQ(8.0,lightsDef.wattsperSpaceFloorArea().get());
  // save attributes json for inspection
  saveJSON(result.attributes(),fileDir / toPath("TestModelUserScript2_4.json"),true);

  // call properly using different multiplier
  arg = definitions[1];
  arg.setValue(0.5);
  user_arguments["multiplier"] = arg;
  ok = script.run(model,runner,user_arguments);
  EXPECT_TRUE(ok);
  result = runner.result();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_TRUE(result.initialCondition()); // describes original state
  EXPECT_TRUE(result.finalCondition());   // describes changes
  EXPECT_EQ(8u,result.attributes().size());
  result.save(fileDir / toPath("TestModelUserScript2_5.ossr"),true);
  EXPECT_DOUBLE_EQ(4.0,lightsDef.wattsperSpaceFloorArea().get());
  // save attributes json for inspection
  saveJSON(result.attributes(),fileDir / toPath("TestModelUserScript2_5.json"),true);

  // check that can load ossrs
  OptionalOSResult temp = OSResult::load(fileDir / toPath("TestModelUserScript2_1.ossr"));
  ASSERT_TRUE(temp);
  result = temp.get();
  EXPECT_TRUE(result.value() == OSResultValue::Fail);
  EXPECT_EQ(2u,result.errors().size()); // missing required argument
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());

  temp = OSResult::load(fileDir / toPath("TestModelUserScript2_2.ossr"));
  ASSERT_TRUE(temp);
  result = temp.get();
  EXPECT_TRUE(result.value() == OSResultValue::Fail);
  EXPECT_EQ(1u,result.errors().size()); // object not in model
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());

  temp = OSResult::load(fileDir / toPath("TestModelUserScript2_3.ossr"));
  ASSERT_TRUE(temp);
  result = temp.get();
  EXPECT_TRUE(result.value() == OSResultValue::NA);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(1u,result.info().size()); // Measure not applicable as called
  EXPECT_FALSE(result.initialCondition());
  EXPECT_FALSE(result.finalCondition());

  temp = OSResult::load(fileDir / toPath("TestModelUserScript2_4.ossr"));
  ASSERT_TRUE(temp);
  result = temp.get();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_TRUE(result.initialCondition()); // describes original state
  EXPECT_TRUE(result.finalCondition());   // describes changes

  temp = OSResult::load(fileDir / toPath("TestModelUserScript2_5.ossr"));
  ASSERT_TRUE(temp);
  result = temp.get();
  EXPECT_TRUE(result.value() == OSResultValue::Success);
  EXPECT_EQ(0u,result.errors().size());
  EXPECT_EQ(0u,result.warnings().size());
  EXPECT_EQ(0u,result.info().size());
  EXPECT_TRUE(result.initialCondition()); // describes original state
  EXPECT_TRUE(result.finalCondition());   // describes changes

  // check that can load attribute jsons
  std::vector<Attribute> loadedAttributes;
  NameFinder<Attribute> lightsDefinitionFinder("lights_definition",true);
  NameFinder<Attribute> multiplierFinder("multiplier",true);
  NameFinder<Attribute> lightsDefinitionNameFinder("lights_definition_name",true);
  NameFinder<Attribute> lpdInFinder("lpd_in",true);
  NameFinder<Attribute> lpdOutFinder("lpd_out",true);
  NameFinder<Attribute> lightsDefinitionNumInstancesFinder("lights_definition_num_instances",true);
  NameFinder<Attribute> lightsDefinitionFloorAreaFinder("lights_definition_floor_area",true);
  NameFinder<Attribute> lightsDefinitionFloorAreaIPFinder("lights_definition_floor_area_ip",true);
  AttributeVector::const_iterator it;

  // lights definition not in model - load attributes
  loadedAttributes = toVectorOfAttribute(fileDir / toPath("TestModelUserScript2_2.json"));
  EXPECT_EQ(2u,loadedAttributes.size());
  // lights_definition
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // multiplier
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),multiplierFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(0.8,it->valueAsDouble());
  EXPECT_FALSE(it->units());

  // run with bad lights definition type - load attributes
  loadedAttributes = toVectorOfAttribute(fileDir / toPath("TestModelUserScript2_3.json"));
  EXPECT_EQ(3u,loadedAttributes.size());
  // lights_definition
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // multiplier
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),multiplierFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(0.8,it->valueAsDouble());
  EXPECT_FALSE(it->units());
  // lights_definition_name
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionNameFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());

  // good run, default multiplier
  loadedAttributes = toVectorOfAttribute(fileDir / toPath("TestModelUserScript2_4.json"));
  EXPECT_EQ(8u,loadedAttributes.size());
  // lights_definition
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // multiplier
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),multiplierFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(0.8,it->valueAsDouble());
  EXPECT_FALSE(it->units());
  // lights_definition_name
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionNameFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // lpd_in
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lpdInFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(10.0,it->valueAsDouble());
  ASSERT_TRUE(it->units());
  EXPECT_EQ("W/m^2",it->units().get());
  // -- unit conversion example --
  OptionalDouble ipValue = convert(it->valueAsDouble(),it->units().get(),"W/ft^2");
  ASSERT_TRUE(ipValue);
  EXPECT_DOUBLE_EQ(0.9290304,*ipValue);
  // lpd_out
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lpdOutFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(8.0,it->valueAsDouble());
  ASSERT_TRUE(it->units());
  EXPECT_EQ("W/m^2",it->units().get());
  // lights_definition_num_instances
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionNumInstancesFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  //EXPECT_TRUE(it->valueType() == AttributeValueType::Integer); // JSON does not distinguish between int and float
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  // lights_definition_floor_area
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFloorAreaFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  ASSERT_TRUE(it->units());
  EXPECT_EQ("m^2",it->units().get());
  // lights_definition_floor_area_ip
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFloorAreaIPFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  ASSERT_TRUE(it->units());
  EXPECT_EQ("ft^2",it->units().get());

  // good run, different multiplier
  loadedAttributes = toVectorOfAttribute(fileDir / toPath("TestModelUserScript2_5.json"));
  EXPECT_EQ(8u,loadedAttributes.size());
  // lights_definition
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // multiplier
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),multiplierFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(0.5,it->valueAsDouble());
  EXPECT_FALSE(it->units());
  // lights_definition_name
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionNameFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::String);
  EXPECT_FALSE(it->valueAsString().empty());
  // lpd_in
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lpdInFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(8.0,it->valueAsDouble()); // uses previous example _out as _in
  ASSERT_TRUE(it->units());
  EXPECT_EQ("W/m^2",it->units().get());
  // -- unit conversion example --
  ipValue = convert(it->valueAsDouble(),it->units().get(),"W/ft^2");
  ASSERT_TRUE(ipValue);
  EXPECT_DOUBLE_EQ(0.74322432,*ipValue);
  // lpd_out
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lpdOutFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  EXPECT_DOUBLE_EQ(4.0,it->valueAsDouble());
  ASSERT_TRUE(it->units());
  EXPECT_EQ("W/m^2",it->units().get());
  // lights_definition_num_instances
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionNumInstancesFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  //EXPECT_TRUE(it->valueType() == AttributeValueType::Integer); // JSON does not distinguish between int and float
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  // lights_definition_floor_area
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFloorAreaFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  ASSERT_TRUE(it->units());
  EXPECT_EQ("m^2",it->units().get());
  // lights_definition_floor_area_ip
  it = std::find_if(loadedAttributes.begin(),loadedAttributes.end(),lightsDefinitionFloorAreaIPFinder);
  ASSERT_FALSE(it == loadedAttributes.end());
  EXPECT_TRUE(it->valueType() == AttributeValueType::Double);
  ASSERT_TRUE(it->units());
  EXPECT_EQ("ft^2",it->units().get());
}
Beispiel #6
0
int main( ){
	WindowsErrorPopupBlocker();
// test OS code samples here
	FileUtil *fileUtil = NULL; 
	fileUtil = new FileUtil();
	const char dirsep =  CoinFindDirSeparator();
 	// Set directory containing mps data files.
 	std::string dataDir;
   dataDir = dirsep == '/' ? "../data/" : "..\\data\\";
	cout << "Start Building the Model" << endl;
	try{
		// get the p0033 problem
		std::string osilFileName;
		osilFileName =  dataDir  +   "p0033.osil";
		std::cout << "Try to read a sample file" << std::endl;
		std::cout << "The file is: " ;
		std::cout <<  osilFileName << std::endl;
		std::string osil = fileUtil->getFileAsString( osilFileName.c_str() );
		OSiLReader *osilreader = NULL;
		osilreader = new OSiLReader(); 
		OSInstance *osinstance;
		osinstance = osilreader->readOSiL( osil);
		// done writing the model
		cout << "Done writing the Model" << endl;
		// now solve the model
		CoinSolver *solver  = NULL;
		solver = new CoinSolver();  
		solver->sSolverName ="cbc"; 
		solver->osinstance = osinstance;
		solver->buildSolverInstance();
		solver->osiSolver->setHintParam(OsiDoReducePrint, true, OsiHintTry);
		solver->osiSolver->initialSolve();
		cout << "Here is the initial objective value "  << solver->osiSolver->getObjValue()  << endl;
		
		CglKnapsackCover cover;
	    CglSimpleRounding round;  
		CglGomory gomory;
		CbcModel *model = new CbcModel( *solver->osiSolver);

		//model->setBestObjectiveValue(4000);
		model->setMaximumNodes(100000);
		//
		model->addCutGenerator(&gomory, 1, "Gomory");
		model->addCutGenerator(&cover, 1, "Cover");
		model->addCutGenerator(&round, 1, "Round");
		model->branchAndBound();	
		// now create a result object
		OSResult *osresult = new OSResult();
		// if we are throw an exception if the problem is nonlinear
		double *x = NULL;
		double *y = NULL;
		double *z = NULL;
		//int i = 0;
		std::string *rcost = NULL;
		// resultHeader infomration
		if(osresult->setServiceName("Solved with Coin Solver: " + solver->sSolverName) != true)
			throw ErrorClass("OSResult error: setServiceName");
		if(osresult->setInstanceName(  solver->osinstance->getInstanceName()) != true)
			throw ErrorClass("OSResult error: setInstanceName");
		if(osresult->setVariableNumber( solver->osinstance->getVariableNumber()) != true)
			throw ErrorClass("OSResult error: setVariableNumer");
		if(osresult->setObjectiveNumber( 1) != true)
			throw ErrorClass("OSResult error: setObjectiveNumber");
		if(osresult->setConstraintNumber( solver->osinstance->getConstraintNumber()) != true)
			throw ErrorClass("OSResult error: setConstraintNumber");
		if(osresult->setSolutionNumber(  1) != true)
			throw ErrorClass("OSResult error: setSolutionNumer");	
		int solIdx = 0;
		std::string description = "";
		osresult->setGeneralStatusType("success");
		std::cout << "PROVEN OPTIMAL " << model->isProvenOptimal() << std::endl;
		int i;
		if (model->isProvenOptimal() == 1){
			osresult->setSolutionStatus(solIdx, "optimal", description);
			/* Retrieve the solution */
			x = new double[solver->osinstance->getVariableNumber() ];
			y = new double[solver->osinstance->getConstraintNumber() ];
			z = new double[1];
			rcost = new std::string[ solver->osinstance->getVariableNumber()];
			//
			*(z + 0)  =  model->getObjValue();
			osresult->setObjectiveValuesDense(solIdx, z);
			for(i=0; i < solver->osinstance->getVariableNumber(); i++){
				*(x + i) = model->getColSolution()[i];
			}
			osresult->setPrimalVariableValuesDense(solIdx, x );
			//if( solver->sSolverName.find( "symphony") == std::string::npos){
			for(i=0; i <  solver->osinstance->getConstraintNumber(); i++){
				*(y + i) = model->getRowPrice()[ i];
			}
			osresult->setDualVariableValuesDense(solIdx, y);
			//
			// now put the reduced costs into the osrl
			int numberOfOtherVariableResult = 1;
			int otherIdx = 0;
			// first set the number of Other Variable Results
			osresult->setNumberOfOtherVariableResults(solIdx, numberOfOtherVariableResult);
			
			std::ostringstream outStr;
			int numberOfVar =  solver->osinstance->getVariableNumber();
			for(i=0; i < numberOfVar; i++){
				outStr << model->getReducedCost()[ i]; 
				rcost[ i] = outStr.str();
				outStr.str("");
			}
			osresult->setAnOtherVariableResultDense(solIdx, otherIdx, "reduced costs", "", "the variable reduced costs",  
				rcost);			
			// end of settiing reduced costs			
		}
		else{ 
			if(solver->osiSolver->isProvenPrimalInfeasible() == true) 
				osresult->setSolutionStatus(solIdx, "infeasible", description);
			else
				if(solver->osiSolver->isProvenDualInfeasible() == true) 
					osresult->setSolutionStatus(solIdx, "dualinfeasible", description);
				else
					osresult->setSolutionStatus(solIdx, "other", description);
		}
		OSrLWriter *osrlwriter = new OSrLWriter();
		std::cout <<  osrlwriter->writeOSrL( osresult) << std::endl;
		if(solver->osinstance->getVariableNumber() > 0){
			delete[] x;
			x = NULL;
		}
		if(solver->osinstance->getConstraintNumber()) delete[] y;
		y = NULL;
		delete[] z;	
		z = NULL;
		if(solver->osinstance->getVariableNumber() > 0){
			delete[] rcost;
			rcost = NULL;
		}
    	// do garbage collection
		delete osresult;
		osresult = NULL;
		delete osrlwriter;
		osrlwriter = NULL;
		delete solver;
		solver = NULL;
		delete osilreader;
		osilreader = NULL;
		delete fileUtil;
		fileUtil  = NULL;
		delete model;
		model = NULL;
		cout << "Done with garbage collection" << endl;
		return 0;
	}
	catch(const ErrorClass& eclass){
		delete fileUtil;
		std::cout << eclass.errormsg <<  std::endl;
		return 0;
	} 
}// end main
bool OSServiceMethods::executeServiceMethod(OSCommandLine *oscommandline)
{
    OSSolverAgent* osagent = NULL;
	/**
	 *  The required file conversions are all assumed 
	 *  to have been taken care of in the nonstandard constructor,
	 *  so this wrapper merely directs traffic
	 */
    try
    {
    	
    	
		/** the only local service method is solve() */
		if	(oscommandline->serviceLocation == "")
			if (oscommandline->serviceMethod == "solve")
				//resultString = runSolver(oscommandline->solverName, oscommandline->osoption, oscommandline->osinstance);
				int junk;
			else
				throw ErrorClass("No service location (URL) specified. Only \"solve\" is available locally");

		/** Here we have a remote call --- reuse as much code as possible */
		else
		{
            osagent = new OSSolverAgent(oscommandline->serviceLocation);
//solve
			if (oscommandline->serviceMethod == "solve")
	            resultString = osagent->solve(oscommandline->osil, oscommandline->osol);
//send --- first check that there is a jobID. If not, get one
			else if (oscommandline->serviceMethod == "send")
			{
                if (oscommandline->osol.find( "<jobID") == std::string::npos)
				{
	                OSoLReader *osolreader = NULL;
		            osolreader = new OSoLReader();
	                OSoLWriter *osolwriter = NULL;
		            osolwriter = new OSoLWriter();
					try
					{

						if (oscommandline->osol != "")
							oscommandline->osoption = osolreader->readOSoL(oscommandline->osol);
			            oscommandline->osoption->setJobID(osagent->getJobID(""));

						// now write the osOption object into a string
				        oscommandline->osol = osolwriter->writeOSoL(oscommandline->osoption);

		                delete osolreader;
			            osolreader = NULL;
		                delete osolwriter;
			            osolwriter = NULL;
					}
					catch (const ErrorClass& eclass)
					{
						delete osolreader;
			            osolreader = NULL;
		                delete osolwriter;
			            osolwriter = NULL;
						throw ErrorClass(eclass.errormsg);
					}
				}
				bool sendResult;
				sendResult = osagent->send(oscommandline->osil, oscommandline->osol);
				if (sendResult == false)
					throw ErrorClass("send() method failed");
            }
//retrieve
			else if (oscommandline->serviceMethod == "retrieve")
			{
	            if (oscommandline->osol.find( "<jobID") == std::string::npos)
		            throw ErrorClass("there is no JobID to retrieve");
			    resultString = osagent->retrieve(oscommandline->osol);
			}
//getJobID
			else if (oscommandline->serviceMethod == "getJobID")
	            resultString = osagent->getJobID(oscommandline->osol);
//knock
			else if (oscommandline->serviceMethod == "knock")
	            resultString = osagent->knock(oscommandline->osplInput, oscommandline->osol);
//kill
			else if (oscommandline->serviceMethod == "kill")
			{
	            if (oscommandline->osol.find( "<jobID") == std::string::npos)
		            throw ErrorClass("there is no JobID to kill");
			    resultString = osagent->kill(oscommandline->osol);
			}
			else
		            throw ErrorClass("serviceMethod not recognized");

			delete osagent;
            osagent = NULL;
		}
		return true;
    }
    catch (const ErrorClass& eclass)
    {
        OSResult *osresult = NULL;
        OSrLWriter *osrlwriter = NULL;
        osrlwriter = new OSrLWriter();
        osresult = new OSResult();
        osresult->setGeneralMessage(eclass.errormsg);
        osresult->setGeneralStatusType("error");
        resultString = osrlwriter->writeOSrL(osresult);
        //catch garbage collection
        delete osresult;
        osresult = NULL;
        delete osrlwriter;
        osrlwriter = NULL;

		if (osagent != NULL) delete osagent;
            osagent = NULL;
        return false;
    }
    
 
}//executeServiceMethod