<commit_before>#define _USE_MATH_DEFINES
#include <cmath>
#include "consts.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <sstream>
#include <cstdlib>
#include <set>
#include <math.h>

//TODO: not to use cout inside Element class
#include <iostream>
//

Element::Element()
{
}

Element::Element(string netlistLine,
                 int &numNodes,
                 vector<string> &variablesList):
    polynomial(false)
{
    stringstream sstream(netlistLine);
    char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME];

    vector<double> _params(MAX_PARAMS);
    for (int i=0; i<MAX_PARAMS; i++){
        _params[i] = 0;
    }

    sstream >> name;
    cout << name << " ";
    type = getType();
    sstream.str( string(netlistLine, name.size(), string::npos) );
    if (type=='R') {
        sstream >> na >> nb;
        cout << na << " " << nb << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            if (i>=1 && _params[i]!=0)
                polynomial = true;
        }
        if (!polynomial){
            value = _params[0];
            cout << value << endl;
        }
        else {
            params = _params;
            for (int i = 0; i < MAX_PARAMS; i++){
                cout << params[i] << " ";
            }
            cout << endl;
        }
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
    else if (type == 'I' || type == 'V') {
        polynomial = true; // XXX Ugly (time is running out!)
        sstream >> na >> nb >> signalType;
        cout << na << " " << nb << " " << signalType << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            cout << _params[i] << " ";
        }
        params = _params;
        cout << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
    else if (type=='G' || type=='E' || type=='F' || type=='H') {
        sstream >> na >> nb >> nc >> nd;
        cout << na << " " << nb << " " << nc << " " << nd << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            if (i >= 1 && _params[i] != 0)
                polynomial = true;
        }
        if (!polynomial){
            value = _params[0];
            cout << value << endl;
        }
        else {
            params = _params;
            for (int i = 0; i < MAX_PARAMS; i++){
                cout << params[i] << " ";
            }
            cout << endl;
        }
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
        c = getNodeNumber(nc, numNodes, variablesList);
        d = getNodeNumber(nd, numNodes, variablesList);
    }
    else if (type=='O') {
        sstream >> na >> nb >> nc >> nd;
        cout << na << " " << nb << " " << nc << " " << nd << " " << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
        c = getNodeNumber(nc, numNodes, variablesList);
        d = getNodeNumber(nd, numNodes, variablesList);
    }
    else if (type == 'C' || type == 'L') {
        sstream >> na >> nb >> value;
        cout << na << " " << nb << " " << value << " " << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
}

void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){
    if (type=='V' || type=='E' || type=='F' || type=='O') {
        numVariables++;
        if (numVariables>MAX_NODES) {
            cout << "The extra currents exceeds maximum number of variables allowed (" << MAX_NODES << ")" << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        x=numVariables;
        variablesList[numVariables] = "j" + name;
    }
    else if (type=='H') {
        numVariables=numVariables+2;
        x=numVariables-1;
        y=numVariables;
        variablesList[numVariables-1] = "jy" + name; // XXX It's reversed!
        variablesList[numVariables] = "jx" + name;   // XXX Magic!!!
    }
    else if (type=='L'){
        numVariables++;
        if (numVariables>MAX_NODES) {
            cout << "The extra currents exceeds maximum number of variables allowed (" << MAX_NODES << ")" << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        x = numVariables;
        variablesList[numVariables] = "j" + name;
    }
}

Element::Element(string name,
                 double value,
                 int a,
                 int b,
                 int c,
                 int d,
                 int x,
                 int y):
    name(name),
    value(value),
    a(a),
    b(b),
    c(c),
    d(d),
    x(x),
    y(y),
    signalType("DC"),
    polynomial(false)
{
    type = getType();
}

Element::Element(string name,
                 vector<double> &params,
                 int a,
                 int b,
                 int c,
                 int d):
    name(name),
    params(params),
    a(a),
    b(b),
    c(c),
    d(d),
    polynomial(true)
{
    type = getType();
}

void Element::calcNewtonRaphsonParameters(const double &Xn){
    dFx = params[1];
    FxMinusdFxTimesXn = params[0];
    for (int i = 2; i < MAX_PARAMS; i++){
        dFx += params[i]*(i)*pow(Xn, i-1);
        FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i);
    }
}

double Element::calcSourceValue(double t, double step){
    if (signalType == "DC"){
        if (polynomial)
            value = params[0];
        return value;
    } else if (signalType == "SIN"){
        double offset = params[0];
        double amplitude = params[1];
        double frequency = params[2];
        double delay = params[3];
        double attenuation = params[4];
        double angle = params[5];
        double cycles = params[6];
        double innerTime = t - delay;
        if (innerTime < delay || innerTime - delay > cycles / frequency)
            return offset + amplitude * sin(M_PI * angle / 180);
        return offset + amplitude*exp(innerTime*attenuation)*sin(2 * M_PI*frequency*innerTime - M_PI*angle / 180);
    }
    else if (signalType == "PULSE"){
       //Parameters
        double amp1 = params[0];
        double amp2 = params[1];
        double delay = params[2];
        double riseTime = params[3];
        double fallTime = params[4];
        double onTime = params[5];
        double period = params[6];
        double cycles = params[7];
        // Local variables for Operations
        double CountPeriod = floor(t/period); // Which period is currently analyzing
        double PeriodTime = (t - (period*CountPeriod)); // Time from the beggining of each period
        double time2 = (delay + riseTime);
        double time3 = (delay + riseTime + onTime);
        double time4 = (delay + riseTime + onTime + fallTime);
        // Limiting Cycle Numbers by the End of Period
        while (CountPeriod < cycles) {
            // Phase 1 of Pulse Source
            if (PeriodTime <= delay)
                return amp1;
            // Phase 2 of Pulse Source
            else if ((delay < PeriodTime) && (PeriodTime <= time2))
                return amp1 + ((PeriodTime - delay) / riseTime) * (amp2 - amp1);
            // Phase 3 of Pulse Source
            else if ((time2 < PeriodTime) && (PeriodTime <= time3))
                return amp2;
            // Phase 4 of Pulse Source
            else if ((time3 < PeriodTime) && (PeriodTime <= time4))
                return amp2 - ((PeriodTime - time3) / fallTime)*(amp2 - amp1);
            //Phase 5 of Pulse Source
            else if ((time4 < PeriodTime) && (PeriodTime <= period))
                return amp1;
        }
        // Finishing the last cycle => The amplitude is always == amp1
        return amp1;
    }
}

void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2],
                         const int &numVariables,
                         double (&previousSolution)[MAX_NODES+1],
                         double t,
                         double step,
                         double (&lastStepSolution)[MAX_NODES+1])
{
    if (type=='R') {
        double G;
        if (!polynomial){
            G=1/value;
        } else {
            double Vab = previousSolution[a]-previousSolution[b];
            calcNewtonRaphsonParameters(Vab);
            G = dFx;
            double I0;
            I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][a]+=G;
        Yn[b][b]+=G;
        Yn[a][b]-=G;
        Yn[b][a]-=G;
    }
    else if (type=='G') {
        double G;
        if (!polynomial){
            G=value;
        } else {
            double Vcd = previousSolution[c]-previousSolution[d];
            calcNewtonRaphsonParameters(Vcd);
            G = dFx;
            double I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][c]+=G;
        Yn[b][d]+=G;
        Yn[a][d]-=G;
        Yn[b][c]-=G;
    }
    else if (type=='I') {
        double I=calcSourceValue(t, step);
        Yn[a][numVariables+1]-=I;
        Yn[b][numVariables+1]+=I;
    }
    else if (type=='V') {
        double V=calcSourceValue(t, step);
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][a]-=1;
        Yn[x][b]+=1;
        Yn[x][numVariables+1]-=V;
    }
    else if (type=='E') {
        // Voltage Amplifier
        double A;
        if (!polynomial){
            A=value;
        } else {
            double Vcd = previousSolution[c]-previousSolution[d];
            calcNewtonRaphsonParameters(Vcd);
            A = dFx;
            double V0 = FxMinusdFxTimesXn;
            Yn[x][numVariables+1]-=V0;
        }
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][a]-=1;
        Yn[x][b]+=1;
        Yn[x][c]+=A;
        Yn[x][d]-=A;
    }
    else if (type=='F') {
        // Current Amplifier
        double B;
        if (!polynomial){
            B=value;
        } else {
            double Jcd = previousSolution[x];
            calcNewtonRaphsonParameters(Jcd);
            B=dFx;
            double I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][x]+=B;
        Yn[b][x]-=B;
        Yn[c][x]+=1;
        Yn[d][x]-=1;
        Yn[x][c]-=1;
        Yn[x][d]+=1;
    }
    else if (type=='H') {
        // CCVS: Transresistance
        double Rm;
        if (!polynomial){
            Rm=value;
        } else {
            double Jcd = previousSolution[x];
            calcNewtonRaphsonParameters(Jcd);
            Rm=dFx;
            double V0 = FxMinusdFxTimesXn;
            Yn[y][numVariables+1]-=V0;
        }
        Yn[a][y]+=1;
        Yn[b][y]-=1;
        Yn[c][x]+=1;
        Yn[d][x]-=1;
        Yn[y][a]-=1;
        Yn[y][b]+=1;
        Yn[x][c]-=1;
        Yn[x][d]+=1;
        Yn[y][x]+=Rm;
    }
    else if (type=='O') {
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][c]+=1;
        Yn[x][d]-=1;
    }
    else if (type == 'C') {
        double G;
        if (!t){
            G = TOLG;
        }
        else {
            G = value / step;
            double Vc = lastStepSolution[a] - lastStepSolution[b];
            double I0 = (value / step) * Vc;
            Yn[a][numVariables + 1] += I0;
            Yn[b][numVariables + 1] -= I0;
        }
        Yn[a][a] += G;
        Yn[b][b] += G;
        Yn[a][b] -= G;
        Yn[b][a] -= G;
    }
    else if (type == 'L') {
        if (!t){
            double R = TOLG;
            Yn[a][x] += 1;
            Yn[b][x] -= 1;
            Yn[x][a] -= 1;
            Yn[x][b] += 1;
            Yn[x][x] += R;
        } else {
            double R = value / step;
            double jL = lastStepSolution[x];
            double V0 = (value / step)*jL;
            Yn[a][x] += 1;
            Yn[b][x] -= 1;
            Yn[x][a] -= 1;
            Yn[x][b] += 1;
            Yn[x][x] += R;
            Yn[x][numVariables+1] += V0;
        }
    }
}

