Exemple #1
1
void MainFrame::OnAddElementsClick(wxCommandEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());

    if(workspace) {
        if(workspace->GetWorkspaceMode() != Workspace::MODE_INSERT) {
            auto elementList = workspace->GetElementList();
            wxString statusBarText = "";
            bool newElement = false;

            switch(event.GetId()) {
                case ID_ADDMENU_BUS: {
                    Bus* newBus = new Bus(wxPoint2DDouble(0, 0),
                                          wxString::Format(_("Bus %d"), workspace->GetElementNumber(ID_BUS)));
                    workspace->IncrementElementNumber(ID_BUS);
                    elementList.push_back(newBus);
                    statusBarText = _("Insert Bus: Click to insert, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_LINE: {
                    Line* newLine = new Line(wxString::Format(_("Line %d"), workspace->GetElementNumber(ID_LINE)));
                    elementList.push_back(newLine);
                    workspace->IncrementElementNumber(ID_LINE);
                    statusBarText = _("Insert Line: Click on two buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_TRANSFORMER: {
                    Transformer* newTransformer = new Transformer(
                        wxString::Format(_("Transformer %d"), workspace->GetElementNumber(ID_TRANSFORMER)));
                    workspace->IncrementElementNumber(ID_TRANSFORMER);
                    elementList.push_back(newTransformer);
                    statusBarText = _("Insert Transformer: Click on two buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_GENERATOR: {
                    SyncGenerator* newGenerator = new SyncGenerator(
                        wxString::Format(_("Generator %d"), workspace->GetElementNumber(ID_SYNCGENERATOR)));
                    workspace->IncrementElementNumber(ID_SYNCGENERATOR);
                    elementList.push_back(newGenerator);
                    statusBarText = _("Insert Generator: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_LOAD: {
                    Load* newLoad = new Load(wxString::Format(_("Load %d"), workspace->GetElementNumber(ID_LOAD)));
                    workspace->IncrementElementNumber(ID_LOAD);
                    elementList.push_back(newLoad);
                    statusBarText = _("Insert Load: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_CAPACITOR: {
                    Capacitor* newCapacitor =
                        new Capacitor(wxString::Format(_("Capacitor %d"), workspace->GetElementNumber(ID_CAPACITOR)));
                    workspace->IncrementElementNumber(ID_CAPACITOR);
                    elementList.push_back(newCapacitor);
                    statusBarText = _("Insert Capacitor: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_INDUCTOR: {
                    Inductor* newInductor =
                        new Inductor(wxString::Format(_("Inductor %d"), workspace->GetElementNumber(ID_INDUCTOR)));
                    workspace->IncrementElementNumber(ID_INDUCTOR);
                    elementList.push_back(newInductor);
                    statusBarText = _("Insert Inductor: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_INDMOTOR: {
                    IndMotor* newIndMotor = new IndMotor(
                        wxString::Format(_("Induction motor %d"), workspace->GetElementNumber(ID_INDMOTOR)));
                    workspace->IncrementElementNumber(ID_INDMOTOR);
                    elementList.push_back(newIndMotor);
                    statusBarText = _("Insert Induction Motor: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
                case ID_ADDMENU_SYNCCOMP: {
                    SyncMotor* newSyncCondenser = new SyncMotor(
                        wxString::Format(_("Synchronous condenser %d"), workspace->GetElementNumber(ID_SYNCMOTOR)));
                    workspace->IncrementElementNumber(ID_SYNCMOTOR);
                    elementList.push_back(newSyncCondenser);
                    statusBarText = _("Insert Synchronous Condenser: Click on a buses, ESC to cancel.");
                    newElement = true;
                } break;
            }
            if(newElement) {
                workspace->SetElementList(elementList);
                workspace->SetWorkspaceMode(Workspace::MODE_INSERT);
                workspace->SetStatusBarText(statusBarText);
                workspace->Redraw();
            }
        }
    }
}
TEST_F(EnergyPlusFixture,ForwardTranslatorTest_TranslateSiteGroundReflectance) {
  openstudio::model::Model model;
  openstudio::model::SiteGroundReflectance groundreflect = model.getUniqueModelObject<openstudio::model::SiteGroundReflectance>();

  groundreflect.setJanuaryGroundReflectance(0.11);
  groundreflect.setFebruaryGroundReflectance(0.12);
  groundreflect.setMarchGroundReflectance(0.13);
  groundreflect.setAprilGroundReflectance(0.14);
  groundreflect.setMayGroundReflectance(0.15);
  groundreflect.setJuneGroundReflectance(0.16);
  groundreflect.setJulyGroundReflectance(0.17);
  groundreflect.setAugustGroundReflectance(0.18);
  groundreflect.setSeptemberGroundReflectance(0.19);
  groundreflect.setOctoberGroundReflectance(0.20);
  groundreflect.setNovemberGroundReflectance(0.21);
  groundreflect.setDecemberGroundReflectance(0.22);

  ForwardTranslator trans;
  Workspace workspace = trans.translateModelObject(groundreflect);
  ASSERT_EQ(1u, workspace.numObjectsOfType(IddObjectType::Site_GroundReflectance));
    
  IdfObject groundreflectIdf = workspace.getObjectsByType(IddObjectType::Site_GroundReflectance)[0];
  EXPECT_EQ(unsigned(12), groundreflectIdf.numFields());

  EXPECT_EQ( 0.11, *(groundreflectIdf.getDouble(0)) );
  EXPECT_EQ( 0.12, *(groundreflectIdf.getDouble(1)) );
  EXPECT_EQ( 0.13, *(groundreflectIdf.getDouble(2)) );
  EXPECT_EQ( 0.14, *(groundreflectIdf.getDouble(3)) );
  EXPECT_EQ( 0.15, *(groundreflectIdf.getDouble(4)) );
  EXPECT_EQ( 0.16, *(groundreflectIdf.getDouble(5)) );
  EXPECT_EQ( 0.17, *(groundreflectIdf.getDouble(6)) );
  EXPECT_EQ( 0.18, *(groundreflectIdf.getDouble(7)) );
  EXPECT_EQ( 0.19, *(groundreflectIdf.getDouble(8)) );
  EXPECT_EQ( 0.20, *(groundreflectIdf.getDouble(9)) );
  EXPECT_EQ( 0.21, *(groundreflectIdf.getDouble(10)) );
  EXPECT_EQ( 0.22, *(groundreflectIdf.getDouble(11)) );
}
TEST_F(EnergyPlusFixture,ForwardTranslatorTest_TranslateSiteGroundTemperatureBuildingSurface) {
  openstudio::model::Model model;
  openstudio::model::SiteGroundTemperatureBuildingSurface groundtemp = model.getUniqueModelObject<openstudio::model::SiteGroundTemperatureBuildingSurface>();

  groundtemp.setJanuaryGroundTemperature(19.527);
  groundtemp.setFebruaryGroundTemperature(19.502);
  groundtemp.setMarchGroundTemperature(19.536);
  groundtemp.setAprilGroundTemperature(19.598);
  groundtemp.setMayGroundTemperature(20.002);
  groundtemp.setJuneGroundTemperature(21.64);
  groundtemp.setJulyGroundTemperature(22.225);
  groundtemp.setAugustGroundTemperature(22.375);
  groundtemp.setSeptemberGroundTemperature(21.449);
  groundtemp.setOctoberGroundTemperature(20.121);
  groundtemp.setNovemberGroundTemperature(19.802);
  groundtemp.setDecemberGroundTemperature(19.633);

  ForwardTranslator trans;
  Workspace workspace = trans.translateModelObject(groundtemp);
  ASSERT_EQ(1u, workspace.numObjectsOfType(IddObjectType::Site_GroundTemperature_BuildingSurface));
    
  IdfObject groundtempIdf = workspace.getObjectsByType(IddObjectType::Site_GroundTemperature_BuildingSurface)[0];
  EXPECT_EQ(unsigned(12), groundtempIdf.numFields());

  EXPECT_EQ( 19.527, *(groundtempIdf.getDouble(0)) );
  EXPECT_EQ( 19.502, *(groundtempIdf.getDouble(1)) );
  EXPECT_EQ( 19.536, *(groundtempIdf.getDouble(2)) );
  EXPECT_EQ( 19.598, *(groundtempIdf.getDouble(3)) );
  EXPECT_EQ( 20.002, *(groundtempIdf.getDouble(4)) );
  EXPECT_EQ( 21.64, *(groundtempIdf.getDouble(5)) );
  EXPECT_EQ( 22.225, *(groundtempIdf.getDouble(6)) );
  EXPECT_EQ( 22.375, *(groundtempIdf.getDouble(7)) );
  EXPECT_EQ( 21.449, *(groundtempIdf.getDouble(8)) );
  EXPECT_EQ( 20.121, *(groundtempIdf.getDouble(9)) );
  EXPECT_EQ( 19.802, *(groundtempIdf.getDouble(10)) );
  EXPECT_EQ( 19.633, *(groundtempIdf.getDouble(11)) );
}
TEST_F(EnergyPlusFixture, ForwardTranslator_AvailabilityManagerLowTemperatureTurnOff) {

  Model m;

  AvailabilityManagerLowTemperatureTurnOff avm(m);

  // Assign Sensor Node and Temperature
  Node n(m);
  EXPECT_TRUE(avm.setSensorNode(n));
  EXPECT_TRUE(avm.setTemperature(60.19));
  // Test Applicability Schedule
  ScheduleConstant sch(m);
  sch.setValue(50);
  EXPECT_TRUE(avm.setApplicabilitySchedule(sch));

  // Assign it to a plant loop
  PlantLoop p(m);
  p.setAvailabilityManager(avm);

  // ForwardTranslate
  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(m);

  WorkspaceObjectVector idfObjs(workspace.getObjectsByType(IddObjectType::AvailabilityManager_LowTemperatureTurnOff));
  EXPECT_EQ(1u, idfObjs.size());
  WorkspaceObject idf_avm(idfObjs[0]);

  // Sensor Node Name
  ASSERT_EQ(n.name().get(), idf_avm.getString(AvailabilityManager_LowTemperatureTurnOffFields::SensorNodeName).get());

  // Temperature
  EXPECT_DOUBLE_EQ(avm.temperature(), idf_avm.getDouble(AvailabilityManager_LowTemperatureTurnOffFields::Temperature).get());

  // Applicability Schedule Name
  ASSERT_EQ(sch.name().get(), idf_avm.getString(AvailabilityManager_LowTemperatureTurnOffFields::ApplicabilityScheduleName).get());

}
TEST_F(EnergyPlusFixture, ForwardTranslator_ExternalInterfaceFunctionalMockupUnitExportToActuator) {
  Model model;

  Building building = model.getUniqueModelObject<Building>();

  // add fan
  Schedule s = model.alwaysOnDiscreteSchedule();
  FanConstantVolume fan(model, s);

  // add actuator
  std::string fanControlType = "Fan Pressure Rise";
  std::string ComponentType = "Fan";
  ExternalInterfaceFunctionalMockupUnitExportToActuator fanActuator(fan, ComponentType, fanControlType, "Fan FMU name", 10);

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);
  EXPECT_EQ(0u, forwardTranslator.errors().size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Actuator).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::ExternalInterface_FunctionalMockupUnitExport_To_Actuator)[0];

  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::Name, false));
  EXPECT_EQ("External Interface Functional Mockup Unit Export To Actuator 1", object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::Name, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentUniqueName, false));
  EXPECT_EQ(fan.nameString(), object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentUniqueName, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentType, false));
  EXPECT_EQ(ComponentType, object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentControlType, false));
  EXPECT_EQ(fanControlType, object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::ActuatedComponentControlType, false).get());
  ASSERT_TRUE(object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::FMUVariableName, false));
  EXPECT_EQ("Fan FMU name", object.getString(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::FMUVariableName, false).get());
  ASSERT_TRUE(object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::InitialValue, false));
  EXPECT_EQ(10.0, object.getDouble(ExternalInterface_FunctionalMockupUnitExport_To_ActuatorFields::InitialValue, false).get());

  model.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToActuator.osm"), true);
  workspace.save(toPath("./ExternalInterfaceFunctionalMockupUnitExportToActuator.idf"), true);
}
TEST_F(EnergyPlusFixture,ForwardTranslator_Building)
{
  Model model;
  Building building = model.getUniqueModelObject<Building>();
  building.setName("Building");
  EXPECT_TRUE(building.isNorthAxisDefaulted());

  ForwardTranslator forwardTranslator;
  Workspace workspace = forwardTranslator.translateModel(model);

  ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::Building).size());
  ASSERT_EQ(0u, workspace.getObjectsByType(IddObjectType::Site_Location).size());
  ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::SimulationControl).size());

  WorkspaceObject object = workspace.getObjectsByType(IddObjectType::Building)[0];
  ASSERT_TRUE(object.getString(BuildingFields::Name));
  EXPECT_EQ("Building", object.getString(BuildingFields::Name).get());
  EXPECT_TRUE(object.isEmpty(BuildingFields::NorthAxis));
  EXPECT_TRUE(object.isEmpty(BuildingFields::Terrain));
  EXPECT_TRUE(object.isEmpty(BuildingFields::LoadsConvergenceToleranceValue));
  EXPECT_TRUE(object.isEmpty(BuildingFields::TemperatureConvergenceToleranceValue));
  EXPECT_TRUE(object.isEmpty(BuildingFields::SolarDistribution));
  EXPECT_TRUE(object.isEmpty(BuildingFields::MaximumNumberofWarmupDays));
}
Exemple #7
0
void MainFrame::OnMoveClick(wxRibbonButtonBarEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());
    if(workspace) {
        auto elementList = workspace->GetAllElements();
        // Calculate the average position of selected elements.
        wxPoint2DDouble averagePos(0, 0);
        int numSelElements = 0;
        for(auto it = elementList.begin(), itEnd = elementList.end(); it != itEnd; ++it) {
            Element* element = *it;
            if(element->IsSelected()) {
                averagePos += element->GetPosition();
                numSelElements++;
            }
        }
        averagePos = wxPoint2DDouble(averagePos.m_x / double(numSelElements), averagePos.m_y / double(numSelElements));
        // Set the move position to the average of selected elements.
        for(auto it = elementList.begin(), itEnd = elementList.end(); it != itEnd; ++it) {
            Element* element = *it;
            if(element->IsSelected()) { element->StartMove(averagePos); }
        }
        workspace->SetWorkspaceMode(Workspace::MODE_MOVE_ELEMENT);
    }
}
Exemple #8
0
 void KeyFinder::chromagramOfBufferedAudio(
   Workspace& workspace,
   const Parameters& params
 ) {
   if (workspace.getFftAdapter() == NULL)
     workspace.setFftAdapter(new FftAdapter(params.getFftFrameSize()));
   SpectrumAnalyser sa(workspace.buffer.getFrameRate(), params, ctFactory);
   Chromagram* c = sa.chromagramOfWholeFrames(workspace.buffer, workspace.getFftAdapter());
   // deal with tuning if necessary
   if (c->getBandsPerSemitone() > 1) {
     if (params.getTuningMethod() == TUNING_BAND_ADAPTIVE) {
       c->tuningBandAdaptive(params.getDetunedBandWeight());
     } else if (params.getTuningMethod() == TUNING_HARTE) {
       c->tuningHarte();
     }
   }
   workspace.buffer.discardFramesFromFront(params.getHopSize() * c->getHops());
   if (workspace.chroma == NULL) {
     workspace.chroma = c;
   } else {
     workspace.chroma->append(*c);
     delete c;
   }
 }
