Files
Rbm/source/StackCreator.cpp
T
2022-01-19 16:05:23 +00:00

112 lines
2.5 KiB
C++

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: StackCreator.cpp
* Author: jens
*
* Created on 17. Januar 2022, 18:04
*/
#include "StackCreator.hpp"
#include "DeepStack.hpp"
#include "RnnStack.hpp"
#include <string>
#include <cassert>
using namespace std;
StackCreator::StackCreator()
{
}
StackCreator::~StackCreator()
{
}
AStack* StackCreator::fromJson(Json::Value& project, LayerConstructor *pLayerConstructor)
{
const string &name = project["stack"]["name"].asString();
Json::Value &stack = project["stack"];
Json::Value &layers = project["stack"]["layers"];
int type = stack["type"].asInt();
AStack *pStack = nullptr;
if (type == AStack::StackType::Rnn)
{
pStack = new RnnStack(name);
}
else
{
pStack = new DeepStack(name);
}
for (int i=0; i < layers.size(); i++)
{
Json::Value &layer = layers[i];
string layername = layer["name"].asString();
int numVisibleX = layer["numVisibleX"].asInt();
int numVisibleY = layer["numVisibleY"].asInt();
int numHidden = layer["numHidden"].asInt();
int numContext = layer["numContext"].asInt();
Layer *pLayer = nullptr;
if (!pLayerConstructor)
{
pLayer = new Layer(layername, i, numVisibleX, numVisibleY, numHidden, numContext);
}
else
{
pLayer = pLayerConstructor->onConstruct(pStack, layername, i, numVisibleX, numVisibleY, numHidden, numContext);
}
assert(pLayer != nullptr);
pLayer->fromJson(layer["rbm"]);
pStack->addLayer(pLayer);
}
return pStack;
}
AStack* StackCreator::fromFile(const std::string &dir, const std::string &name, LayerConstructor *pLayerConstructor)
{
std::cout << "Importing Project " << name << std::endl;
ifstream ifs(dir + "/" + name + string(".prj"));
Json::Value project;
ifs >> project;
return fromJson(project, pLayerConstructor);
}
bool StackCreator::toFile(AStack* pStack, const std::string& dir, const std::string& name)
{
std::cout << "Exporting Project " << name << std::endl;
ofstream ofs(dir + "/" + name + string(".prj"));
Json::Value project;
project["stack"]["name"] = name;
project["stack"]["type_string"] = AStack::stackTypeStrings[pStack->type()];
project["stack"]["type"] = pStack->type();
Json::Value layers(Json::arrayValue);
Layer *pLayer = pStack->getLayer(0);
while(pLayer)
{
layers.append(pLayer->toJson());
pLayer = pLayer->next;
}
project["stack"]["layers"] = layers;
ofs << project;
return true;
}