int Element::getNodeNumber(const char *name,
                           int &numNodes,
                           vector<string> &variablesList)
{
    int i=0, achou=0;

    while (!achou && i<=numNodes)
        if (!(achou=!variablesList[i].compare(name))) i++;

    if (!achou) {
        if (numNodes==MAX_NODES) {
            cout << "Maximum number of nodes reached: " << MAX_NODES << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        numNodes++;
        variablesList[numNodes] = name;
        return numNodes; /* new node */
    }
    else {
        return i; /* known node */
    }
}

bool Element::isValidElement(const char &netlistLinePrefix){
    // Initializing set with tmpElementPrefixes
    char tmpElementPrefixes[] = {
        'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O', 'L', 'C'
    };
    set<char> elementPrefixes(
        tmpElementPrefixes,
        tmpElementPrefixes +
            sizeof(tmpElementPrefixes) /
            sizeof(tmpElementPrefixes[0])
    );

    // Returns whether or not line prefix corresponds to valid Element
    // verifying if netlistLinePrefix is in elementPrefixes
    return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end();
}

string Element::getName() const
{
    return name;
}

char Element::getType() const
{
    return name[0];
}
<commit_msg>Sets rise/fall/on time to step if they are zero on the netlist<commit_after>#define _USE_MATH_DEFINES
#include <cmath>
#include "consts.h"
#include "circuits/element.h"
#include "matrix/matrix.h"
#include <sstream>
#include <cstdlib>
#include <set>
#include <math.h>

//TODO: not to use cout inside Element class
#include <iostream>
//

Element::Element()
{
}

Element::Element(string netlistLine,
                 int &numNodes,
                 vector<string> &variablesList):
    polynomial(false)
{
    stringstream sstream(netlistLine);
    char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME];

    vector<double> _params(MAX_PARAMS);
    for (int i=0; i<MAX_PARAMS; i++){
        _params[i] = 0;
    }

    sstream >> name;
    cout << name << " ";
    type = getType();
    sstream.str( string(netlistLine, name.size(), string::npos) );
    if (type=='R') {
        sstream >> na >> nb;
        cout << na << " " << nb << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            if (i>=1 && _params[i]!=0)
                polynomial = true;
        }
        if (!polynomial){
            value = _params[0];
            cout << value << endl;
        }
        else {
            params = _params;
            for (int i = 0; i < MAX_PARAMS; i++){
                cout << params[i] << " ";
            }
            cout << endl;
        }
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
    else if (type == 'I' || type == 'V') {
        polynomial = true; // XXX Ugly (time is running out!)
        sstream >> na >> nb >> signalType;
        cout << na << " " << nb << " " << signalType << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            cout << _params[i] << " ";
        }
        params = _params;
        cout << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
    else if (type=='G' || type=='E' || type=='F' || type=='H') {
        sstream >> na >> nb >> nc >> nd;
        cout << na << " " << nb << " " << nc << " " << nd << " ";
        for (int i = 0; i < MAX_PARAMS; i++){
            sstream >> _params[i];
            if (i >= 1 && _params[i] != 0)
                polynomial = true;
        }
        if (!polynomial){
            value = _params[0];
            cout << value << endl;
        }
        else {
            params = _params;
            for (int i = 0; i < MAX_PARAMS; i++){
                cout << params[i] << " ";
            }
            cout << endl;
        }
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
        c = getNodeNumber(nc, numNodes, variablesList);
        d = getNodeNumber(nd, numNodes, variablesList);
    }
    else if (type=='O') {
        sstream >> na >> nb >> nc >> nd;
        cout << na << " " << nb << " " << nc << " " << nd << " " << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
        c = getNodeNumber(nc, numNodes, variablesList);
        d = getNodeNumber(nd, numNodes, variablesList);
    }
    else if (type == 'C' || type == 'L') {
        sstream >> na >> nb >> value;
        cout << na << " " << nb << " " << value << " " << endl;
        a = getNodeNumber(na, numNodes, variablesList);
        b = getNodeNumber(nb, numNodes, variablesList);
    }
}

void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){
    if (type=='V' || type=='E' || type=='F' || type=='O') {
        numVariables++;
        if (numVariables>MAX_NODES) {
            cout << "The extra currents exceeds maximum number of variables allowed (" << MAX_NODES << ")" << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        x=numVariables;
        variablesList[numVariables] = "j" + name;
    }
    else if (type=='H') {
        numVariables=numVariables+2;
        x=numVariables-1;
        y=numVariables;
        variablesList[numVariables-1] = "jy" + name; // XXX It's reversed!
        variablesList[numVariables] = "jx" + name;   // XXX Magic!!!
    }
    else if (type=='L'){
        numVariables++;
        if (numVariables>MAX_NODES) {
            cout << "The extra currents exceeds maximum number of variables allowed (" << MAX_NODES << ")" << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        x = numVariables;
        variablesList[numVariables] = "j" + name;
    }
}

Element::Element(string name,
                 double value,
                 int a,
                 int b,
                 int c,
                 int d,
                 int x,
                 int y):
    name(name),
    value(value),
    a(a),
    b(b),
    c(c),
    d(d),
    x(x),
    y(y),
    signalType("DC"),
    polynomial(false)
{
    type = getType();
}

Element::Element(string name,
                 vector<double> &params,
                 int a,
                 int b,
                 int c,
                 int d):
    name(name),
    params(params),
    a(a),
    b(b),
    c(c),
    d(d),
    polynomial(true)
{
    type = getType();
}

void Element::calcNewtonRaphsonParameters(const double &Xn){
    dFx = params[1];
    FxMinusdFxTimesXn = params[0];
    for (int i = 2; i < MAX_PARAMS; i++){
        dFx += params[i]*(i)*pow(Xn, i-1);
        FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i);
    }
}

double Element::calcSourceValue(double t, double step){
    if (signalType == "DC"){
        if (polynomial)
            value = params[0];
        return value;
    } else if (signalType == "SIN"){
        double offset = params[0];
        double amplitude = params[1];
        double frequency = params[2];
        double delay = params[3];
        double attenuation = params[4];
        double angle = params[5];
        double cycles = params[6];
        double innerTime = t - delay;
        if (innerTime < delay || innerTime - delay > cycles / frequency)
            return offset + amplitude * sin(M_PI * angle / 180);
        return offset + amplitude*exp(innerTime*attenuation)*sin(2 * M_PI*frequency*innerTime - M_PI*angle / 180);
    }
    else if (signalType == "PULSE"){
       //Parameters
        double amp1 = params[0];
        double amp2 = params[1];
        double delay = params[2];
        double riseTime = params[3];
        if (!riseTime)
            riseTime = step;
        double fallTime = params[4];
        if (!fallTime)
            fallTime = step;
        double onTime = params[5];
        if (!onTime)
            onTime = step;
        double period = params[6];
        double cycles = params[7];
        // Local variables for Operations
        double CountPeriod = floor(t/period); // Which period is currently analyzing
        double PeriodTime = (t - (period*CountPeriod)); // Time from the beggining of each period
        double time2 = (delay + riseTime);
        double time3 = (delay + riseTime + onTime);
        double time4 = (delay + riseTime + onTime + fallTime);
        // Limiting Cycle Numbers by the End of Period
        while (CountPeriod < cycles) {
            // Phase 1 of Pulse Source
            if (PeriodTime <= delay)
                return amp1;
            // Phase 2 of Pulse Source
            else if ((delay < PeriodTime) && (PeriodTime <= time2))
                return amp1 + ((PeriodTime - delay) / riseTime) * (amp2 - amp1);
            // Phase 3 of Pulse Source
            else if ((time2 < PeriodTime) && (PeriodTime <= time3))
                return amp2;
            // Phase 4 of Pulse Source
            else if ((time3 < PeriodTime) && (PeriodTime <= time4))
                return amp2 - ((PeriodTime - time3) / fallTime)*(amp2 - amp1);
            //Phase 5 of Pulse Source
            else if ((time4 < PeriodTime) && (PeriodTime <= period))
                return amp1;
        }
        // Finishing the last cycle => The amplitude is always == amp1
        return amp1;
    }
}

void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2],
                         const int &numVariables,
                         double (&previousSolution)[MAX_NODES+1],
                         double t,
                         double step,
                         double (&lastStepSolution)[MAX_NODES+1])
{
    if (type=='R') {
        double G;
        if (!polynomial){
            G=1/value;
        } else {
            double Vab = previousSolution[a]-previousSolution[b];
            calcNewtonRaphsonParameters(Vab);
            G = dFx;
            double I0;
            I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][a]+=G;
        Yn[b][b]+=G;
        Yn[a][b]-=G;
        Yn[b][a]-=G;
    }
    else if (type=='G') {
        double G;
        if (!polynomial){
            G=value;
        } else {
            double Vcd = previousSolution[c]-previousSolution[d];
            calcNewtonRaphsonParameters(Vcd);
            G = dFx;
            double I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][c]+=G;
        Yn[b][d]+=G;
        Yn[a][d]-=G;
        Yn[b][c]-=G;
    }
    else if (type=='I') {
        double I=calcSourceValue(t, step);
        Yn[a][numVariables+1]-=I;
        Yn[b][numVariables+1]+=I;
    }
    else if (type=='V') {
        double V=calcSourceValue(t, step);
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][a]-=1;
        Yn[x][b]+=1;
        Yn[x][numVariables+1]-=V;
    }
    else if (type=='E') {
        // Voltage Amplifier
        double A;
        if (!polynomial){
            A=value;
        } else {
            double Vcd = previousSolution[c]-previousSolution[d];
            calcNewtonRaphsonParameters(Vcd);
            A = dFx;
            double V0 = FxMinusdFxTimesXn;
            Yn[x][numVariables+1]-=V0;
        }
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][a]-=1;
        Yn[x][b]+=1;
        Yn[x][c]+=A;
        Yn[x][d]-=A;
    }
    else if (type=='F') {
        // Current Amplifier
        double B;
        if (!polynomial){
            B=value;
        } else {
            double Jcd = previousSolution[x];
            calcNewtonRaphsonParameters(Jcd);
            B=dFx;
            double I0 = FxMinusdFxTimesXn;
            Yn[a][numVariables+1]-=I0;
            Yn[b][numVariables+1]+=I0;
        }
        Yn[a][x]+=B;
        Yn[b][x]-=B;
        Yn[c][x]+=1;
        Yn[d][x]-=1;
        Yn[x][c]-=1;
        Yn[x][d]+=1;
    }
    else if (type=='H') {
        // CCVS: Transresistance
        double Rm;
        if (!polynomial){
            Rm=value;
        } else {
            double Jcd = previousSolution[x];
            calcNewtonRaphsonParameters(Jcd);
            Rm=dFx;
            double V0 = FxMinusdFxTimesXn;
            Yn[y][numVariables+1]-=V0;
        }
        Yn[a][y]+=1;
        Yn[b][y]-=1;
        Yn[c][x]+=1;
        Yn[d][x]-=1;
        Yn[y][a]-=1;
        Yn[y][b]+=1;
        Yn[x][c]-=1;
        Yn[x][d]+=1;
        Yn[y][x]+=Rm;
    }
    else if (type=='O') {
        Yn[a][x]+=1;
        Yn[b][x]-=1;
        Yn[x][c]+=1;
        Yn[x][d]-=1;
    }
    else if (type == 'C') {
        double G;
        if (!t){
            G = TOLG;
        }
        else {
            G = value / step;
            double Vc = lastStepSolution[a] - lastStepSolution[b];
            double I0 = (value / step) * Vc;
            Yn[a][numVariables + 1] += I0;
            Yn[b][numVariables + 1] -= I0;
        }
        Yn[a][a] += G;
        Yn[b][b] += G;
        Yn[a][b] -= G;
        Yn[b][a] -= G;
    }
    else if (type == 'L') {
        if (!t){
            double R = TOLG;
            Yn[a][x] += 1;
            Yn[b][x] -= 1;
            Yn[x][a] -= 1;
            Yn[x][b] += 1;
            Yn[x][x] += R;
        } else {
            double R = value / step;
            double jL = lastStepSolution[x];
            double V0 = (value / step)*jL;
            Yn[a][x] += 1;
            Yn[b][x] -= 1;
            Yn[x][a] -= 1;
            Yn[x][b] += 1;
            Yn[x][x] += R;
            Yn[x][numVariables+1] += V0;
        }
    }
}