Exemple #9
0
void cleanAll() {
	utils::rm("./build", true, true);
	utils::mkdir("./build");
	utils::rm(".busy", true, true);
	std::cout << "clean all done" << std::endl;

	// ignore exceptions
	try {
		Workspace ws;
		auto validPackages = ws.getPackages();
		auto allDepPackages = validPackages.begin()->getAllDependendPackages();
		std::vector<Package const*> noDepPackage;
		for (auto const& p : validPackages) {
			auto iter = std::find_if(allDepPackages.begin(), allDepPackages.end(), [&](Package const* p2) {
				return p.getName() == p2->getName();
			});
			if (iter == allDepPackages.end()) {
				noDepPackage.push_back(&p);
			}
		}

		if (noDepPackage.size() > 0) {
			std::cout << "\n" << TERM_RED << "Packages is not used or referenced:\n" << TERM_RESET;
			std::string paths;
			for (auto p : noDepPackage) {
				std::cout << " - " << p->getName() << "\n";
				paths += " " + p->getPath();
			}
			std::cout << "you might want to run\n";
			std::cout << TERM_GREEN"  rm -rf " << paths << TERM_RESET"\n";
		}

	} catch (...) {}


}
TEST_F(IdfFixture,ValidityReport_WithCustomIdd) 
{
  Workspace workspace;
  EXPECT_EQ(IddFileType::OpenStudio, workspace.iddFileType().value());
  EXPECT_TRUE(workspace.isValid(StrictnessLevel::Draft));
  workspace.addObject(IdfObject(IddObjectType::OS_Building));
  EXPECT_TRUE(workspace.isValid(StrictnessLevel::Draft));

  std::stringstream ss;
  workspace.iddFile().print(ss);
  boost::optional<IddFile> iddFile = IddFile::load(ss);
  ASSERT_TRUE(iddFile);

  Workspace workspace2(*iddFile, StrictnessLevel::None);
  EXPECT_EQ(IddFileType::UserCustom, workspace2.iddFileType().value());
  workspace2.addObjects(workspace.toIdfFile().objects());
  EXPECT_EQ(workspace.objects().size(), workspace2.objects().size());
  EXPECT_TRUE(workspace2.isValid(StrictnessLevel::Draft));
  ValidityReport report = workspace2.validityReport(StrictnessLevel::Draft);
  LOG(Debug,"Validity report for workspace2: " << std::endl << report);
}
Exemple #11
0
const Workspace& Ide::IdeWorkspace() const
{
	static Workspace wspc;
	static String _main;
	if(main != _main || wspc.GetCount() == 0) {
		wspc.Scan(main);
		_main = main;
	}
	else {
		for(int i = 0; i < wspc.GetCount(); i++)
			if(wspc.GetPackage(i).time != FileGetTime(PackagePath(wspc[i]))) {
				wspc.Scan(main);
				break;
			}
	}
	return wspc;
}
/**
 * Tests only the controlType of the ForwardTranslator which I exposed after the fact
 **/