int Element::getNodeNumber(const char *name,
                           int &numNodes,
                           vector<string> &variablesList)
{
    int i=0, achou=0;

    while (!achou && i<=numNodes)
        if (!(achou=!variablesList[i].compare(name))) i++;

    if (!achou) {
        if (numNodes==MAX_NODES) {
            cout << "Maximum number of nodes reached: " << MAX_NODES << endl;
            #if defined (WIN32) || defined(_WIN32)
            cout << endl << "Press any key to exit...";
            cin.get();
            cin.get();
            #endif
            exit(EXIT_FAILURE);
        }
        numNodes++;
        variablesList[numNodes] = name;
        return numNodes; /* new node */
    }
    else {
        return i; /* known node */
    }
}

bool Element::isValidElement(const char &netlistLinePrefix){
    // Initializing set with tmpElementPrefixes
    char tmpElementPrefixes[] = {
        'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O', 'L', 'C'
    };
    set<char> elementPrefixes(
        tmpElementPrefixes,
        tmpElementPrefixes +
            sizeof(tmpElementPrefixes) /
            sizeof(tmpElementPrefixes[0])
    );

    // Returns whether or not line prefix corresponds to valid Element
    // verifying if netlistLinePrefix is in elementPrefixes
    return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end();
}

string Element::getName() const
{
    return name;
}

char Element::getType() const
{
    return name[0];
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yanshiguang02@baidu.com

#include <gflags/gflags.h>

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <unistd.h>

#include "common/timer.h"
#include "sdk/bfs.h"

DECLARE_string(flagfile);
DECLARE_string(nameserver);
DECLARE_string(nameserver_port);

void print_usage() {
    printf("Use:\nbfs_client <commond> path\n");
    printf("\t commond:\n");
    printf("\t    -ls <path> : list the directory\n");
    printf("\t    -cat <path> : cat the file\n");
    printf("\t    -mkdir <path> : make director\n");
    printf("\t    -mv <srcpath> <destpath> : rename director or file\n");
    printf("\t    -touchz <path> : create a new file\n");
    printf("\t    -rm <path> : remove a file\n");
    printf("\t    -get <bfsfile> <localfile> : copy file to local\n");
    printf("\t    -put <localfile> <bfsfile> : copy file from local to bfs\n");
    printf("\t    -append <localfile> <bfsfile> : append localfile to bfsfile\n");
    printf("\t    -rmdir [recursive] <path> : remove directory\n");
}

int BfsMkdir(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    bool ret = fs->CreateDirectory(argv[0]);
    if (!ret) {
        fprintf(stderr, "Create dir %s fail\n", argv[0]);
        return 1;
    }
    return 0;
}

int BfsRename(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 2) {
        print_usage();
        return 1;
    }
    bool ret = fs->Rename(argv[0], argv[1]);
    if (!ret) {
        fprintf(stderr, "Rename %s to %s fail\n", argv[0], argv[1]);
        return 1;
    }
    return 0;
}

int BfsCat(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    for (int i = 0; i < argc; i++) {
        bfs::File* file;
        if (!fs->OpenFile(argv[i], O_RDONLY, &file)) {
            fprintf(stderr, "Can't Open bfs file %s\n", argv[0]);
            return 1;
        }
        char buf[1024];
        int64_t bytes = 0;
        int64_t len = 0;
        while (1) {
            len = file->Read(buf, sizeof(buf));
            if (len <= 0) {
                break;
            }
            bytes += len;
            write(1, buf, len);
        }
        delete file;
    }
    return 0;
}

int BfsGet(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 2) {
        print_usage();
        return 1;
    }
    bfs::File* file;
    if (!fs->OpenFile(argv[0], O_RDONLY, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[0]);
        return 1;
    }

    FILE* fp = fopen(argv[1], "wb");
    if (fp == NULL) {
        fprintf(stderr, "Open local file %s fail\n", argv[1]);
        delete file;
        return -1;
    }
    char buf[1024];
    int64_t bytes = 0;
    int64_t len = 0;
    while (1) {
        len = file->Read(buf, sizeof(buf));
        if (len <= 0) {
            break;
        }
        bytes += len;
        fwrite(buf, len, 1, fp);
    }
    printf("Read %ld bytes from %s\n", bytes, argv[1]);
    delete file;
    return 0;
}

int BfsPut(bfs::FS* fs, int argc, char* argv[]) {
    if (argc != 4) {
        print_usage();
        return 0;
    }
    common::timer::AutoTimer at(0, "BfsPut", argv[3]);
    FILE* fp = fopen(argv[2], "rb");
    if (fp == NULL) {
        fprintf(stderr, "Can't open local file %s\n", argv[2]);
        return 1;
    }

    bfs::File* file;
    if (!fs->OpenFile(argv[3], O_WRONLY, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[3]);
        return 1;
    }
    char buf[1024];
    int64_t len = 0;
    int64_t bytes = 0;
    while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {
        int64_t write_bytes = file->Write(buf, bytes);
        if (write_bytes < bytes) {
            fprintf(stderr, "Write fail: [%s:%ld]\n", argv[3], len);
            return 1;
        }
        len += bytes;
    }
    if (!file->Close()) {
        fprintf(stderr, "close fail: %s\n", argv[3]);
        return 1;
    }
    delete file;
    printf("Put file to bfs %s %ld bytes\n", argv[3], len);
    return 0;
}

int BfsList(bfs::FS* fs, int argc, char* argv[]) {
    std::string path("/");
    if (argc == 3) {
        path = argv[2];
    }
    bfs::BfsFileInfo* files = NULL;
    int num;
    fs->ListDirectory(path.c_str(), &files, &num);
    printf("Found %d itmes\n", num);
    for (int i = 0; i < num; i++) {
        int32_t type = files[i].mode;
        char statbuf[16] = "drwxrwxrwx";
        for (int j = 0; j < 10; j++) {
            if ((type & (1<<(9-j))) == 0) {
                statbuf[j] = '-';
            }
        }
        char timestr[64];
        struct tm stm;
        time_t ctime = files[i].ctime;
        localtime_r(&ctime, &stm);
        snprintf(timestr, sizeof(timestr), "%4d-%02d-%02d %2d:%02d",
            stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min);
        printf("%s\t%s  %s\n", statbuf, timestr, files[i].name);
    }
    delete files;
    return 0;
}

int BfsAppend(bfs::FS* fs, int argc, char* argv[]) {
    if (argc != 4) {
        print_usage();
        return 0;
    }
    common::timer::AutoTimer at(0, "BfsAppend", argv[3]);
    FILE* fp = fopen(argv[2], "rb");
    if (fp == NULL) {
        fprintf(stderr, "Can't open local file %s\n", argv[2]);
        return 1;
    }

    bfs::File* file;
    if (!fs->OpenFile(argv[3], O_APPEND, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[3]);
        return 1;
    }
    char buf[1024];
    int64_t len = 0;
    int64_t bytes = 0;
    while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {
        int64_t write_bytes = file->Write(buf, bytes);
        if (write_bytes < bytes) {
            fprintf(stderr, "Append fail: [%s:%ld]\n", argv[3], len);
            return 1;
        }
        len += bytes;
    }
    if (!fs->CloseFile(file)) {
        fprintf(stderr, "close fail: %s\n", argv[3]);
        return 1;
    }
    delete file;
    printf("Append to bfs %s %ld bytes\n", argv[3], len);
    return 0;
}

int BfsRmdir(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    bool recursive = false;;
    if (argc == 2 && strcmp(argv[0], "recursive") == 0) {
        recursive = true;
    }
    char* path = recursive ? argv[1] : argv[0];
    bool ret = fs->DeleteDirectory(path, recursive);
    if (!ret) {
        fprintf(stderr, "Remove dir %s fail\n", argv[0]);
        return 1;
    }
    return 0;
}

/// bfs client main
int main(int argc, char* argv[]) {
    FLAGS_flagfile = "./bfs.flag";
    ::google::ParseCommandLineFlags(&argc, &argv, false);

    if (argc < 2) {
        print_usage();
        return 0;
    }

    bfs::FS* fs;
    std::string ns_address = FLAGS_nameserver + ":" + FLAGS_nameserver_port;
    if (!bfs::FS::OpenFileSystem(ns_address.c_str(), &fs)) {
        fprintf(stderr, "Open filesytem %s fail\n", ns_address.c_str());
        return 1;
    }

    int ret = 1;
    if (strcmp(argv[1], "touchz") == 0) {
        if (argc != 3) {
            print_usage();
            return ret;
        }
        bfs::File* file;
        if (!fs->OpenFile(argv[2], O_WRONLY, &file)) {
            fprintf(stderr, "Open %s fail\n", argv[2]);
        }
    } else if (strcmp(argv[1], "rm") == 0) {
        if (argc != 3) {
            print_usage();
            return ret;
        }
        if (fs->DeleteFile(argv[2])) {
            printf("%s Removed\n", argv[2]);
        } else {
            fprintf(stderr, "Remove file fail: %s\n", argv[2]);
        }
    } else if (strcmp(argv[1], "mkdir") == 0) {
        ret = BfsMkdir(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "mv") == 0) {
        ret = BfsRename(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "put") == 0) {
        ret = BfsPut(fs, argc, argv);
    } else if (strcmp(argv[1], "get") == 0 ) {
        ret = BfsGet(fs, argc-2, argv+2);
    } else if (strcmp(argv[1], "cat") == 0) {
        ret = BfsCat(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "ls") == 0) {
        ret = BfsList(fs, argc, argv);
    } else if (strcmp(argv[1], "append") == 0) {
        ret = BfsAppend(fs, argc, argv);
    } else if (strcmp(argv[1], "rmdir") == 0) {
        ret = BfsRmdir(fs, argc - 2, argv + 2);
    } else {
        fprintf(stderr, "Unknow common: %s\n", argv[1]);
    }
    return ret;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<commit_msg>Small fix<commit_after>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yanshiguang02@baidu.com

#include <gflags/gflags.h>

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <unistd.h>

#include "common/timer.h"
#include "sdk/bfs.h"

DECLARE_string(flagfile);
DECLARE_string(nameserver);
DECLARE_string(nameserver_port);

void print_usage() {
    printf("Use:\nbfs_client <commond> path\n");
    printf("\t commond:\n");
    printf("\t    -ls <path> : list the directory\n");
    printf("\t    -cat <path> : cat the file\n");
    printf("\t    -mkdir <path> : make director\n");
    printf("\t    -mv <srcpath> <destpath> : rename director or file\n");
    printf("\t    -touchz <path> : create a new file\n");
    printf("\t    -rm <path> : remove a file\n");
    printf("\t    -get <bfsfile> <localfile> : copy file to local\n");
    printf("\t    -put <localfile> <bfsfile> : copy file from local to bfs\n");
    printf("\t    -append <localfile> <bfsfile> : append localfile to bfsfile\n");
    printf("\t    -rmdir [recursive] <path> : remove directory\n");
}

int BfsMkdir(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    bool ret = fs->CreateDirectory(argv[0]);
    if (!ret) {
        fprintf(stderr, "Create dir %s fail\n", argv[0]);
        return 1;
    }
    return 0;
}

int BfsRename(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 2) {
        print_usage();
        return 1;
    }
    bool ret = fs->Rename(argv[0], argv[1]);
    if (!ret) {
        fprintf(stderr, "Rename %s to %s fail\n", argv[0], argv[1]);
        return 1;
    }
    return 0;
}

int BfsCat(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    for (int i = 0; i < argc; i++) {
        bfs::File* file;
        if (!fs->OpenFile(argv[i], O_RDONLY, &file)) {
            fprintf(stderr, "Can't Open bfs file %s\n", argv[0]);
            return 1;
        }
        char buf[1024];
        int64_t bytes = 0;
        int64_t len = 0;
        while (1) {
            len = file->Read(buf, sizeof(buf));
            if (len <= 0) {
                break;
            }
            bytes += len;
            write(1, buf, len);
        }
        delete file;
    }
    return 0;
}

int BfsGet(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 2) {
        print_usage();
        return 1;
    }
    bfs::File* file;
    if (!fs->OpenFile(argv[0], O_RDONLY, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[0]);
        return 1;
    }

    FILE* fp = fopen(argv[1], "wb");
    if (fp == NULL) {
        fprintf(stderr, "Open local file %s fail\n", argv[1]);
        delete file;
        return -1;
    }
    char buf[1024];
    int64_t bytes = 0;
    int64_t len = 0;
    while (1) {
        len = file->Read(buf, sizeof(buf));
        if (len <= 0) {
            break;
        }
        bytes += len;
        fwrite(buf, len, 1, fp);
    }
    printf("Read %ld bytes from %s\n", bytes, argv[1]);
    delete file;
    return 0;
}

int BfsPut(bfs::FS* fs, int argc, char* argv[]) {
    if (argc != 4) {
        print_usage();
        return 0;
    }
    common::timer::AutoTimer at(0, "BfsPut", argv[3]);
    FILE* fp = fopen(argv[2], "rb");
    if (fp == NULL) {
        fprintf(stderr, "Can't open local file %s\n", argv[2]);
        return 1;
    }

    bfs::File* file;
    if (!fs->OpenFile(argv[3], O_WRONLY, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[3]);
        return 1;
    }
    char buf[1024];
    int64_t len = 0;
    int64_t bytes = 0;
    while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {
        int64_t write_bytes = file->Write(buf, bytes);
        if (write_bytes < bytes) {
            fprintf(stderr, "Write fail: [%s:%ld]\n", argv[3], len);
            return 1;
        }
        len += bytes;
    }
    if (!file->Close()) {
        fprintf(stderr, "close fail: %s\n", argv[3]);
        return 1;
    }
    delete file;
    printf("Put file to bfs %s %ld bytes\n", argv[3], len);
    return 0;
}

int BfsList(bfs::FS* fs, int argc, char* argv[]) {
    std::string path("/");
    if (argc == 3) {
        path = argv[2];
    }
    bfs::BfsFileInfo* files = NULL;
    int num;
    fs->ListDirectory(path.c_str(), &files, &num);
    printf("Found %d itmes\n", num);
    for (int i = 0; i < num; i++) {
        int32_t type = files[i].mode;
        char statbuf[16] = "drwxrwxrwx";
        for (int j = 0; j < 10; j++) {
            if ((type & (1<<(9-j))) == 0) {
                statbuf[j] = '-';
            }
        }
        char timestr[64];
        struct tm stm;
        time_t ctime = files[i].ctime;
        localtime_r(&ctime, &stm);
        snprintf(timestr, sizeof(timestr), "%4d-%02d-%02d %2d:%02d",
            stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday, stm.tm_hour, stm.tm_min);
        printf("%s\t%s  %s\n", statbuf, timestr, files[i].name);
    }
    delete files;
    return 0;
}