TEST_F(EnergyPlusFixture,ForwardTranslator_AirLoopHVACUnitarySystem_ControlType)
{
  Model m;

  AirLoopHVAC airLoop(m);
  AirLoopHVACUnitarySystem unitary(m);

  Node supplyOutletNode = airLoop.supplyOutletNode();
  unitary.addToNode(supplyOutletNode);

  // test if Setpoint
  unitary.setControlType("Setpoint");

  ForwardTranslator ft;
  Workspace workspace = ft.translateModel(m);

  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::AirLoopHVAC_UnitarySystem).size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::AirLoopHVAC).size());

  IdfObject idf_unitary = workspace.getObjectsByType(IddObjectType::AirLoopHVAC_UnitarySystem)[0];

  ASSERT_EQ("Setpoint",
            idf_unitary.getString(AirLoopHVAC_UnitarySystemFields::ControlType).get() );

  // test if load (make sure nothing is hardcoded)
  unitary.setControlType("Load");

  workspace = ft.translateModel(m);

  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::AirLoopHVAC_UnitarySystem).size());
  EXPECT_EQ(1u, workspace.getObjectsByType(IddObjectType::AirLoopHVAC).size());

  idf_unitary = workspace.getObjectsByType(IddObjectType::AirLoopHVAC_UnitarySystem)[0];

  ASSERT_EQ("Load",
            idf_unitary.getString(AirLoopHVAC_UnitarySystemFields::ControlType).get() );


}
OSArgument makeChoiceArgumentOfWorkspaceObjects(const std::string& name,
                                                const IddObjectType& iddObjectType,
                                                const Workspace& workspace,
                                                bool required)
{
  std::vector< std::pair<std::string, std::string> > intermediate;

  std::vector<WorkspaceObject> objects = workspace.getObjectsByType(iddObjectType);
  for (const WorkspaceObject& object : objects){
    std::string objectName;
    if (object.name()) {
      objectName = object.name().get();
    }
    else {
      objectName = object.iddObject().type().valueName();
    }
    intermediate.push_back(std::pair<std::string,std::string>(toString(object.handle()),
                                                              objectName));
  }

  std::sort(intermediate.begin(),
            intermediate.end(),
            SecondOfPairLess< std::pair<std::string,std::string> >());

  int n = intermediate.size();
  StringVector choices(n), displayNames(n);
  for (int i = 0; i < n; ++i) {
    choices[i] = intermediate[i].first;
    displayNames[i] = intermediate[i].second;
  }

  return OSArgument::makeChoiceArgument(name,
                                        choices,
                                        displayNames,
                                        required);
}
Exemple #14
0
void MainFrame::OnSaveClick(wxRibbonButtonBarEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());
    if(workspace) {
        FileHanding fileHandling(workspace);

        if(workspace->GetSavedPath().IsOk()) {
            fileHandling.SaveProject(workspace->GetSavedPath());
        } else {
            wxFileDialog saveFileDialog(this, _("Save PSP file"), "", "", "PSP files (*.psp)|*.psp",
                                        wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
            if(saveFileDialog.ShowModal() == wxID_CANCEL) return;

            fileHandling.SaveProject(saveFileDialog.GetPath());
            wxFileName fileName(saveFileDialog.GetPath());
            workspace->SetName(fileName.GetName());
            m_auiNotebook->SetPageText(m_auiNotebook->GetPageIndex(workspace), workspace->GetName());
            workspace->SetSavedPath(fileName);
        }
    }
}
Exemple #15
0
void MainFrame::OnImportClick(wxRibbonButtonBarEvent& event)
{
    // Create a new workspace to import
    Workspace* impWorkspace = new Workspace(this, _("Imported project"), this->GetStatusBar(), m_sharedGLContext);
    ImportForm importForm(this, impWorkspace);
    if(importForm.ShowModal() == wxID_OK) {
        // Import file(s)
        EnableCurrentProjectRibbon();

        if(!m_sharedGLContext) m_sharedGLContext = impWorkspace->GetOpenGLContext();
        m_workspaceList.push_back(impWorkspace);

        m_ribbonButtonBarContinuous->ToggleButton(ID_RIBBON_DISABLESOL, true);
        m_ribbonButtonBarContinuous->ToggleButton(ID_RIBBON_ENABLESOL, false);

        m_auiNotebook->AddPage(impWorkspace, impWorkspace->GetName(), true);
        m_auiNotebook->Layout();
        impWorkspace->Redraw();
        impWorkspace->SetJustOpened(true);
        impWorkspace->Fit();
        m_projectNumber++;
    }
}
OptionalModelObject ReverseTranslator::translateEnergyManagementSystemOutputVariable(const WorkspaceObject & workspaceObject)
{
  if (workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_OutputVariable) {
    LOG(Error, "WorkspaceObject is not IddObjectType: EnergyManagementSystem_OutputVariable");
    return boost::none;
  }

  //make sure all other objects are translated first except below
  for (const WorkspaceObject& workspaceObject : m_workspace.objects()) {
    if ((workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_Program)
      && (workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_Subroutine)
      && (workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_ProgramCallingManager)
      && (workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_MeteredOutputVariable)
      && (workspaceObject.iddObject().type() != IddObjectType::EnergyManagementSystem_OutputVariable)) {
      translateAndMapWorkspaceObject(workspaceObject);
    }
  }

  OptionalString s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::Name);
  if (!s) {
    LOG(Error, "EnergyManagementSystem_OutputVariable has no Name");
    return boost::none;
  }
  openstudio::model::EnergyManagementSystemOutputVariable emsOutputVariable(m_model);
  emsOutputVariable.setName(*s);

  s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::EMSVariableName);
  if (!s) {
    LOG(Error, emsOutputVariable.nameString() + ": EMSVariableName not set");
    return boost::none;
  } else {
    Workspace workspace = workspaceObject.workspace();
    //look for GlobalVariables, translate and check if there is a name match since GV's dont have name field.
    boost::optional<WorkspaceObject> wsObject = workspace.getObjectByTypeAndName(IddObjectType::EnergyManagementSystem_GlobalVariable, *s);
    //for (WorkspaceObject& wsObject : workspace.getObjectsByType(IddObjectType::EnergyManagementSystem_GlobalVariable)) {
    if (wsObject) {
      boost::optional<model::ModelObject> modelObject = translateAndMapWorkspaceObject(wsObject.get());
      if (modelObject) {
        if (modelObject.get().cast<EnergyManagementSystemGlobalVariable>().name() == s) {
          emsOutputVariable.setEMSVariableName(*s);
        }
      }
    }
    //look for name match on other (EMS) objects.
    for (WorkspaceObject& wsObject : workspace.getObjectsByName(*s)) {
      boost::optional<model::ModelObject> modelObject = translateAndMapWorkspaceObject(wsObject);
      if (modelObject) {
        emsOutputVariable.setEMSVariableName(*s);
        break;
      }
    }
  }

  s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::UpdateFrequency);
  if (!s) {
    LOG(Error, emsOutputVariable.nameString() + ": UpdateFrequency not set");
    return boost::none;
  } else {
    emsOutputVariable.setUpdateFrequency(*s);
  }

  s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::TypeofDatainVariable);
  if (!s) {
    LOG(Error, emsOutputVariable.nameString() + ": TypeofDatainVariable not set");
    return boost::none;
  } else {
    emsOutputVariable.setTypeOfDataInVariable(*s);
  }

  s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::Units);
  if (s) {
    emsOutputVariable.setUnits(*s);
  }

  s = workspaceObject.getString(EnergyManagementSystem_OutputVariableFields::EMSProgramorSubroutineName);
  if (s) {
    Workspace workspace = workspaceObject.workspace();
    for (WorkspaceObject& wsObject : workspace.getObjectsByName(*s)) {
      boost::optional<model::ModelObject> modelObject = translateAndMapWorkspaceObject(wsObject);
      if (modelObject) {
        if (modelObject.get().iddObjectType() == IddObjectType::OS_EnergyManagementSystem_Program) {
          emsOutputVariable.setEMSProgramOrSubroutineName(modelObject.get().cast<EnergyManagementSystemProgram>());
        } else if (modelObject.get().iddObjectType() == IddObjectType::OS_EnergyManagementSystem_Subroutine) {
          emsOutputVariable.setEMSProgramOrSubroutineName(modelObject.get().cast<EnergyManagementSystemSubroutine>());
        }
        return emsOutputVariable;
      }
    }
  }

  return emsOutputVariable;
}
Exemple #17
0
bool DuplicateViewCommand::onEnabled(Context* context)
{
  Workspace* workspace = App::instance()->workspace();
  WorkspaceView* view = workspace->activeView();
  return (view != nullptr);
}
Exemple #18
0
void MainFrame::OnRotCounterClockClick(wxRibbonButtonBarEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());
    if(workspace) { workspace->RotateSelectedElements(false); }
}
Exemple #19
0
	WebResponse* ListHandler::Execute(WebRequest* pWebRequest, WebContext* pWebContext, User* pUser)
	{
		GLogger* pLogger = augeGetLoggerInstance();
		ListRequest* pRequest = static_cast<ListRequest*>(pWebRequest);

		const char* sourceName = pRequest->GetSourceName();
		const char* path = pRequest->GetPath();

		if(sourceName==NULL)
		{
			const char* msg = "Parameter [sourceName] is NULL";
			GLogger* pLogger = augeGetLoggerInstance();
			pLogger->Error(msg, __FILE__, __LINE__);
			WebExceptionResponse* pExpResponse = augeCreateWebExceptionResponse();
			pExpResponse->SetMessage(msg);
			return pExpResponse;
		}

		Workspace* pWorkspace = NULL;
		RasterWorkspace* pRasterWorkspace = NULL;
		ConnectionManager* pConnManager = augeGetConnectionManagerInstance();

		pWorkspace = pConnManager->GetWorkspace(pUser->GetID(), sourceName);
		if(pWorkspace==NULL)
		{
			char msg[AUGE_MSG_MAX];
			g_sprintf(msg, "Cannot Get DataSource [%s]", sourceName);
			GLogger* pLogger = augeGetLoggerInstance();
			pLogger->Error(msg, __FILE__, __LINE__);
			WebExceptionResponse* pExpResponse = augeCreateWebExceptionResponse();
			pExpResponse->SetMessage(msg);
			return pExpResponse;
		}
		if(!pWorkspace->IsOpen())
		{
			char msg[AUGE_MSG_MAX];
			g_sprintf(msg, "Cannot Connect to DataSource [%s]", sourceName);
			GLogger* pLogger = augeGetLoggerInstance();
			pLogger->Error(msg, __FILE__, __LINE__);
			WebExceptionResponse* pExpResponse = augeCreateWebExceptionResponse();
			pExpResponse->SetMessage(msg);
			return pExpResponse;
		}

		pRasterWorkspace = dynamic_cast<RasterWorkspace*>(pWorkspace);

		RasterFolder* pFolder = pRasterWorkspace->GetFolder(path);
		if(pFolder==NULL)
		{
			char msg[AUGE_MSG_MAX];
			g_sprintf(msg, "Path [%s] does not exist.", path);
			GLogger* pLogger = augeGetLoggerInstance();
			pLogger->Error(msg, __FILE__, __LINE__);
			WebExceptionResponse* pExpResponse = augeCreateWebExceptionResponse();
			pExpResponse->SetMessage(msg);
			return pExpResponse;
		}

		ListResponse* pResponse = new ListResponse(pRequest);
		pResponse->SetFolder(pFolder);

		return pResponse;
	}