int BfsAppend(bfs::FS* fs, int argc, char* argv[]) {
    if (argc != 4) {
        print_usage();
        return 0;
    }
    common::timer::AutoTimer at(0, "BfsAppend", argv[3]);
    FILE* fp = fopen(argv[2], "rb");
    if (fp == NULL) {
        fprintf(stderr, "Can't open local file %s\n", argv[2]);
        return 1;
    }

    bfs::File* file;
    if (!fs->OpenFile(argv[3], O_APPEND, &file)) {
        fprintf(stderr, "Can't Open bfs file %s\n", argv[3]);
        return 1;
    }
    char buf[1024];
    int64_t len = 0;
    int64_t bytes = 0;
    while ( (bytes = fread(buf, 1, sizeof(buf), fp)) > 0) {
        int64_t write_bytes = file->Write(buf, bytes);
        if (write_bytes < bytes) {
            fprintf(stderr, "Append fail: [%s:%ld]\n", argv[3], len);
            return 1;
        }
        len += bytes;
    }
    if (!fs->CloseFile(file)) {
        fprintf(stderr, "close fail: %s\n", argv[3]);
        return 1;
    }
    delete file;
    printf("Append to bfs %s %ld bytes\n", argv[3], len);
    return 0;
}

int BfsRmdir(bfs::FS* fs, int argc, char* argv[]) {
    if (argc < 1) {
        print_usage();
        return 1;
    }
    bool recursive = false;;
    if (argc == 2 && strcmp(argv[0], "recursive") == 0) {
        recursive = true;
    }
    char* path = recursive ? argv[1] : argv[0];
    bool ret = fs->DeleteDirectory(path, recursive);
    if (!ret) {
        fprintf(stderr, "Remove dir %s fail\n", path);
        return 1;
    }
    return 0;
}

/// bfs client main
int main(int argc, char* argv[]) {
    FLAGS_flagfile = "./bfs.flag";
    ::google::ParseCommandLineFlags(&argc, &argv, false);

    if (argc < 2) {
        print_usage();
        return 0;
    }

    bfs::FS* fs;
    std::string ns_address = FLAGS_nameserver + ":" + FLAGS_nameserver_port;
    if (!bfs::FS::OpenFileSystem(ns_address.c_str(), &fs)) {
        fprintf(stderr, "Open filesytem %s fail\n", ns_address.c_str());
        return 1;
    }

    int ret = 1;
    if (strcmp(argv[1], "touchz") == 0) {
        if (argc != 3) {
            print_usage();
            return ret;
        }
        bfs::File* file;
        if (!fs->OpenFile(argv[2], O_WRONLY, &file)) {
            fprintf(stderr, "Open %s fail\n", argv[2]);
        }
    } else if (strcmp(argv[1], "rm") == 0) {
        if (argc != 3) {
            print_usage();
            return ret;
        }
        if (fs->DeleteFile(argv[2])) {
            printf("%s Removed\n", argv[2]);
        } else {
            fprintf(stderr, "Remove file fail: %s\n", argv[2]);
        }
    } else if (strcmp(argv[1], "mkdir") == 0) {
        ret = BfsMkdir(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "mv") == 0) {
        ret = BfsRename(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "put") == 0) {
        ret = BfsPut(fs, argc, argv);
    } else if (strcmp(argv[1], "get") == 0 ) {
        ret = BfsGet(fs, argc-2, argv+2);
    } else if (strcmp(argv[1], "cat") == 0) {
        ret = BfsCat(fs, argc - 2, argv + 2);
    } else if (strcmp(argv[1], "ls") == 0) {
        ret = BfsList(fs, argc, argv);
    } else if (strcmp(argv[1], "append") == 0) {
        ret = BfsAppend(fs, argc, argv);
    } else if (strcmp(argv[1], "rmdir") == 0) {
        ret = BfsRmdir(fs, argc - 2, argv + 2);
    } else {
        fprintf(stderr, "Unknow common: %s\n", argv[1]);
    }
    return ret;
}

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<|endoftext|>


<commit_before>#include "base/flags.hpp"

#include "gtest/gtest.h"

namespace principia {
namespace base {

TEST(FlagsTest, Basics) {
  Flags::Set("zfp=yes,hex,gipfeli=");
  EXPECT_TRUE(Flags::IsPresent("zfp"));
  EXPECT_TRUE(Flags::IsPresent("hex"));
  EXPECT_TRUE(Flags::IsPresent("gipfeli"));
  EXPECT_FALSE(Flags::IsPresent("decimal"));
  EXPECT_EQ("yes", Flags::Value("zfp"));
  EXPECT_EQ("", Flags::Value("hex"));
  EXPECT_EQ("", Flags::Value("gipfeli"));
}

TEST(FlagsTest, Space) {
  Flags::Set("zfp=yes , hex");
  EXPECT_TRUE(Flags::IsPresent("zfp"));
  EXPECT_TRUE(Flags::IsPresent(" hex"));
  EXPECT_EQ("yes", Flags::Value("zfp"));
  EXPECT_EQ("", Flags::Value(" hex"));
}

}  // namespace base
}  // namespace principia
<commit_msg>Test the flags.<commit_after>#include "base/flags.hpp"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace principia {
namespace base {

using ::testing::ElementsAre;
using ::testing::IsEmpty;

TEST(FlagsTest, Basics) {
  Flags::Set("zfp", "yes");
  Flags::Set("hex", "");
  Flags::Set("gipfeli", "on");
  Flags::Set("gipfeli", "off");
  EXPECT_TRUE(Flags::IsPresent("zfp"));
  EXPECT_TRUE(Flags::IsPresent("hex"));
  EXPECT_TRUE(Flags::IsPresent("gipfeli"));
  EXPECT_FALSE(Flags::IsPresent("decimal"));
  EXPECT_TRUE(Flags::IsPresent("zfp", "yes"));
  EXPECT_TRUE(Flags::IsPresent("hex", ""));
  EXPECT_TRUE(Flags::IsPresent("gipfeli", "on"));
  EXPECT_TRUE(Flags::IsPresent("gipfeli", "off"));
  EXPECT_FALSE(Flags::IsPresent("gipfeli", "n/a"));
  EXPECT_FALSE(Flags::IsPresent("decimal", "0"));
  EXPECT_THAT(Flags::Values("zfp"), ElementsAre("yes"));
  EXPECT_THAT(Flags::Values("hex"), ElementsAre(""));
  EXPECT_THAT(Flags::Values("gipfeli"), ElementsAre("off", "on"));
  EXPECT_THAT(Flags::Values("decimal"), IsEmpty());
}

}  // namespace base
}  // namespace principia
<|endoftext|>


<commit_before>/*
 * HyPerCol.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: Craig Rasmussen
 */

#undef TIMER_ON
#undef TIMESTEP_OUTPUT

#include "HyPerCol.hpp"
#include "InterColComm.hpp"
#include "../connections/PVConnection.h"
#include "../io/clock.h"
#include "../io/imageio.hpp"
#include "../io/io.h"
#include "../utils/pv_random.h"

#include <assert.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>

namespace PV {

HyPerCol::HyPerCol(const char * name, int argc, char * argv[])
         : warmStart(false), isInitialized(false)
{
   // TODO - fix these numbers to dynamically grow
   maxLayers = MAX_LAYERS;
   maxConnections = MAX_CONNECTIONS;

   this->name = strdup(name);

   char * param_file;
   simTime = 0;
   numLayers = 0;
   numConnections = 0;
   layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));
   connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));

#ifdef MULTITHREADED
   numThreads = 1;
#else
   numThreads = 0;
#endif

   numSteps = 2;
   image_file = NULL;
   param_file = NULL;
   parse_options(argc, argv, &image_file, &param_file, &numSteps, &numThreads);

   // estimate for now
   // TODO -get rid of maxGroups
   int maxGroups = 2*(maxLayers + maxConnections);
   params = new PVParams(param_file, maxGroups);

   icComm = new InterColComm(&argc, &argv);

   // initialize random seed
   //
   pv_srandom(getRandomSeed());

   if (param_file != NULL) free(param_file);

   deltaTime = DELTA_T;
   if (params->present(name, "dt")) deltaTime = params->value(name, "dt");

   int status = -1;
   if (image_file) {
      status = getImageInfo(image_file, icComm, &imageLoc);
   }

   if (status) {
      imageLoc.nxGlobal = (int) params->value(name, "nx");
      imageLoc.nyGlobal = (int) params->value(name, "ny");

      // set loc based on global parameters and processor partitioning
      //
      setLayerLoc(&imageLoc, 1.0f, 1.0f, 0, 1);
   }

   runDelegate = NULL;
}

HyPerCol::~HyPerCol()
{
   int n;

#ifdef MULTITHREADED
   finalizeThreads();
#endif

   if (image_file != NULL) free(image_file);

   for (n = 0; n < numConnections; n++) {
      delete connections[n];
   }

   free(threadCLayers);

   for (n = 0; n < numLayers; n++) {
      // TODO: check to see if finalize called
      if (layers[n] != NULL) {
         delete layers[n]; // will call *_finalize
      }
      else {
         // TODO move finalize
         // PVLayer_finalize(getCLayer(n));
      }
   }

   delete icComm;

   free(connections);
   free(layers);
   free(name);
}

int HyPerCol::initFinish(void)
{
   int status = 0;

   for (int i = 0; i < this->numLayers; i++) {
      status = layers[i]->initFinish();
      if (status != 0) {
         fprintf(stderr, "[%d]: HyPerCol::initFinish: ERROR condition, exiting...\n", this->columnId());
         exit(status);
      }
   }

   log_parameters(numSteps, image_file);

#ifdef MULTITHREADED
   initializeThreads();
#endif

   isInitialized = true;

   return status;
}

int HyPerCol::columnId()
{
   return icComm->commRank();
}

int HyPerCol::numberOfColumns()
{
   return icComm->numCommRows() * icComm->numCommColumns();
}

int HyPerCol::commColumn(int colId)
{
   return colId % icComm->numCommColumns();
}

int HyPerCol::commRow(int colId)
{
   return colId / icComm->numCommColumns();
}

int HyPerCol::setLayerLoc(PVLayerLoc * layerLoc,
                          float nxScale, float nyScale, int margin, int nf)
{
   layerLoc->nxGlobal = (int) (nxScale * imageLoc.nxGlobal);
   layerLoc->nyGlobal = (int) (nyScale * imageLoc.nyGlobal);

   // partition input space based on the number of processor
   // columns and rows
   //

   layerLoc->nx = layerLoc->nxGlobal / icComm->numCommColumns();
   layerLoc->ny = layerLoc->nyGlobal / icComm->numCommRows();

   assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());
   assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());

   layerLoc->kx0 = layerLoc->nx * icComm->commColumn();
   layerLoc->ky0 = layerLoc->ny * icComm->commRow();

   layerLoc->nPad = margin;
   layerLoc->nBands = nf;

   return 0;
}

int HyPerCol::addLayer(HyPerLayer * l)
{
   assert(numLayers < maxLayers);
   l->columnWillAddLayer(icComm, numLayers);
   layers[numLayers++] = l;
   return (numLayers - 1);
}

int HyPerCol::addConnection(HyPerConn * conn)
{
   int connId = numConnections;

   assert(numConnections < maxConnections);

   // numConnections is the ID of this connection
   icComm->subscribe(conn);

   connections[numConnections++] = conn;

   return connId;
}

int HyPerCol::run(int nTimeSteps)
{
   int step = 0;
   float stopTime = simTime + nTimeSteps * deltaTime;
   const bool exitOnFinish = false;

   if (!isInitialized) {
      initFinish();
   }

   numSteps = nTimeSteps;

#ifdef DEBUG_OUTPUT
   if (columnId() == 0) {
      printf("[0]: HyPerCol: running...\n");  fflush(stdout);
   }
#endif

   // publish initial conditions
   //
   for (int l = 0; l < numLayers; l++) {
      layers[l]->publish(icComm, simTime);
   }

   // wait for all published data to arrive
   //
   for (int l = 0; l < numLayers; l++) {
      icComm->wait(layers[l]->getLayerId());
   }

   if (runDelegate) {
      // let delegate advance the time
      //
      runDelegate->run(simTime, stopTime);
   }

   // time loop
   //
   while (simTime < stopTime) {
      simTime = advanceTime(simTime);
      step += 1;

#ifdef TIMER_ON
      if (step == 10) start_clock();
#endif

   }  // end time loop

#ifdef DEBUG_OUTPUT
   if (columnId() == 0) {
      printf("[0]: HyPerCol::run done...\n");  fflush(stdout);
   }
#endif

   exitRunLoop(exitOnFinish);

#ifdef TIMER_ON
      stop_clock();
#endif

   return 0;
}

float HyPerCol::advanceTime(float sim_time)
{
#ifdef TIMESTEP_OUTPUT
   int nstep = (int) (simTime/getDeltaTime());
   if (nstep%2000 == 0 && columnId() == 0) {
      printf("   [%d]: time==%f\n", columnId(), simTime);
   }
#endif

   // At this point all activity from the previous time step have
   // been delivered to the data store.
   //

   // update the connections (weights)
   //
   for (int c = 0; c < numConnections; c++) {
      connections[c]->updateState(sim_time, deltaTime);
      connections[c]->outputState(sim_time);
   }

   // Update the layers (activity)
   //
   for (int l = 0; l < numLayers; l++) {
      layers[l]->outputState(sim_time);

      // deliver new synaptic activity to layer
      //
      icComm->deliver(this, layers[l]->getLayerId());

      // update layer and calculate new activity
      //
      layers[l]->updateState(sim_time, deltaTime);

      // TODO - move this to layer
      // Advance time level so we have a new place in data store
      // to copy the data.  This should be done immediately after before
      // publish so there is a place to publish and deliver the data to
      // but no one can access the data store (except to publish) until
      // wait has been called.  This should be fixed so that publish goes
      // to last time level and level is advanced only after wait.
      icComm->increaseTimeLevel(layers[l]->getLayerId());

      layers[l]->publish(icComm, sim_time);
   }

   // wait for all published data to arrive
   //
   for (int l = 0; l < numLayers; l++) {
      icComm->wait(layers[l]->getLayerId());
   }

   return sim_time + deltaTime;
}

int HyPerCol::exitRunLoop(bool exitOnFinish)
{
   int status = 0;

   // output final state of layers and connections
   //
   bool last = true;

   for (int l = 0; l < numLayers; l++) {
      layers[l]->writeState(layers[l]->getName(), simTime, last);
   }

   for (int c = 0; c < numConnections; c++) {
      connections[c]->outputState(simTime, last);
   }

   if (exitOnFinish) {
      delete this;
      exit(0);
   }

   return status;
}

int HyPerCol::initializeThreads()
{
   int err = 0;
#ifdef IBM_CELL_BE
   err = pv_cell_thread_init(columnId(), numThreads);
#endif
   return err;
}

int HyPerCol::finalizeThreads()
{
   int err = 0;
#ifdef IBM_CELL_BE
   err = pv_cell_thread_finalize(columnId(), numThreads);
#endif
   return err;
}

int HyPerCol::loadState()
{
   return 0;
}

int HyPerCol::writeState()
{
   for (int l = 0; l < numLayers; l++) {
      layers[l]->writeState(OUTPUT_PATH, simTime);
   }
   return 0;
}

} // PV namespace
<commit_msg>Fixed sim_time variable in TIMESTEP_OUTPUT block.<commit_after>/*
 * HyPerCol.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: Craig Rasmussen
 */

#undef TIMER_ON
#undef TIMESTEP_OUTPUT

#include "HyPerCol.hpp"
#include "InterColComm.hpp"
#include "../connections/PVConnection.h"
#include "../io/clock.h"
#include "../io/imageio.hpp"
#include "../io/io.h"
#include "../utils/pv_random.h"

#include <assert.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>