TEST_F(EnergyPlusFixture, ForwardTranslator_ScheduleVariableInterval_500_Shifted)
{
  // The vector of time deltas, randomly generated
  long numbers[500] = { 86313, 48668, 46739, 86313, 86313, 35939, 28787, 81175, 41086, 60467, 71308, 36332,
    75050, 44913, 86313, 36150, 86313, 86313, 86313, 86313, 49633, 23793, 86313, 86313, 86313, 78168, 72707,
    56754, 35868, 29986, 25413, 40812, 62829, 31364, 77455, 76379, 86313, 50167, 34835, 70623, 86313, 70817,
    48215, 52955, 59462, 27876, 27334, 52308, 32575, 86313, 86313, 53883, 57044, 86313, 45829, 38304, 42861,
    86313, 86313, 29215, 35662, 86313, 86313, 63866, 73697, 58074, 80833, 85161, 60866, 85214, 38748, 86313,
    86313, 36676, 33285, 86313, 38269, 86313, 67373, 56445, 86313, 85745, 54775, 51067, 86313, 23644, 34226,
    86313, 71364, 64214, 45392, 86313, 49499, 71086, 50232, 86313, 86313, 75456, 62390, 78586, 67472, 66497,
    51741, 76133, 86313, 52833, 72670, 65395, 86313, 86180, 67179, 86313, 86313, 86313, 33630, 48006, 42881,
    69935, 39664, 63806, 41471, 35258, 31512, 83115, 86313, 73282, 86313, 86313, 53505, 47981, 61876, 86313,
    31543, 86313, 37030, 66163, 47482, 58352, 86313, 73380, 86313, 46900, 59984, 57889, 41704, 42690, 86313,
    86313, 51497, 71154, 42596, 73589, 27242, 61291, 43573, 86313, 65535, 86313, 58071, 86313, 79620, 86313,
    26578, 32739, 86313, 34133, 70385, 27867, 81956, 72324, 38580, 29633, 33298, 59005, 27369, 32838, 61259,
    35188, 77004, 86313, 60872, 86313, 49717, 43171, 27070, 35573, 30796, 86313, 86313, 86313, 86313, 63163,
    77254, 45155, 86313, 86313, 57614, 59737, 48050, 86313, 86313, 72316, 52488, 60663, 50962, 35766, 81130,
    70904, 34878, 76407, 68502, 82977, 86313, 55383, 33518, 86313, 29334, 28864, 44800, 64615, 86313, 78882,
    66482, 50578, 78395, 66541, 68202, 83235, 61364, 81762, 86313, 47870, 34782, 46302, 50788, 49417, 44120,
    74002, 25114, 86313, 24457, 53465, 26107, 33636, 86313, 80121, 64977, 30723, 40309, 86313, 86313, 76107,
    86313, 33956, 52007, 62567, 86313, 58138, 41487, 31619, 33507, 62906, 35965, 86313, 43492, 86313, 24031,
    83944, 86313, 86313, 71510, 86284, 56508, 28345, 39127, 86313, 37952, 54719, 79620, 36024, 86313, 86313,
    86313, 86313, 30591, 83941, 64038, 74265, 75851, 56856, 44849, 27458, 30350, 24754, 31329, 56821, 55979,
    39576, 50515, 52438, 84957, 85891, 51660, 86313, 49117, 86313, 63442, 24063, 77802, 29621, 37905, 53515,
    72884, 81821, 86313, 86313, 86313, 86313, 84048, 86313, 76408, 70785, 55767, 86313, 41679, 83722, 85612,
    86313, 86313, 29925, 86313, 52021, 86313, 78981, 86313, 86313, 50598, 74333, 67904, 86313, 31582, 86313,
    70034, 86313, 35070, 74448, 45073, 86313, 86313, 71613, 35444, 63476, 53592, 84978, 26717, 58140, 61863,
    84549, 58604, 34180, 62200, 36225, 83922, 33905, 83064, 24935, 51077, 86313, 49476, 61010, 41624, 65246,
    30697, 86313, 26883, 86313, 75916, 48961, 86313, 53663, 86313, 38177, 51527, 79510, 86313, 26712, 74984,
    64740, 86313, 49378, 86313, 86313, 47440, 32930, 25094, 76695, 68608, 35416, 86313, 86313, 26731, 86313,
    65665, 57451, 86313, 64561, 47067, 76935, 31435, 72573, 86313, 38846, 72254, 42634, 86313, 86313, 71265,
    86313, 56154, 86313, 66939, 86313, 30369, 36409, 67475, 86313, 86313, 86313, 86313, 38236, 86313, 57408,
    66435, 29802, 72062, 86313, 43899, 86313, 47590, 64377, 53064, 68569, 37843, 86313, 86313, 86313, 86313,
    69253, 54914, 33398, 26446, 49428, 59356, 86313, 86313, 86313, 78915, 44437, 61977, 75481, 86313, 86313,
    47774, 71126, 86313, 84201, 86313, 66183, 44427, 59010, 24018, 34729, 86313, 32745, 86313, 48847, 61975,
    76417, 86313, 86313, 66541, 51775, 86313, 86129, 36853, 86313, 70306, 46162, 86313, 86313, 29768, 46103,
    24318, 26234, 59933, 43230, 65930, 86313, 86313, 54580 };

  // The vector of values
  Vector values = linspace(1, 500, 500);

  // Create the vector of seconds from start
  std::vector<long> seconds(500);
  seconds[0] = numbers[0];
  for (unsigned i = 1; i<500; i++) {
    seconds[i] = numbers[i] + seconds[i - 1];
  }

  // Create a time series starting 12/31 00:00:-86313 with irregular interval
  TimeSeries timeseries(DateTime(Date(MonthOfYear::Jan, 1)), seconds, values, "");

  Model model;

  // Create a schedule and make sure it worked
  boost::optional<ScheduleInterval> scheduleInterval = ScheduleInterval::fromTimeSeries(timeseries, model);
  ASSERT_TRUE(scheduleInterval);
  ASSERT_TRUE(scheduleInterval->optionalCast<ScheduleVariableInterval>());

  // Forward translate the schedule
  ForwardTranslator ft;
  Workspace workspace = ft.translateModel(model);

  std::vector<WorkspaceObject> objects = workspace.getObjectsByType(IddObjectType::Schedule_Compact);
  ASSERT_EQ(1u, objects.size());

  boost::regex throughRegex("^Through:\\s*(.*)/\\s*(.*)\\s*");
  boost::regex untilRegex("^Until:\\s*(.*):(.*)\\s*");

  // Write out the schedule - keep this around for now
  //workspace.save(toPath("./ForwardTranslator_ScheduleVariableInterval_500_Shifted.idf"), true);

  // Check the contents of the output
  unsigned N = objects[0].numFields();
  boost::optional<Date> lastDateThrough;
  bool until24Found = false;
  bool nextValueShouldBeLast = false;
  unsigned numUntils = 0;

  for (unsigned i = 0; i < N; ++i) {
    boost::optional<std::string> field = objects[0].getString(i, true, false);
    ASSERT_TRUE(field);

    if (nextValueShouldBeLast) {
      double value = boost::lexical_cast<double>(*field);
      EXPECT_EQ(500.0, value);
      nextValueShouldBeLast = false;
    }

    boost::smatch throughMatches;
    if (boost::regex_search(*field, throughMatches, throughRegex)) {

      std::string monthText(throughMatches[1].first, throughMatches[1].second);
      std::string dayText(throughMatches[2].first, throughMatches[2].second);

      int month = boost::lexical_cast<int>(monthText);
      int day = boost::lexical_cast<int>(dayText);

      Date date(MonthOfYear(month), day);
      if (lastDateThrough) {
        // check that this date is greater than last date
        EXPECT_TRUE(date > *lastDateThrough) << date << " <= " << *lastDateThrough;

        // check that last date was closed at 24:00
        EXPECT_TRUE(until24Found);
      }
      lastDateThrough = date;
      until24Found = false;
    }

    boost::smatch untilMatches;
    if (boost::regex_search(*field, untilMatches, untilRegex)) {

      numUntils += 1;

      std::string hrText(untilMatches[1].first, untilMatches[1].second);
      std::string minText(untilMatches[2].first, untilMatches[2].second);

      int hr = boost::lexical_cast<int>(hrText);
      int min = boost::lexical_cast<int>(minText);
      EXPECT_TRUE(hr <= 24);
      EXPECT_TRUE(min < 60);

      if ((hr == 24) && (min == 0)) {
        until24Found = true;
      }

      // should NOT see Until: 00:00,
      EXPECT_FALSE((hr == 0) && (min == 0));

      if ((lastDateThrough == Date(MonthOfYear(12), 31)) && until24Found) {
        nextValueShouldBeLast = true;
      }
    }
  }
  bool lastUntil24Found = until24Found;

  // check last date was closed
  EXPECT_TRUE(lastUntil24Found);

  // check that there were 8760 untils
  EXPECT_EQ(864, numUntils);
}
Exemple #21
0
bool MakeBuild::Build(const Workspace& wspc, String mainparam, String outfile, bool clear_console)
{
	String hfile = outfile + ".xxx";
	SaveFile(hfile, "");
	FileTime start_time = GetFileTime(hfile); // Defensive way to get correct filetime of start
	DeleteFile(hfile);
	
	ClearErrorEditor();
	BeginBuilding(true, clear_console);
	bool ok = true;
	if(wspc.GetCount()) {
		for(int i = 0; i < wspc.GetCount(); i++) {
			const Package& pk = wspc.package[i];
			for(int j = 0; j < pk.GetCount(); j++)
				if(pk[j] == "main.conf") {
					String pn = wspc[i];
					String p = SourcePath(pn, "main.conf");
					main_conf << "// " << pn << "\r\n" << LoadFile(p) << "\r\n";
					PutConsole("Found " + p);
				}
		}

		if(main_conf.GetCount()) {
			VectorMap<String, String> bm = GetMethodVars(method);
			One<Host> host = CreateHost(false);
			One<Builder> b = CreateBuilder(~host);
			if(b) {
				Index<String> mcfg = PackageConfig(wspc, 0, bm, mainparam, *host, *b, NULL);
				String outdir = OutDir(mcfg, wspc[0], bm, false);
				String path = AppendFileName(outdir, "main.conf.h");
				RealizePath(path);
				SaveChangedFile(path, main_conf);
				PutConsole("Saving " + path);
				add_includes << outdir << ';';
			}
		}

		Vector<int> build_order;
		if(GetTargetMode().linkmode != 2) {
			for(int i = 1; i < wspc.GetCount(); i++)
				build_order.Add(i);
		}
		else {
			Index<int> remaining;
			for(int i = 1; i < wspc.GetCount(); i++)
				remaining.Add(i);
			while(!remaining.IsEmpty()) {
				int t;
				for(t = 0; t < remaining.GetCount(); t++) {
					const Package& pk = wspc.package[remaining[t]];
					bool delay = false;
					for(int u = 0; u < pk.uses.GetCount(); u++)
						if(remaining.Find(wspc.package.Find(pk.uses[u].text)) >= 0) {
							delay = true;
							break;
						}
					if(!delay)
						break;
				}
				if(t >= remaining.GetCount())
					t = 0;
				build_order.Add(remaining[t]);
				remaining.Remove(t);
			}
		}

		String mainpackage = wspc[0];
		Vector<String> linkfile;
		String linkopt = GetMethodVars(method).Get(targetmode ? "RELEASE_LINK" : "DEBUG_LINK", Null);
		if(linkopt.GetCount())
			linkopt << ' ';
		ok = true;
		int ms = msecs();
		for(int i = 0; i < build_order.GetCount() && (ok || !stoponerrors); i++) {
			int px = build_order[i];
			ok = BuildPackage(wspc, px, i, build_order.GetCount() + 1,
				              mainparam, Null, linkfile, linkopt) && ok;
			if(msecs() - ms >= 200) {
				DoProcessEvents();
				ms = msecs();
			}
		}
		if(ok || !stoponerrors) {
			ok = BuildPackage(wspc, 0, build_order.GetCount(), build_order.GetCount() + 1,
			                  mainparam, outfile, linkfile, linkopt, ok) && ok;
			// Set the time of target to start-time, so that if any file changes during
			// compilation, it is recompiled during next build
			SetFileTime(target, start_time); 
		}
	}
	EndBuilding(ok);
	ReQualifyCodeBase();
	SetErrorEditor();
	return ok;
}
Exemple #22
0
void MainFrame::OnDeleteClick(wxRibbonButtonBarEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());
    if(workspace) { workspace->DeleteSelectedElements(); }
}
OptionalModelObject ReverseTranslator::translateZone( const WorkspaceObject & workspaceObject )
{
 if( workspaceObject.iddObject().type() != IddObjectType::Zone ){
    LOG(Error, "WorkspaceObject is not IddObjectType: Zone");
    return boost::none;
  }

  // this function creates a space and a thermal zone, it returns the space.  If you want the 
  // thermal zone you can reliably dereference the result of space.thermalZone().

  openstudio::model::ThermalZone thermalZone( m_model );

  openstudio::model::Space space( m_model );
  space.setThermalZone(thermalZone);

  boost::optional<std::string> idfZoneName;

  OptionalString s = workspaceObject.name();
  if(s){
    space.setName(*s);
    thermalZone.setName(*s + " Thermal Zone");
    idfZoneName = *s;
  }

  OptionalDouble d = workspaceObject.getDouble(ZoneFields::DirectionofRelativeNorth);
  if(d){
    space.setDirectionofRelativeNorth(*d);
  }

  d=workspaceObject.getDouble(ZoneFields::XOrigin);
  if(d){
    space.setXOrigin(*d);
  }

  d=workspaceObject.getDouble(ZoneFields::YOrigin);
  if(d){
    space.setYOrigin(*d);
  }

  d=workspaceObject.getDouble(ZoneFields::ZOrigin);
  if(d){
    space.setZOrigin(*d);
  }

  OptionalInt i = workspaceObject.getInt(ZoneFields::Type);
  if(i){
    // no-op
  }

  i = workspaceObject.getInt(ZoneFields::Multiplier);
  if(i){
    thermalZone.setMultiplier(*i);
  }

  d = workspaceObject.getDouble(ZoneFields::CeilingHeight);
  if(d){
    thermalZone.setCeilingHeight(*d);
  }

  d=workspaceObject.getDouble(ZoneFields::Volume);
  if(d){
    thermalZone.setVolume(*d);
  }

  s = workspaceObject.getString(ZoneFields::ZoneInsideConvectionAlgorithm);
  if(s){
    thermalZone.setZoneInsideConvectionAlgorithm(*s);
  }

  s = workspaceObject.getString(ZoneFields::ZoneOutsideConvectionAlgorithm);
  if(s){
    thermalZone.setZoneOutsideConvectionAlgorithm(*s);
  }

  s = workspaceObject.getString(ZoneFields::PartofTotalFloorArea);
  if(s){
    if(istringEqual("Yes",*s))
    {
      space.setPartofTotalFloorArea(true);
    }
    else
    {
      space.setPartofTotalFloorArea(false);
    }
  }

  // Thermostat

  // If the zone in the idf file does not have a name, there is no use in even trying to find a thermostat
  if( idfZoneName )
  {
    Workspace workspace = workspaceObject.workspace();
    
    std::vector<WorkspaceObject> _zoneControlThermostats;
    _zoneControlThermostats = workspace.getObjectsByType(IddObjectType::ZoneControl_Thermostat);

    for( const auto & _zoneControlThermostat : _zoneControlThermostats )
    {
      if( boost::optional<std::string> zoneName = _zoneControlThermostat.getString( ZoneControl_ThermostatFields::ZoneorZoneListName ) )
      {
        bool zoneControlThermostatfound = false;

        if( zoneName.get() == idfZoneName ) 
        { 
          zoneControlThermostatfound = true; 
        }
        else if( boost::optional<WorkspaceObject> _zoneList = workspace.getObjectByTypeAndName(IddObjectType::ZoneList,zoneName.get()) )
        {
          std::vector<IdfExtensibleGroup> zoneListGroup = _zoneList->extensibleGroups();

          for( const auto & zoneListElem : zoneListGroup )
          {
            boost::optional<std::string> zoneListZoneName = zoneListElem.getString(ZoneListExtensibleFields::ZoneName);
            if( zoneListZoneName )
            {
              if( zoneListZoneName.get() == idfZoneName ) { zoneControlThermostatfound = true; }
              break;
            }
          }
        }
        if( zoneControlThermostatfound )
        {
          std::vector<IdfExtensibleGroup> extensibleGroups = _zoneControlThermostat.extensibleGroups();
          for( const auto & extensibleGroup : extensibleGroups )
          {
            boost::optional<std::string> thermostatType = extensibleGroup.getString(ZoneControl_ThermostatExtensibleFields::ControlObjectType);
            boost::optional<std::string> thermostatName = extensibleGroup.getString(ZoneControl_ThermostatExtensibleFields::ControlName);

            if( thermostatName && thermostatType )
            {
              boost::optional<WorkspaceObject> _thermostat
               = workspace.getObjectByTypeAndName(IddObjectType(thermostatType.get()),thermostatName.get());
              
              if( _thermostat )
              {
                boost::optional<ModelObject> thermostat = translateAndMapWorkspaceObject(_thermostat.get());
                if( thermostat )
                {
                  if( boost::optional<ThermostatSetpointDualSetpoint> thermostatSetpointDualSetpoint
                      = thermostat->optionalCast<ThermostatSetpointDualSetpoint>() )
                  {
                    thermalZone.setThermostatSetpointDualSetpoint(thermostatSetpointDualSetpoint.get());
                  }
                }
              }
            }
          }
          break;
        }
      }
    }
  }

  // Zone Equipment
/*
  if( idfZoneName )
  {
    std::vector<WorkspaceObject> zoneHVACEquipmentConnections;
    zoneHVACEquipmentConnections = workspaceObject.workspace().getObjectsByType(IddObjectType::ZoneHVAC_EquipmentConnections);

    for( std::vector<WorkspaceObject>::iterator it = zoneHVACEquipmentConnections.begin();
         it != zoneHVACEquipmentConnections.end();
         it++ )
    {
      s = it->getString(ZoneHVAC_EquipmentConnectionsFields::ZoneName);

      if( s && istringEqual(s.get(),idfZoneName.get()) )
      {
        boost::optional<WorkspaceObject> _zoneEquipmentList = it->getTarget(ZoneHVAC_EquipmentConnectionsFields::ZoneConditioningEquipmentListName);

        if( _zoneEquipmentList )
        {
          translateAndMapWorkspaceObject(_zoneEquipmentList.get());
        }

        break;
      }
    }
  }
*/

  return space;
}
Exemple #24
0
void MakeBuild::SaveMakeFile(const String& fn, bool exporting)
{
	BeginBuilding(false, true);

	VectorMap<String, String> bm = GetMethodVars(method);
	One<Host> host = CreateHost(false);
	One<Builder> b = CreateBuilder(~host);
	
	if(!b)
		return;
	
	const TargetMode& tm = GetTargetMode();

	String makefile;

	Vector<String> uppdirs = GetUppDirs();
	String uppout = exporting ? host->GetHostPath(GetVar("OUTPUT")) : "_out/";
	String inclist;

	Index<String> allconfig = PackageConfig(GetIdeWorkspace(), 0, bm, mainconfigparam, *host, *b);
	bool win32 = allconfig.Find("WIN32") >= 0;

	Workspace wspc;
	wspc.Scan(GetMain(), allconfig.GetKeys());

	for(int i = 1; i < wspc.GetCount(); i++) {
		Index<String> modconfig = PackageConfig(wspc, i, bm, mainconfigparam, *host, *b);
		for(int a = allconfig.GetCount(); --a >= 0;)
			if(modconfig.Find(allconfig[a]) < 0)
				allconfig.Remove(a);
	}

	if(!exporting)
		for(int i = 0; i < uppdirs.GetCount(); i++) {
			String srcdir = GetMakePath(AdjustMakePath(host->GetHostPath(AppendFileName(uppdirs[i], ""))), win32);
			makefile << "UPPDIR" << (i + 1) << " = " << srcdir << "\n";
			inclist << " -I$(UPPDIR" << (i + 1) << ")";
		}
	else
		inclist << "-I./";
	Vector<String> includes = SplitDirs(bm.Get("INCLUDE",""));
	for(int i = 0; i < includes.GetCount(); i++)
		inclist << " -I" << includes[i];

	makefile << "\n"
		"UPPOUT = " << (exporting ? "_out/" : GetMakePath(AdjustMakePath(host->GetHostPath(AppendFileName(uppout, ""))), win32)) << "\n"
		"CINC = " << inclist << "\n"
		"Macro = ";

	for(int i = 0; i < allconfig.GetCount(); i++)
		makefile << " -Dflag" << allconfig[i];
	makefile << "\n";

	String output, config, install, rules, linkdep, linkfiles, linkfileend;

	for(int i = 0; i < wspc.GetCount(); i++) {
		b->config = PackageConfig(wspc, i, bm, mainconfigparam, *host, *b);
		b->version = tm.version;
		b->method = method;
		MakeFile mf;
		b->AddMakeFile(mf, wspc[i], GetAllUses(wspc, i),
		               GetAllLibraries(wspc, i, bm, mainconfigparam, *host, *b), allconfig,
		               exporting);
		if(!i) {
			String tdir = mf.outdir;
			String trg;
			if(tm.target_override) {
				trg = GetMakePath(AdjustMakePath(tm.target), win32);
				if(!trg.IsEmpty() && *trg.Last() == (win32 ? '\\' : '/'))
					trg << mf.outfile;
				else if(trg.Find(win32 ? '\\' : '/') < 0)
					trg.Insert(0, "$(OutDir)");
			}
			output = Nvl(trg, mf.output);
			if(exporting)
				output = wspc[i] + ".out";
			install << "\n"
				"OutDir = " << tdir << "\n"
				"OutFile = " << output << "\n"
				"\n"
				".PHONY: all\n"
				"all: prepare $(OutFile)\n"
				"\n"
				".PHONY: prepare\n"
				"prepare:\n";
		}
		config << mf.config;
		install << mf.install;
		rules << mf.rules;
		linkdep << mf.linkdep;
		linkfiles << mf.linkfiles;
		linkfileend << mf.linkfileend;
	}

	makefile
		<< config
		<< install
		<< "\n"
		"$(OutFile): " << linkdep << "\n\t" << linkfiles << linkfileend << " -Wl,--end-group\n\n"
		<< rules
		<< ".PHONY: clean\n"
		<< "clean:\n"
		<< "\tif [ -d $(UPPOUT) ]; then rm -rf $(UPPOUT); fi;\n";

	bool sv = ::SaveFile(fn, makefile);
	if(!exporting)
		if(sv)
			PutConsole(NFormat("%s(1): makefile generation complete", fn));
		else
			PutConsole(NFormat("%s: error writing makefile", fn));

	EndBuilding(true);
}
/* Ensures that the nodes that translated correctly
 * that means correct node names in the CentralHeatPumpSystem but also
 * on the Branches
 */