namespace PV {

HyPerCol::HyPerCol(const char * name, int argc, char * argv[])
         : warmStart(false), isInitialized(false)
{
   // TODO - fix these numbers to dynamically grow
   maxLayers = MAX_LAYERS;
   maxConnections = MAX_CONNECTIONS;

   this->name = strdup(name);

   char * param_file;
   simTime = 0;
   numLayers = 0;
   numConnections = 0;
   layers = (HyPerLayer **) malloc(maxLayers * sizeof(HyPerLayer *));
   connections = (HyPerConn **) malloc(maxConnections * sizeof(HyPerConn *));

#ifdef MULTITHREADED
   numThreads = 1;
#else
   numThreads = 0;
#endif

   numSteps = 2;
   image_file = NULL;
   param_file = NULL;
   parse_options(argc, argv, &image_file, &param_file, &numSteps, &numThreads);

   // estimate for now
   // TODO -get rid of maxGroups
   int maxGroups = 2*(maxLayers + maxConnections);
   params = new PVParams(param_file, maxGroups);

   icComm = new InterColComm(&argc, &argv);

   // initialize random seed
   //
   pv_srandom(getRandomSeed());

   if (param_file != NULL) free(param_file);

   deltaTime = DELTA_T;
   if (params->present(name, "dt")) deltaTime = params->value(name, "dt");

   int status = -1;
   if (image_file) {
      status = getImageInfo(image_file, icComm, &imageLoc);
   }

   if (status) {
      imageLoc.nxGlobal = (int) params->value(name, "nx");
      imageLoc.nyGlobal = (int) params->value(name, "ny");

      // set loc based on global parameters and processor partitioning
      //
      setLayerLoc(&imageLoc, 1.0f, 1.0f, 0, 1);
   }

   runDelegate = NULL;
}

HyPerCol::~HyPerCol()
{
   int n;

#ifdef MULTITHREADED
   finalizeThreads();
#endif

   if (image_file != NULL) free(image_file);

   for (n = 0; n < numConnections; n++) {
      delete connections[n];
   }

   free(threadCLayers);

   for (n = 0; n < numLayers; n++) {
      // TODO: check to see if finalize called
      if (layers[n] != NULL) {
         delete layers[n]; // will call *_finalize
      }
      else {
         // TODO move finalize
         // PVLayer_finalize(getCLayer(n));
      }
   }

   delete icComm;

   free(connections);
   free(layers);
   free(name);
}

int HyPerCol::initFinish(void)
{
   int status = 0;

   for (int i = 0; i < this->numLayers; i++) {
      status = layers[i]->initFinish();
      if (status != 0) {
         fprintf(stderr, "[%d]: HyPerCol::initFinish: ERROR condition, exiting...\n", this->columnId());
         exit(status);
      }
   }

   log_parameters(numSteps, image_file);

#ifdef MULTITHREADED
   initializeThreads();
#endif

   isInitialized = true;

   return status;
}

int HyPerCol::columnId()
{
   return icComm->commRank();
}

int HyPerCol::numberOfColumns()
{
   return icComm->numCommRows() * icComm->numCommColumns();
}

int HyPerCol::commColumn(int colId)
{
   return colId % icComm->numCommColumns();
}

int HyPerCol::commRow(int colId)
{
   return colId / icComm->numCommColumns();
}

int HyPerCol::setLayerLoc(PVLayerLoc * layerLoc,
                          float nxScale, float nyScale, int margin, int nf)
{
   layerLoc->nxGlobal = (int) (nxScale * imageLoc.nxGlobal);
   layerLoc->nyGlobal = (int) (nyScale * imageLoc.nyGlobal);

   // partition input space based on the number of processor
   // columns and rows
   //

   layerLoc->nx = layerLoc->nxGlobal / icComm->numCommColumns();
   layerLoc->ny = layerLoc->nyGlobal / icComm->numCommRows();

   assert(layerLoc->nxGlobal == layerLoc->nx * icComm->numCommColumns());
   assert(layerLoc->nyGlobal == layerLoc->ny * icComm->numCommRows());

   layerLoc->kx0 = layerLoc->nx * icComm->commColumn();
   layerLoc->ky0 = layerLoc->ny * icComm->commRow();

   layerLoc->nPad = margin;
   layerLoc->nBands = nf;

   return 0;
}

int HyPerCol::addLayer(HyPerLayer * l)
{
   assert(numLayers < maxLayers);
   l->columnWillAddLayer(icComm, numLayers);
   layers[numLayers++] = l;
   return (numLayers - 1);
}

int HyPerCol::addConnection(HyPerConn * conn)
{
   int connId = numConnections;

   assert(numConnections < maxConnections);

   // numConnections is the ID of this connection
   icComm->subscribe(conn);

   connections[numConnections++] = conn;

   return connId;
}

int HyPerCol::run(int nTimeSteps)
{
   int step = 0;
   float stopTime = simTime + nTimeSteps * deltaTime;
   const bool exitOnFinish = false;

   if (!isInitialized) {
      initFinish();
   }

   numSteps = nTimeSteps;

#ifdef DEBUG_OUTPUT
   if (columnId() == 0) {
      printf("[0]: HyPerCol: running...\n");  fflush(stdout);
   }
#endif

   // publish initial conditions
   //
   for (int l = 0; l < numLayers; l++) {
      layers[l]->publish(icComm, simTime);
   }

   // wait for all published data to arrive
   //
   for (int l = 0; l < numLayers; l++) {
      icComm->wait(layers[l]->getLayerId());
   }

   if (runDelegate) {
      // let delegate advance the time
      //
      runDelegate->run(simTime, stopTime);
   }

   // time loop
   //
   while (simTime < stopTime) {
      simTime = advanceTime(simTime);
      step += 1;

#ifdef TIMER_ON
      if (step == 10) start_clock();
#endif

   }  // end time loop

#ifdef DEBUG_OUTPUT
   if (columnId() == 0) {
      printf("[0]: HyPerCol::run done...\n");  fflush(stdout);
   }
#endif

   exitRunLoop(exitOnFinish);

#ifdef TIMER_ON
      stop_clock();
#endif

   return 0;
}

float HyPerCol::advanceTime(float sim_time)
{
#ifdef TIMESTEP_OUTPUT
   int nstep = (int) (sim_time/getDeltaTime());
   if (nstep%2000 == 0 && columnId() == 0) {
      printf("   [%d]: time==%f\n", columnId(), sim_time);
   }
#endif

   // At this point all activity from the previous time step have
   // been delivered to the data store.
   //

   // update the connections (weights)
   //
   for (int c = 0; c < numConnections; c++) {
      connections[c]->updateState(sim_time, deltaTime);
      connections[c]->outputState(sim_time);
   }

   // Update the layers (activity)
   //
   for (int l = 0; l < numLayers; l++) {
      layers[l]->outputState(sim_time);

      // deliver new synaptic activity to layer
      //
      icComm->deliver(this, layers[l]->getLayerId());

      // update layer and calculate new activity
      //
      layers[l]->updateState(sim_time, deltaTime);

      // TODO - move this to layer
      // Advance time level so we have a new place in data store
      // to copy the data.  This should be done immediately after before
      // publish so there is a place to publish and deliver the data to
      // but no one can access the data store (except to publish) until
      // wait has been called.  This should be fixed so that publish goes
      // to last time level and level is advanced only after wait.
      icComm->increaseTimeLevel(layers[l]->getLayerId());

      layers[l]->publish(icComm, sim_time);
   }

   // wait for all published data to arrive
   //
   for (int l = 0; l < numLayers; l++) {
      icComm->wait(layers[l]->getLayerId());
   }

   return sim_time + deltaTime;
}

int HyPerCol::exitRunLoop(bool exitOnFinish)
{
   int status = 0;

   // output final state of layers and connections
   //
   bool last = true;

   for (int l = 0; l < numLayers; l++) {
      layers[l]->writeState(layers[l]->getName(), simTime, last);
   }

   for (int c = 0; c < numConnections; c++) {
      connections[c]->outputState(simTime, last);
   }

   if (exitOnFinish) {
      delete this;
      exit(0);
   }

   return status;
}

int HyPerCol::initializeThreads()
{
   int err = 0;
#ifdef IBM_CELL_BE
   err = pv_cell_thread_init(columnId(), numThreads);
#endif
   return err;
}

int HyPerCol::finalizeThreads()
{
   int err = 0;
#ifdef IBM_CELL_BE
   err = pv_cell_thread_finalize(columnId(), numThreads);
#endif
   return err;
}

int HyPerCol::loadState()
{
   return 0;
}

int HyPerCol::writeState()
{
   for (int l = 0; l < numLayers; l++) {
      layers[l]->writeState(OUTPUT_PATH, simTime);
   }
   return 0;
}

} // PV namespace
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <stdlib.h>
#include <Context.h>
#include <i18n.h>
#include <text.h>
#include <CmdExec.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdExec::CmdExec ()
{
  _keyword     = "execute";
  _usage       = "task          execute <external command>";
  _description = STRING_CMD_EXEC_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdExec::execute (std::string& output)
{
  std::string command_line;
  join (command_line, " ", context.parser.getWords ());
  return system (command_line.c_str ());
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CLI<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <stdlib.h>
#include <Context.h>
#include <i18n.h>
#include <text.h>
#include <CmdExec.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdExec::CmdExec ()
{
  _keyword     = "execute";
  _usage       = "task          execute <external command>";
  _description = STRING_CMD_EXEC_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdExec::execute (std::string& output)
{
  std::string command_line;
  join (command_line, " ", context.cli.getWords ());
  return system (command_line.c_str ());
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/trace_event.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/time.h"

#define USE_UNRELIABLE_NOW

namespace base {

static const char* kEventTypeNames[] = {
  "BEGIN",
  "END",
  "INSTANT"
};

static const FilePath::CharType* kLogFileName =
    FILE_PATH_LITERAL("trace_%d.log");

TraceLog::TraceLog() : enabled_(false), log_file_(NULL) {
  base::ProcessHandle proc = base::GetCurrentProcessHandle();
  process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc));
}

TraceLog::~TraceLog() {
  Stop();
}

// static
bool TraceLog::IsTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->enabled_;
}

// static
bool TraceLog::StartTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->Start();
}

bool TraceLog::Start() {
  if (enabled_)
    return true;
  enabled_ = OpenLogFile();
  if (enabled_) {
    Log("var raw_trace_events = [\r\n");
    trace_start_time_ = TimeTicks::Now();
    timer_.Start(TimeDelta::FromMilliseconds(250), this, &TraceLog::Heartbeat);
  }
  return enabled_;
}

// static
void TraceLog::StopTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->Stop();
}

void TraceLog::Stop() {
  if (enabled_) {
    enabled_ = false;
    Log("];\r\n");
    CloseLogFile();
    timer_.Stop();
  }
}

void TraceLog::Heartbeat() {
  std::string cpu = StringPrintf("%d", process_metrics_->GetCPUUsage());
  TRACE_EVENT_INSTANT("heartbeat.cpu", 0, cpu);
}

void TraceLog::CloseLogFile() {
  if (log_file_) {
    file_util::CloseFile(log_file_);
  }
}

bool TraceLog::OpenLogFile() {
  FilePath::StringType pid_filename =
      StringPrintf(kLogFileName, base::GetCurrentProcId());
  FilePath log_file_path;
  if (!PathService::Get(base::DIR_EXE, &log_file_path))
    return false;
  log_file_path = log_file_path.Append(pid_filename);
  log_file_ = file_util::OpenFile(log_file_path, "a");
  if (!log_file_) {
    // try the current directory
    log_file_ = file_util::OpenFile(FilePath(pid_filename), "a");
    if (!log_file_) {
      return false;
    }
  }
  return true;
}

void TraceLog::Trace(const std::string& name,
                     EventType type,
                     const void* id,
                     const std::wstring& extra,
                     const char* file,
                     int line) {
  if (!enabled_)
    return;
  Trace(name, type, id, WideToUTF8(extra), file, line);
}

void TraceLog::Trace(const std::string& name,
                     EventType type,
                     const void* id,
                     const std::string& extra,
                     const char* file,
                     int line) {
  if (!enabled_)
    return;

#ifdef USE_UNRELIABLE_NOW
  TimeTicks tick = TimeTicks::HighResNow();
#else
  TimeTicks tick = TimeTicks::Now();
#endif
  TimeDelta delta = tick - trace_start_time_;
  int64 usec = delta.InMicroseconds();
  std::string msg =
    StringPrintf("{'pid':'0x%lx', 'tid':'0x%lx', 'type':'%s', "
                 "'name':'%s', 'id':'0x%lx', 'extra':'%s', 'file':'%s', "
                 "'line_number':'%d', 'usec_begin': %I64d},\r\n",
                 base::GetCurrentProcId(),
                 PlatformThread::CurrentId(),
                 kEventTypeNames[type],
                 name.c_str(),
                 id,
                 extra.c_str(),
                 file,
                 line,
                 usec);

  Log(msg);
}

void TraceLog::Log(const std::string& msg) {
  AutoLock lock(file_lock_);

  fprintf(log_file_, "%s", msg.c_str());
}

} // namespace base
<commit_msg>clean up line ending<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/trace_event.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/time.h"

#define USE_UNRELIABLE_NOW