TEST_F(EnergyPlusFixture,ForwardTranslatorCentralHeatPumpSystem_Nodes) {

  boost::optional<WorkspaceObject> _wo;
  ForwardTranslator ft;

  Model m;

  CentralHeatPumpSystem central_hp(m);
  ASSERT_TRUE(central_hp.setAncillaryPower(0.7));
  EXPECT_FALSE(central_hp.ancillaryOperationSchedule());
  Schedule schedule = m.alwaysOnDiscreteSchedule();

  // Return type: bool
  ASSERT_TRUE(central_hp.setAncillaryOperationSchedule(schedule));
  EXPECT_TRUE(central_hp.ancillaryOperationSchedule());

  // First module has one
  CentralHeatPumpSystemModule central_hp_module(m);
  central_hp.addModule(central_hp_module);
  EXPECT_EQ(1, central_hp_module.numberofChillerHeaterModules());

  // Second has 2
  CentralHeatPumpSystemModule central_hp_module2(m);
  central_hp.addModule(central_hp_module2);
  ASSERT_TRUE(central_hp_module2.setNumberofChillerHeaterModules(2));


  ASSERT_EQ( (unsigned)2, central_hp.modules().size() );


  // Connect the CentralHP to three plant loops
  // CoolingLoop: on the supply side
  PlantLoop coolingPlant(m);
  EXPECT_TRUE(coolingPlant.addSupplyBranchForComponent(central_hp));

  // SourceLoop: on the demand side
  PlantLoop sourcePlant(m);
  EXPECT_TRUE(sourcePlant.addDemandBranchForComponent(central_hp));
  // Also add a CT to the sourcePlant
  CoolingTowerSingleSpeed ct(m);
  sourcePlant.addSupplyBranchForComponent(ct);

  // HeatingLoop: on the supply side
  PlantLoop heatingPlant(m);
  // Workaround to be able to use addToTertiaryNode directly
  // (addSupplyBranchForComponent should work directly, but this is tested in model GTest, so here we just make sure we call
  // addToTertiaryNode directly)
  BoilerHotWater temp_b(m);
  EXPECT_TRUE(heatingPlant.addSupplyBranchForComponent(temp_b));

  ASSERT_TRUE(temp_b.inletModelObject());
  auto node = temp_b.inletModelObject().get().cast<Node>();
  EXPECT_TRUE(central_hp.addToTertiaryNode(node));
  temp_b.remove();


  // Translate
  Workspace w = ft.translateModel(m);

  EXPECT_EQ(0u, ft.errors().size());
  EXPECT_EQ(1u, w.getObjectsByType(IddObjectType::CentralHeatPumpSystem).size());

  IdfObject i_central_hp = w.getObjectsByType(IddObjectType::CentralHeatPumpSystem)[0];

  // supply = Cooling
  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::CoolingLoopInletNodeName).get(),
            central_hp.supplyInletModelObject().get().name());

  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::CoolingLoopOutletNodeName).get(),
            central_hp.supplyOutletModelObject().get().name());

  // demand = Source
  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::SourceLoopInletNodeName).get(),
            central_hp.demandInletModelObject().get().name());

  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::SourceLoopOutletNodeName).get(),
            central_hp.demandOutletModelObject().get().name());

  // tertiary = Heating
  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::HeatingLoopInletNodeName).get(),
            central_hp.tertiaryInletModelObject().get().name());

  ASSERT_EQ(i_central_hp.getString(CentralHeatPumpSystemFields::HeatingLoopOutletNodeName).get(),
            central_hp.tertiaryOutletModelObject().get().name());


  // Check node names on supply/demand branches
  // Checks that the special case implemented in ForwardTranslatePlantLoop::populateBranch does the right job

  // supply = Cooling (on supply)
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, coolingPlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_plant = _wo.get();
    WorkspaceObject idf_brlist = idf_plant.getTarget(PlantLoopFields::PlantSideBranchListName).get();

    // Should have three branches: supply inlet, the one with the centralHP, supply outlet
    ASSERT_EQ(3u, idf_brlist.extensibleGroups().size());
    // Get the Central HP one
    WorkspaceExtensibleGroup w_eg = idf_brlist.extensibleGroups()[1].cast<WorkspaceExtensibleGroup>();
    WorkspaceObject idf_branch = w_eg.getTarget(BranchListExtensibleFields::BranchName).get();

    // There should be only one equipment on the branch
    ASSERT_EQ(1u, idf_branch.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg2 = idf_branch.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentName).get(),
        central_hp.name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentInletNodeName).get(),
        central_hp.supplyInletModelObject().get().name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentOutletNodeName).get(),
        central_hp.supplyOutletModelObject().get().name());
  }

  // tertiary = Heating (on supply)
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, heatingPlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_plant = _wo.get();
    WorkspaceObject idf_brlist = idf_plant.getTarget(PlantLoopFields::PlantSideBranchListName).get();

    // Should have three branches: supply inlet, the one with the centralHP, supply outlet
    ASSERT_EQ(3u, idf_brlist.extensibleGroups().size());
    // Get the Central HP one
    WorkspaceExtensibleGroup w_eg = idf_brlist.extensibleGroups()[1].cast<WorkspaceExtensibleGroup>();
    WorkspaceObject idf_branch = w_eg.getTarget(BranchListExtensibleFields::BranchName).get();

    // There should be only one equipment on the branch
    ASSERT_EQ(1u, idf_branch.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg2 = idf_branch.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentName).get(),
        central_hp.name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentInletNodeName).get(),
        central_hp.tertiaryInletModelObject().get().name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentOutletNodeName).get(),
        central_hp.tertiaryOutletModelObject().get().name());
  }

  // demand = Source (on demand)
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, sourcePlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_plant = _wo.get();
    // Demand Side Branch List Name
    WorkspaceObject idf_brlist = idf_plant.getTarget(PlantLoopFields::DemandSideBranchListName).get();

    // Should have four branches: supply inlet, the one with the centralHP, a bypass, supply outlet
    ASSERT_EQ(4u, idf_brlist.extensibleGroups().size());
    // Get the Central HP one, which should be the second one
    WorkspaceExtensibleGroup w_eg = idf_brlist.extensibleGroups()[1].cast<WorkspaceExtensibleGroup>();
    WorkspaceObject idf_branch = w_eg.getTarget(BranchListExtensibleFields::BranchName).get();

    // There should be only one equipment on the branch
    ASSERT_EQ(1u, idf_branch.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg2 = idf_branch.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentName).get(),
        central_hp.name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentInletNodeName).get(),
        central_hp.demandInletModelObject().get().name());

    ASSERT_EQ(w_eg2.getString(BranchExtensibleFields::ComponentOutletNodeName).get(),
        central_hp.demandOutletModelObject().get().name());
  }

  // m.save(toPath("./ft_central_hp.osm"), true);
  // w.save(toPath("./ft_central_hp.idf"), true);

}
/* This tests ensures that the CentralHeatPumpSystem ends up in a PlantEquipmentOperation:HeatingLoad for the heating loop
 * and PlantEquipmentOperation:CoolingLoad for the cooling loop. For the source loop, it's on the demand side so it shouldn't
 * be part of the plant equipment list used
 */