namespace base {

static const char* kEventTypeNames[] = {
  "BEGIN",
  "END",
  "INSTANT"
};

static const FilePath::CharType* kLogFileName =
    FILE_PATH_LITERAL("trace_%d.log");

TraceLog::TraceLog() : enabled_(false), log_file_(NULL) {
  base::ProcessHandle proc = base::GetCurrentProcessHandle();
  process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc));
}

TraceLog::~TraceLog() {
  Stop();
}

// static
bool TraceLog::IsTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->enabled_;
}

// static
bool TraceLog::StartTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->Start();
}

bool TraceLog::Start() {
  if (enabled_)
    return true;
  enabled_ = OpenLogFile();
  if (enabled_) {
    Log("var raw_trace_events = [\n");
    trace_start_time_ = TimeTicks::Now();
    timer_.Start(TimeDelta::FromMilliseconds(250), this, &TraceLog::Heartbeat);
  }
  return enabled_;
}

// static
void TraceLog::StopTracing() {
  TraceLog* trace = Singleton<TraceLog>::get();
  return trace->Stop();
}

void TraceLog::Stop() {
  if (enabled_) {
    enabled_ = false;
    Log("];\n");
    CloseLogFile();
    timer_.Stop();
  }
}

void TraceLog::Heartbeat() {
  std::string cpu = StringPrintf("%d", process_metrics_->GetCPUUsage());
  TRACE_EVENT_INSTANT("heartbeat.cpu", 0, cpu);
}

void TraceLog::CloseLogFile() {
  if (log_file_) {
    file_util::CloseFile(log_file_);
  }
}

bool TraceLog::OpenLogFile() {
  FilePath::StringType pid_filename =
      StringPrintf(kLogFileName, base::GetCurrentProcId());
  FilePath log_file_path;
  if (!PathService::Get(base::DIR_EXE, &log_file_path))
    return false;
  log_file_path = log_file_path.Append(pid_filename);
  log_file_ = file_util::OpenFile(log_file_path, "a");
  if (!log_file_) {
    // try the current directory
    log_file_ = file_util::OpenFile(FilePath(pid_filename), "a");
    if (!log_file_) {
      return false;
    }
  }
  return true;
}

void TraceLog::Trace(const std::string& name,
                     EventType type,
                     const void* id,
                     const std::wstring& extra,
                     const char* file,
                     int line) {
  if (!enabled_)
    return;
  Trace(name, type, id, WideToUTF8(extra), file, line);
}

void TraceLog::Trace(const std::string& name,
                     EventType type,
                     const void* id,
                     const std::string& extra,
                     const char* file,
                     int line) {
  if (!enabled_)
    return;

#ifdef USE_UNRELIABLE_NOW
  TimeTicks tick = TimeTicks::HighResNow();
#else
  TimeTicks tick = TimeTicks::Now();
#endif
  TimeDelta delta = tick - trace_start_time_;
  int64 usec = delta.InMicroseconds();
  std::string msg =
    StringPrintf("{'pid':'0x%lx', 'tid':'0x%lx', 'type':'%s', "
                 "'name':'%s', 'id':'0x%lx', 'extra':'%s', 'file':'%s', "
                 "'line_number':'%d', 'usec_begin': %I64d},\n",
                 base::GetCurrentProcId(),
                 PlatformThread::CurrentId(),
                 kEventTypeNames[type],
                 name.c_str(),
                 id,
                 extra.c_str(),
                 file,
                 line,
                 usec);

  Log(msg);
}

void TraceLog::Log(const std::string& msg) {
  AutoLock lock(file_lock_);

  fprintf(log_file_, "%s", msg.c_str());
}

} // namespace base
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <i18n.h>
#include <CmdUndo.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdUndo::CmdUndo ()
{
  _keyword     = "undo";
  _usage       = "task          undo";
  _description = STRING_CMD_UNDO_USAGE;
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdUndo::execute (std::string& output)
{
  // Detect attemps to modify the task.
  if (context.a3.extract_modifications ().size () > 0)
    throw std::string (STRING_CMD_UNDO_MODS);

  context.tdb2.revert ();
  context.tdb2.commit ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdUndo<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <i18n.h>
#include <CmdUndo.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdUndo::CmdUndo ()
{
  _keyword     = "undo";
  _usage       = "task          undo";
  _description = STRING_CMD_UNDO_USAGE;
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdUndo::execute (std::string& output)
{
  // Detect attempts to modify the task.
  std::vector <Tree*>::iterator i;
  for (i = context.a3t.tree ()->_branches.begin (); i != context.a3t.tree ()->_branches.end (); ++i)
    if ((*i)->hasTag ("MODIFICATION"))
      throw std::string (STRING_CMD_UNDO_MODS);

  context.tdb2.revert ();
  context.tdb2.commit ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2003 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _WIN32
#pragma warning(4: 4786)
#endif

#include <string>
#include "BZDBCache.h"

bool  BZDBCache::displayMainFlags;
bool  BZDBCache::enhancedRadar;

float BZDBCache::maxLOD;
float BZDBCache::tankHeight;
float BZDBCache::flagRadius;

void BZDBCache::init()
{
  BZDB->addCallback("displayMainFlags", clientCallback, NULL);
  BZDB->addCallback("enhancedradar", clientCallback, NULL);

  BZDB->addCallback(StateDatabase::BZDB_MAXLOD, serverCallback, NULL);
  BZDB->addCallback(StateDatabase::BZDB_TANKHEIGHT, serverCallback, NULL);
  BZDB->addCallback(StateDatabase::BZDB_FLAGRADIUS, serverCallback, NULL);
}

void BZDBCache::clientCallback(const std::string& name, void *)
{
  if (name == "displayMainFlags")
    displayMainFlags = BZDB->isTrue("displayMainFlags");
  else if (name == "enhancedradar")
    enhancedRadar = BZDB->isTrue("enhancedradar");
}

void BZDBCache::serverCallback(const std::string& name, void *)
{
  if (name == StateDatabase::BZDB_MAXLOD)
    maxLOD = BZDB->eval(StateDatabase::BZDB_MAXLOD);
  else if (name == StateDatabase::BZDB_TANKHEIGHT)
    tankHeight = BZDB->eval(StateDatabase::BZDB_TANKHEIGHT);
  else if (name == StateDatabase::BZDB_FLAGRADIUS)
    flagRadius = BZDB->eval(StateDatabase::BZDB_FLAGRADIUS);
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Init cached variables. Server needs it.<commit_after>/* bzflag
 * Copyright (c) 1993 - 2003 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _WIN32
#pragma warning(4: 4786)
#endif

#include <string>
#include "BZDBCache.h"

bool  BZDBCache::displayMainFlags;
bool  BZDBCache::enhancedRadar;

float BZDBCache::maxLOD;
float BZDBCache::tankHeight;
float BZDBCache::flagRadius;

void BZDBCache::init()
{
  BZDB->addCallback("displayMainFlags", clientCallback, NULL);
  BZDB->addCallback("enhancedradar", clientCallback, NULL);

  BZDB->addCallback(StateDatabase::BZDB_MAXLOD, serverCallback, NULL);
  BZDB->addCallback(StateDatabase::BZDB_TANKHEIGHT, serverCallback, NULL);
  BZDB->addCallback(StateDatabase::BZDB_FLAGRADIUS, serverCallback, NULL);

  maxLOD     = BZDB->eval(StateDatabase::BZDB_MAXLOD);
  tankHeight = BZDB->eval(StateDatabase::BZDB_TANKHEIGHT);
  flagRadius = BZDB->eval(StateDatabase::BZDB_FLAGRADIUS);
}

void BZDBCache::clientCallback(const std::string& name, void *)
{
  if (name == "displayMainFlags")
    displayMainFlags = BZDB->isTrue("displayMainFlags");
  else if (name == "enhancedradar")
    enhancedRadar = BZDB->isTrue("enhancedradar");
}

void BZDBCache::serverCallback(const std::string& name, void *)
{
  if (name == StateDatabase::BZDB_MAXLOD)
    maxLOD = BZDB->eval(StateDatabase::BZDB_MAXLOD);
  else if (name == StateDatabase::BZDB_TANKHEIGHT)
    tankHeight = BZDB->eval(StateDatabase::BZDB_TANKHEIGHT);
  else if (name == StateDatabase::BZDB_FLAGRADIUS)
    flagRadius = BZDB->eval(StateDatabase::BZDB_FLAGRADIUS);
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
  std::cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
  std::cout << REVISION << '\n' << std::endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
      std::cerr << "Backoff type (--backoff-type) must be one of none|simple." << std::endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
    std::set<int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
      std::vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
        std::vector<std::string> strings = contexts_corpus.context2string(*termIt);
        std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

        all_terms.insert(*termIt);
      }
      documents_out << std::endl;
    }
    documents_out.close();

    std::ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() << std::endl;
    for (std::set<int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
      std::vector<std::string> strings = contexts_corpus.context2string(*termIt);
      std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(documents_out, " "));
      default_topics << model.max(-1, *termIt) << std::endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

  std::cout << std::endl;

  return 0;
}
<commit_msg><commit_after>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
  std::cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
  std::cout << REVISION << '\n' << std::endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
      std::cerr << "Backoff type (--backoff-type) must be one of none|simple." << std::endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
    std::set<int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
      std::vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
        std::vector<std::string> strings = contexts_corpus.context2string(*termIt);
        std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

        all_terms.insert(*termIt);
      }
      documents_out << std::endl;
    }
    documents_out.close();

    std::ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() << std::endl;
    for (std::set<int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
      std::vector<std::string> strings = contexts_corpus.context2string(*termIt);
      std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(default_topics, " "));
      default_topics << "||| " << model.max(-1, *termIt) << std::endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

  std::cout << std::endl;

  return 0;
}
<|endoftext|>