TEST_F(EnergyPlusFixture,ForwardTranslatorCentralHeatPumpSystem_PlantEquipmentOperation) {

  boost::optional<WorkspaceObject> _wo;
  ForwardTranslator ft;

  Model m;

  CentralHeatPumpSystem central_hp(m);

  // Add a Module
  CentralHeatPumpSystemModule central_hp_module(m);
  central_hp.addModule(central_hp_module);
  EXPECT_EQ(1, central_hp_module.numberofChillerHeaterModules());

  // Connect the CentralHP to three plant loops
  // CoolingLoop: on the supply side
  PlantLoop coolingPlant(m);
  EXPECT_TRUE(coolingPlant.addSupplyBranchForComponent(central_hp));

  // SourceLoop: on the demand side
  PlantLoop sourcePlant(m);
  EXPECT_TRUE(sourcePlant.addDemandBranchForComponent(central_hp));
  // Also add a CT to the sourcePlant
  CoolingTowerSingleSpeed ct(m);
  sourcePlant.addSupplyBranchForComponent(ct);

  // HeatingLoop: on the supply side
  PlantLoop heatingPlant(m);
  // Workaround to be able to use addToTertiaryNode directly
  // (addSupplyBranchForComponent should work directly, but this is tested in model GTest, so here we just make sure we call
  // addToTertiaryNode directly)
  BoilerHotWater temp_b(m);
  EXPECT_TRUE(heatingPlant.addSupplyBranchForComponent(temp_b));

  ASSERT_TRUE(temp_b.inletModelObject());
  auto node = temp_b.inletModelObject().get().cast<Node>();
  EXPECT_TRUE(central_hp.addToTertiaryNode(node));
  temp_b.remove();



  Workspace w = ft.translateModel(m);

  EXPECT_EQ(0u, ft.errors().size());
  EXPECT_EQ(1u, w.getObjectsByType(IddObjectType::CentralHeatPumpSystem).size());

  IdfObject i_central_hp = w.getObjectsByType(IddObjectType::CentralHeatPumpSystem)[0];



  // Get the Loops, and find their plant operation scheme

  // supply = Cooling
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, coolingPlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_coolingPlant = _wo.get();
    WorkspaceObject idf_plant_op = idf_coolingPlant.getTarget(PlantLoopFields::PlantEquipmentOperationSchemeName).get();

    // Should have created a Cooling Load one only
    ASSERT_EQ(1u, idf_plant_op.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg = idf_plant_op.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    ASSERT_EQ("PlantEquipmentOperation:CoolingLoad", w_eg.getString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType).get());

    // Get the Operation Scheme
    _wo = w_eg.getTarget(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_op_scheme = _wo.get();

    // Get the Plant Equipment List of this CoolingLoad scheme
    // There should only be one Load Range
    ASSERT_EQ(1u, idf_op_scheme.extensibleGroups().size());
    // Load range 1
    w_eg = idf_op_scheme.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    _wo = w_eg.getTarget(PlantEquipmentOperation_CoolingLoadExtensibleFields::RangeEquipmentListName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_peq_list = _wo.get();

    // Should have one equipment on it: CentralHeatPumpSystem
    ASSERT_EQ(1u, idf_peq_list.extensibleGroups().size());
    IdfExtensibleGroup idf_eg(idf_peq_list.extensibleGroups()[0]);
    ASSERT_EQ(central_hp.name().get(), idf_eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());

  }


  // tertiary = Heating
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, heatingPlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_heatingPlant = _wo.get();
    WorkspaceObject idf_plant_op = idf_heatingPlant.getTarget(PlantLoopFields::PlantEquipmentOperationSchemeName).get();

    // Should have created a Heating Load one only
    ASSERT_EQ(1u, idf_plant_op.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg = idf_plant_op.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    ASSERT_EQ("PlantEquipmentOperation:HeatingLoad", w_eg.getString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType).get());

    // Get the Operation Scheme
    _wo = w_eg.getTarget(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_op_scheme = _wo.get();

    // Get the Plant Equipment List of this HeatingLoad scheme
    // There should only be one Load Range
    ASSERT_EQ(1u, idf_op_scheme.extensibleGroups().size());
    // Load range 1
    w_eg = idf_op_scheme.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    _wo = w_eg.getTarget(PlantEquipmentOperation_HeatingLoadExtensibleFields::RangeEquipmentListName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_peq_list = _wo.get();

    // Should have one equipment on it: CentralHeatPumpSystem
    ASSERT_EQ(1u, idf_peq_list.extensibleGroups().size());
    IdfExtensibleGroup idf_eg(idf_peq_list.extensibleGroups()[0]);
    ASSERT_EQ(central_hp.name().get(), idf_eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());

  }



  // SourceLoop: on the demand side. So it shouldn't be on it
  {
    _wo = w.getObjectByTypeAndName(IddObjectType::PlantLoop, sourcePlant.name().get());
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_sourcePlant = _wo.get();
    WorkspaceObject idf_plant_op = idf_sourcePlant.getTarget(PlantLoopFields::PlantEquipmentOperationSchemeName).get();

    // Should have created a Cooling Load one only
    ASSERT_EQ(1u, idf_plant_op.extensibleGroups().size());
    WorkspaceExtensibleGroup w_eg = idf_plant_op.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    ASSERT_EQ("PlantEquipmentOperation:CoolingLoad", w_eg.getString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType).get());

    // Get the Operation Scheme
    _wo = w_eg.getTarget(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_op_scheme = _wo.get();

    // Get the Plant Equipment List of this HeatingLoad scheme
    // There should only be one Load Range
    ASSERT_EQ(1u, idf_op_scheme.extensibleGroups().size());
    // Load range 1
    w_eg = idf_op_scheme.extensibleGroups()[0].cast<WorkspaceExtensibleGroup>();
    _wo = w_eg.getTarget(PlantEquipmentOperation_CoolingLoadExtensibleFields::RangeEquipmentListName);
    ASSERT_TRUE(_wo.is_initialized());
    WorkspaceObject idf_peq_list = _wo.get();

    // Should have one equipment on it: Cooling Tower
    ASSERT_EQ(1u, idf_peq_list.extensibleGroups().size());
    IdfExtensibleGroup idf_eg(idf_peq_list.extensibleGroups()[0]);
    ASSERT_EQ(ct.name().get(), idf_eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());

  }

  m.save(toPath("./ft_central_hp.osm"), true);
  w.save(toPath("./ft_central_hp.idf"), true);

}
TEST_F(EnergyPlusFixture,ForwardTranslatorTest_TranslateCoolingCoil)
{
  Model model;
  ScheduleCompact scheduleCompact(model);
  scheduleCompact.setName("Daytime Ventilation For Cooling Coil Test");
  scheduleCompact.setString(1,"Fraction");
  scheduleCompact.setString(2,"Through: 12/31");
  scheduleCompact.setString(3,"For: Weekdays SummerDesignDay");
  scheduleCompact.setString(4,"Until: 08:00");
  scheduleCompact.setString(5,"0.0");
  scheduleCompact.setString(6,"Until: 18:00");
  scheduleCompact.setString(7,"1.0");
  scheduleCompact.setString(8,"Until: 24:00");
  scheduleCompact.setString(9,"0.0");
  scheduleCompact.setString(10,"For: Weekends WinterDesignDay");
  scheduleCompact.setString(11,"Until: 10:00");
  scheduleCompact.setString(12,"0.0");
  scheduleCompact.setString(13,"Until: 16:00");
  scheduleCompact.setString(14,"1.0");
  scheduleCompact.setString(15,"Until: 24:00");
  scheduleCompact.setString(16,"0.0");
  scheduleCompact.setString(17,"For: Holidays AllOtherDays");
  scheduleCompact.setString(18,"Until: 24:00");
  scheduleCompact.setString(19,"0.0");

  CurveBiquadratic ccFofT(model);
  CurveBiquadratic eirFofT(model);
  CurveQuadratic ccFofF(model);
  CurveQuadratic eirFofF(model);
  CurveQuadratic plf(model);

  ccFofT.setCoefficient1Constant(1.0);
  ccFofT.setCoefficient2x(2.0);
  ccFofT.setCoefficient3xPOW2(3.0);
  ccFofT.setCoefficient4y(4.0);
  ccFofT.setCoefficient5yPOW2(5.0);
  ccFofT.setCoefficient6xTIMESY(6.0);
  ccFofT.setMinimumValueofx(-10.0);
  ccFofT.setMaximumValueofx(100.03);
  ccFofT.setMinimumValueofy(-99999);
  ccFofT.setMaximumValueofy(100232);
  ccFofT.setMinimumCurveOutput(-1000);
  ccFofT.setMaximumCurveOutput(99999);
  ccFofT.setInputUnitTypeforX("Temperature");
  ccFofT.setInputUnitTypeforY("MassFlow");

  eirFofT.setCoefficient1Constant(10.0);
  // eirFofT.setCoefficient2x(20.0); check default
  eirFofT.setCoefficient3xPOW2(30.0);
  eirFofT.setCoefficient4y(40.0);
  eirFofT.setCoefficient5yPOW2(50.0);
  eirFofT.setCoefficient6xTIMESY(60.0);
  eirFofT.setInputUnitTypeforX("VolumetricFlow");
  eirFofT.setInputUnitTypeforY("Power");

  plf.setCoefficient1Constant(5.50);
  plf.setCoefficient2x(55.50);
  plf.setCoefficient3xPOW2(23.50);

  CoilCoolingDXSingleSpeed cool(model,
                                scheduleCompact,
                                ccFofT,
                                ccFofF,
                                eirFofT,
                                eirFofF,
                                plf);

  ForwardTranslator trans;
  Workspace workspace = trans.translateModel(model);

  EXPECT_EQ(1u,workspace.getObjectsByType(IddObjectType::Version).size());
  EXPECT_EQ(1u,workspace.getObjectsByType(IddObjectType::Coil_Cooling_DX_SingleSpeed).size());
  EXPECT_EQ(1u,workspace.getObjectsByType(IddObjectType::Schedule_Compact).size());
  EXPECT_EQ(2u,workspace.getObjectsByType(IddObjectType::Curve_Biquadratic).size());
  EXPECT_EQ(3u,workspace.getObjectsByType(IddObjectType::Curve_Quadratic).size());

  path outDir = resourcesPath() / openstudio::toPath("CoolingCoilDXSingleSpeed.idf");
  boost::filesystem::ofstream ofs(outDir);
  workspace.toIdfFile().print(ofs);
  ofs.close();

  openstudio::path idfPath = resourcesPath() / openstudio::toPath("CoolingCoilDXSingleSpeed.idf");
  OptionalIdfFile idfFile = IdfFile::load(idfPath, IddFileType::EnergyPlus);
  ASSERT_TRUE(idfFile);
  Workspace inWorkspace(*idfFile);

  // Get the Model by calling the translator
  ReverseTranslator trans2;
  ASSERT_NO_THROW(trans2.translateWorkspace(inWorkspace));
  Model model2 =  trans2.translateWorkspace(inWorkspace);
}
Exemple #28
0
void MainFrame::OnSCPowerClick(wxRibbonButtonBarEvent& event)
{
    Workspace* workspace = static_cast<Workspace*>(m_auiNotebook->GetCurrentPage());
    if(workspace) { workspace->RunSCPower(); }
}
int witness_set_test(Workspace& workspace_cpu, CPUInstHom& cpu_inst_hom, Parameter path_parameter, CT* x_cpu, CT t, int device_option) {
	std::cout << "--------- Witness Set Test ----------" << std::endl;

	bool cpu_test = 0;
	bool gpu_test = 0;
	if(device_option == 1){
			cpu_test = 1;
			gpu_test = 0;
	}
	else if(device_option == 2){
		cpu_test = 0;
		gpu_test = 1;
	}
	else{
		std::cout << "Device_option Invalid. Choose from the following:" << std::endl
				  << "  1. CPU" << std::endl
				  << "  2. GPU" << std::endl
				  << "Your device_option = " << device_option << std::endl;
	}


	CT* x_new = NULL;

	PolySolSet witness_set_start(cpu_inst_hom.dim);
	PolySolSet witness_set_target(cpu_inst_hom.dim);

	witness_set_start.add_diff_sol(x_cpu);
	std::cout << "Witness Set1" << std::endl;
	witness_set_start.print_short();

	double timeSec_Predict = 0;
	double timeSec_Eval = 0;
	double timeSec_MGS = 0;
	double timeSec = 0;

	for(int i=0; i<10; i++){

		clock_t begin = clock();

		bool success = 0;
		int alpha_round = 0;
		while(success==0){
			cpu_inst_hom.path_data.clear();
			t = CT(0.0,0.0);
			workspace_cpu.init_x_t_idx();
			workspace_cpu.update_x_t(x_cpu, t);
			cpu_inst_hom.update_alpha();
			if(cpu_test == 1){
				success = path_tracker(workspace_cpu, cpu_inst_hom, path_parameter,\
						 timeSec_Predict, timeSec_Eval, timeSec_MGS);
			}
			if(gpu_test == 1){
				success = GPU_Path(cpu_inst_hom, path_parameter, x_cpu, t, x_new);
			}
			alpha_round++;
			if(success == 0 && alpha_round > 5){
				break;
			}
		}

		if(success == 0 && alpha_round > 5){
			std::cout << "Path Fail! Start -> Target" << std::endl \
					  << "alpha round = " << alpha_round << std::endl \
					  << "path  round = " << i << std::endl;
			break;
		}

		cpu_inst_hom.path_data.print_phc();

		clock_t end = clock();
		timeSec += (end - begin) / static_cast<double>( CLOCKS_PER_SEC );

		if(cpu_test == 1){
			workspace_cpu.copy_x_last(x_cpu);
		}

		if(gpu_test == 1){
			delete[] x_cpu;
			x_cpu = x_new;
		}

		witness_set_target.add_diff_sol(x_cpu);

		std::cout << "Witness Set Target" << std::endl;
		witness_set_target.print_short();
		if(witness_set_target.n_sol == 4 and witness_set_start.n_sol == 4){
			break;
		}

		// Path Tracking Reverse Test
		success = 0;
		alpha_round = 0;
		while(success==0){
			cpu_inst_hom.path_data.clear();
			t = CT(0.0,0.0);
			workspace_cpu.init_x_t_idx();
			workspace_cpu.update_x_t(x_cpu, t);
			cpu_inst_hom.update_alpha();
			//success = path_tracker(workspace_cpu, cpu_inst_hom, path_parameter,\
			//			 timeSec_Predict, timeSec_Eval, timeSec_MGS, 1);
			if(cpu_test == 1){
				success = path_tracker(workspace_cpu, cpu_inst_hom, path_parameter,\
						 timeSec_Predict, timeSec_Eval, timeSec_MGS, 1);
			}
			if(gpu_test == 1){
				success = GPU_Path(cpu_inst_hom, path_parameter, x_cpu, t, x_new, 1);
			}
			alpha_round++;
			if(success == 0 && alpha_round > 5){
				break;
			}
		}

		cpu_inst_hom.path_data.print_phc();

		if(success == 0 && alpha_round > 5){
			std::cout << "Path Fail! Target -> Start" << std::endl \
					  << "alpha round = " << alpha_round << std::endl \
					  << "path  round = " << i << std::endl;
			break;
		}

		if(cpu_test == 1){
			workspace_cpu.copy_x_last(x_cpu);
		}

		if(gpu_test == 1){
			delete[] x_cpu;
			x_cpu = x_new;
		}

		witness_set_start.add_diff_sol(x_cpu);

		std::cout << "Witness Set Start" << std::endl;
		witness_set_start.print_short();
		if(witness_set_target.n_sol == 4 and witness_set_start.n_sol == 4){
			break;
		}
	}
	std::cout << "Witness Set Start" << std::endl;
	witness_set_start.print_short();
	std::cout << "Witness Set Target" << std::endl;
	witness_set_target.print_short();

	/*for(int i=0; i<cpu_inst_hom.dim; i++) {
		std::cout << i << " " << x_cpu[i];
	}*/

	/*CT* x_gpu = GPU_Path(cpu_inst_hom, sol0, t, n_predictor, max_it, err_max_delta_x, max_step);
	 cout << "Path CPU Test      Time: "<< timeSec << endl;
	 std::cout << "--------- Path Tracking Error CPU vs GPU ----------" << std::endl;
	 T1 err = err_check_workspace(x_cpu, x_gpu, cpu_inst_hom.dim);
	 std::cout << " x_cpu[0] = " << x_cpu[0];
	 std::cout << " x_gpu[0] = " << x_gpu[0];
	 free(x_gpu);*/

	//T1 err = err_check_workspace(sol0, x_cpu, cpu_inst_hom.dim);

	cout << "Path CPU Predict   Time: "<< timeSec_Predict << endl;
	cout << "Path CPU Eval      Time: "<< timeSec_Eval << endl;
	cout << "Path CPU MGS       Time: "<< timeSec_MGS << endl;

	return witness_set_start.n_sol;
}
TEST_F(EnergyPlusFixture,ForwardTranslator_ScheduleVariableInterval_Hourly_Shifted)
{
  // Create the values vector and a vector of seconds from the start
  Vector values = linspace(1, 8760, 8760);
  std::vector<long> seconds(8760);
  for(unsigned i=0;i<seconds.size();i++) {
    seconds[i]=(i+1)*3600;
  }

  // Create an hourly time series starting 12/31 23:00:00
  TimeSeries timeseries(DateTime(Date(MonthOfYear::Jan, 1)), seconds, values, "");

  Model model;

  // Create a schedule and make sure it worked
  boost::optional<ScheduleInterval> scheduleInterval = ScheduleInterval::fromTimeSeries(timeseries, model);
  ASSERT_TRUE(scheduleInterval);
  ASSERT_TRUE(scheduleInterval->optionalCast<ScheduleVariableInterval>());

  // Forward translate the schedule
  ForwardTranslator ft;
  Workspace workspace = ft.translateModel(model);

  std::vector<WorkspaceObject> objects = workspace.getObjectsByType(IddObjectType::Schedule_Compact);
  ASSERT_EQ(1u, objects.size());

  boost::regex throughRegex("^Through:\\s*(.*)/\\s*(.*)\\s*");
  boost::regex untilRegex("^Until:\\s*(.*):(.*)\\s*");

  // Write out the schedule - keep this around for now
  //workspace.save(toPath("./ForwardTranslator_ScheduleVariableInterval_Hourly_Shifted.idf"), true);

  // Check the contents of the output
  unsigned N = objects[0].numFields();
  boost::optional<Date> lastDateThrough;
  bool until24Found = false;
  bool nextValueShouldBeLast = false;
  unsigned numUntils = 0;

  int currentHour = 0;
  for ( unsigned i = 0; i < N; ++i){
    boost::optional<std::string> field = objects[0].getString(i, true, false);
    ASSERT_TRUE(field);

    if (nextValueShouldBeLast){
      double value = boost::lexical_cast<double>(*field);
      EXPECT_EQ(8760.0, value);
      nextValueShouldBeLast = false;
    }

    boost::smatch throughMatches;
    if (boost::regex_search(*field, throughMatches, throughRegex)){

      currentHour = 1;

      std::string monthText(throughMatches[1].first, throughMatches[1].second);
      std::string dayText(throughMatches[2].first, throughMatches[2].second);

      int month = boost::lexical_cast<int>(monthText);
      int day = boost::lexical_cast<int>(dayText);

      Date date(MonthOfYear(month), day);
      if (lastDateThrough){
        // check that this date is greater than last date
        EXPECT_TRUE(date > *lastDateThrough) << date << " <= " << *lastDateThrough;

        // DLM: this schedule should not wrap around to 1/1, it should end on 12/31 at 24:00

        // check that last date was closed at 24:00
        EXPECT_TRUE(until24Found);
      }
      lastDateThrough = date;
      until24Found = false;
    }

    boost::smatch untilMatches;
    if (boost::regex_search(*field, untilMatches, untilRegex)){

      numUntils += 1;

      std::string hrText(untilMatches[1].first, untilMatches[1].second);
      std::string minText(untilMatches[2].first, untilMatches[2].second);

      int hr = boost::lexical_cast<int>(hrText);
      int min = boost::lexical_cast<int>(minText);
      EXPECT_EQ(currentHour, hr);
      ++currentHour;
      EXPECT_EQ(0, min);

      if ((hr == 24) && (min == 0)){
        until24Found = true;
      }

      // should NOT see Until: 00:00,
      EXPECT_FALSE((hr==0) && (min==0));

      if ((lastDateThrough == Date(MonthOfYear(12),31)) && until24Found){
        nextValueShouldBeLast = true;
      }
    }
  }
  bool lastUntil24Found = until24Found;

  // check last date was closed
  EXPECT_TRUE(lastUntil24Found);

  // check that there were 8760 untils
  EXPECT_EQ(8760, numUntils);
}