<commit_before>#include "include/amici_interface_matlab.h"

#include "wrapfunctions.h" /* user functions */

#include <include/edata_accessors.h>
#include <include/udata_accessors.h>
#include <include/rdata_accessors.h>
#include <include/tdata_accessors.h>

#include <cstring>

/**
 * @ brief initialise matrix and attach to the field
 * @ param FIELD name of the field to which the matrix will be attached
 * @ param D1 number of rows in the matrix
 * @ param D2 number of columns in the matrix
 */
#define initField2(FIELD,D1,D2) \
    mxArray *mx ## FIELD = mxCreateDoubleMatrix(D1,D2,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief initialise 3D tensor and attach to the field
 * @ param FIELD name of the field to which the tensor will be attached
 * @ param D1 number of rows in the tensor
 * @ param D2 number of columns in the tensor
 * @ param D3 number of elements in the third dimension of the tensor
 */
#define initField3(FIELD,D1,D2,D3) \
    mwSize dims ## FIELD[] = {D1,D2,D3}; \
    mxArray *mx ## FIELD = mxCreateNumericArray(3,dims ## FIELD,mxDOUBLE_CLASS,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief initialise 4D tensor and attach to the field
 * @ param FIELD name of the field to which the tensor will be attached
 * @ param D1 number of rows in the tensor
 * @ param D2 number of columns in the tensor
 * @ param D3 number of elements in the third dimension of the tensor
 * @ param D4 number of elements in the fourth dimension of the tensor
 */
#define initField4(FIELD,D1,D2,D3,D4) \
    mwSize dims ## FIELD[] = {D1,D2,D3,D4}; \
    mxArray *mx ## FIELD = mxCreateNumericArray(4,dims ## FIELD,mxDOUBLE_CLASS,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief extract information from a property of a matlab class (scalar)
 * @ param OPTION name of the property
 * @ param TYPE class to which the information should be cast
 */
#define readOptionScalar(OPTION,TYPE) \
    if(mxGetProperty(prhs[3],0,#OPTION)){ \
        OPTION = (TYPE)mxGetScalar(mxGetProperty(prhs[3],0,#OPTION)); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

/**
 * @ brief extract information from a property of a matlab class (matrix)
 * @ param OPTION name of the property
 */
#define readOptionData(OPTION) \
    if(mxGetProperty(prhs[3],0,#OPTION)){ \
        OPTION = (double *) mxGetData(mxGetProperty(prhs[3],0,#OPTION)); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

UserData *userDataFromMatlabCall(const mxArray *prhs[]) {
    /* User udata structure */
    UserData *udata = new UserData();
    if(udata==NULL) return NULL;

    init_modeldims(udata);

    /* time */

    if (!prhs[0]) {
        errMsgIdAndTxt("AMICI:mex:tout","No time vector provided!");
    }
    ts = mxGetPr(prhs[0]);

    nt = (int) mxGetM(prhs[0]) * mxGetN(prhs[0]);

    /* parameters */

    if (!prhs[1]) {
        errMsgIdAndTxt("AMICI:mex:theta","No parameter vector provided!");
    }
    p = mxGetPr(prhs[1]);

    /* constants */

    if (!prhs[2]) {
        errMsgIdAndTxt("AMICI:mex:kappa","No constant vector provided!");
    }
    k = mxGetPr(prhs[2]);

    if (!prhs[3]) {
        errMsgIdAndTxt("AMICI:mex:options","No options provided!");
    }

    /* plist */
    realtype *plistdata;
    if (!prhs[4]) {
        errMsgIdAndTxt("AMICI:mex:plist","No parameter list provided!");
    } else {
        nplist = (int) mxGetM(prhs[4]) * mxGetN(prhs[4]);
        plistdata = mxGetPr(prhs[4]);
    }

    plist = new int[nplist]();
    for (int ip=0; ip<nplist; ip++) {
        plist[ip] = (int)plistdata[ip];
    }

    readOptionScalar(nmaxevent,int)
    readOptionScalar(tstart,double)
    readOptionScalar(atol,double)
    readOptionScalar(rtol,double)
    readOptionScalar(maxsteps,int)
    readOptionScalar(lmm,int)
    readOptionScalar(iter,int)
    readOptionScalar(interpType,int)
    readOptionScalar(linsol,int)
    readOptionScalar(stldet,booleantype)

    if(mxGetProperty(prhs[3],0,"id")){ \
        idlist = (double *) mxGetData(mxGetProperty(prhs[3],0,"id")); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

    readOptionData(z2event)
    readOptionData(qpositivex)
    readOptionScalar(sensi,AMI_sensi_order)
    readOptionScalar(ism,int)
    readOptionScalar(sensi_meth,AMI_sensi_meth)
    readOptionScalar(ordering,int)

    /* pbar */
    if (!prhs[5]) {
        errMsgIdAndTxt("AMICI:mex:pbar","No parameter scales provided!");
    }

    pbar = mxGetPr(prhs[5]);

    /* xscale */
    if (!prhs[6]) {
        errMsgIdAndTxt("AMICI:mex:xscale","No state scales provided!");
    }

    xbar = mxGetPr(prhs[6]);

    /* Check, if initial states and sensitivities are passed by user or must be calculated */
    x0data = NULL;
    sx0data = NULL;
    if (prhs[7]) {
        if(mxGetField(prhs[7], 0 ,"x0")) {
            if ((mxGetM(mxGetField(prhs[7], 0 ,"x0")) * mxGetN(mxGetField(prhs[7], 0 ,"x0")))>0) {
                x0data = mxGetPr(mxGetField(prhs[7], 0 ,"x0"));

                /* check dimensions */
                if(mxGetN(mxGetField(prhs[7], 0 ,"x0")) != 1) { errMsgIdAndTxt("AMICI:mex:x0","Number of rows in x0 field must be equal to 1!"); }
                if(mxGetM(mxGetField(prhs[7], 0 ,"x0")) != nx) { errMsgIdAndTxt("AMICI:mex:x0","Number of columns in x0 field does not agree with number of model states!"); }
            }
        }

        if(mxGetField(prhs[7], 0 ,"sx0")) {
            if ((mxGetM(mxGetField(prhs[7], 0 ,"sx0")) * mxGetN(mxGetField(prhs[7], 0 ,"sx0")))>0) {
                sx0data = mxGetPr(mxGetField(prhs[7], 0 ,"sx0"));

                /* check dimensions */
                if(mxGetN(mxGetField(prhs[7], 0 ,"sx0")) != nplist) { errMsgIdAndTxt("AMICI:mex:sx0","Number of rows in sx0 field does not agree with number of model parameters!"); }
                if(mxGetM(mxGetField(prhs[7], 0 ,"sx0")) != nx) { errMsgIdAndTxt("AMICI:mex:sx0","Number of columns in sx0 field does not agree with number of model states!"); }
            }
        }
    }

    processUserData(udata);

    return(udata);
}

ReturnData *setupReturnData(mxArray *plhs[], const UserData *udata, double *pstatus) {

    const char *field_names_sol[] = {"status","llh","sllh","s2llh","chi2","t","numsteps","numrhsevals","order","numstepsS","numrhsevalsS","rz","z","x","y","srz","sz","sx","sy","s2rz","sigmay","ssigmay","sigmaz","ssigmaz","xdot","J","dydp","dydx","dxdotdp"};

    /* Return rdata structure */
    ReturnData *rdata = (ReturnData*) mxMalloc(sizeof *rdata);
    if (rdata == NULL) return(NULL);

    memset(rdata, 0, sizeof(*rdata));

    mxArray *mxsol = mxCreateStructMatrix(1,1,29,field_names_sol);
    plhs[0] = mxsol;

    #include "include/amici_init_return_data_fields.h"

    mxArray *mxstatus = mxCreateDoubleMatrix(1,1,mxREAL);
    mxSetPr(mxstatus,pstatus);
    mxSetField(mxsol,0,"status",mxstatus);

    mxArray *mxts = mxCreateDoubleMatrix(nt,1,mxREAL);
    tsdata = mxGetPr(mxts);
    mxSetField(mxsol,0,"t",mxts);

    return(rdata);
}

ExpData *expDataFromMatlabCall(const mxArray *prhs[], const UserData *udata, int *status) {
    int nmyt = 0, nmyy = 0, nysigmat = 0, nysigmay = 0; /* integers with problem dimensionality */
    int nmzt = 0, nmzy = 0, nzsigmat = 0, nzsigmay = 0; /* integers with problem dimensionality */

    char *errmsg;
    errmsg = new char[200]();

    *status = -97;

    ExpData *edata; /* returned rdata struct */

    if ((mxGetM(prhs[8]) == 0 && mxGetN(prhs[8]) == 0) || !prhs[8]) {
        if(sensi >= AMI_SENSI_ORDER_FIRST && sensi_meth == AMI_SENSI_ASA) {
            errMsgIdAndTxt("AMICI:mex:data","No data provided!");
        } else {
            *status = 0;
        }
        return NULL;
    } else {
        /* Return edata structure */
        edata = new ExpData();
        if (edata == NULL) return(NULL);

        if (mxGetProperty(prhs[8], 0 ,"Y")) {
            my = mxGetPr(mxGetProperty(prhs[8], 0 ,"Y"));
            nmyy = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Y"));
            nmyt = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Y"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Y","Field Y not specified as field in data struct!");
            return NULL;
        }

        if (mxGetProperty(prhs[8], 0 ,"Sigma_Y")) {
            ysigma = mxGetPr(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
            nysigmay = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
            nysigmat = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Sigma_Y","Field Sigma_Y not specified as field in data struct!");
            return NULL;
        }
        if (mxGetProperty(prhs[8], 0 ,"Z")) {
            mz = mxGetPr(mxGetProperty(prhs[8], 0 ,"Z"));
            nmzy = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Z"));
            nmzt = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Z"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Z","Field Z not specified as field in data struct!");
            return NULL;
        }

        if (mxGetProperty(prhs[8], 0 ,"Sigma_Z")) {
            zsigma = mxGetPr(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
            nzsigmay = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
            nzsigmat = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Sigma_Z","Field Sigma_Z not specified as field in data struct!");
            return NULL;
        }

        if (nmyt != nt) {
            sprintf(errmsg,"Number of time-points in data matrix does (%i) not match provided time vector (%i)",nmyt,nt);
            errMsgIdAndTxt("AMICI:mex:data:nty",errmsg);
            return NULL;
        }

        if (nysigmat != nt) {
            sprintf(errmsg,"Number of time-points in data-sigma matrix (%i) does not match provided time vector (%i)",nysigmat,nt);
            errMsgIdAndTxt("AMICI:mex:data:ntsdy",errmsg);
            return NULL;
        }

        if (nmyy != nytrue) {
            sprintf(errmsg,"Number of observables in data matrix (%i) does not match model ny (%i)",nmyy,nytrue);
            errMsgIdAndTxt("AMICI:mex:data:nyy",errmsg);
            return NULL;
        }

        if (nysigmay != nytrue) {
            sprintf(errmsg,"Number of observables in data-sigma matrix (%i) does not match model ny (%i)",nysigmay,nytrue);
            errMsgIdAndTxt("AMICI:mex:data:nysdy",errmsg);
            return NULL;
        }

        if (nmzt != nmaxevent) {
            sprintf(errmsg,"Number of time-points in event matrix (%i) does not match provided nmaxevent (%i)",nmzt,nmaxevent);
            errMsgIdAndTxt("AMICI:mex:data:nmaxeventnz",errmsg);
            return NULL;
        }

        if (nzsigmat != nmaxevent) {
            sprintf(errmsg,"Number of time-points in event-sigma matrix (%i) does not match provided nmaxevent (%i)",nzsigmat,nmaxevent);
            errMsgIdAndTxt("AMICI:mex:data:nmaxeventnsdz",errmsg);
            return NULL;
        }

        if (nmzy != nztrue) {
            sprintf(errmsg,"Number of events in event matrix (%i) does not match provided nz (%i)",nmzy,nztrue);
            errMsgIdAndTxt("AMICI:mex:data:nenz",errmsg);
            return NULL;
        }

        if (nzsigmay != nztrue) {
            sprintf(errmsg,"Number of events in event-sigma matrix (%i) does not match provided nz (%i)",nzsigmay,nztrue);
            errMsgIdAndTxt("AMICI:mex:data:nensdz",errmsg);
            return NULL;
        }
    }

    delete[] errmsg;

    *status = 0;

    return(edata);
}

<commit_msg>Fix compile warnings for type conversion<commit_after>#include "include/amici_interface_matlab.h"

#include "wrapfunctions.h" /* user functions */

#include <include/edata_accessors.h>
#include <include/udata_accessors.h>
#include <include/rdata_accessors.h>
#include <include/tdata_accessors.h>

#include <cstring>

/**
 * @ brief initialise matrix and attach to the field
 * @ param FIELD name of the field to which the matrix will be attached
 * @ param D1 number of rows in the matrix
 * @ param D2 number of columns in the matrix
 */
#define initField2(FIELD,D1,D2) \
    mxArray *mx ## FIELD = mxCreateDoubleMatrix(D1,D2,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief initialise 3D tensor and attach to the field
 * @ param FIELD name of the field to which the tensor will be attached
 * @ param D1 number of rows in the tensor
 * @ param D2 number of columns in the tensor
 * @ param D3 number of elements in the third dimension of the tensor
 */
#define initField3(FIELD,D1,D2,D3) \
    mwSize dims ## FIELD[] = {(mwSize)(D1), (mwSize)(D2), (mwSize)(D3)}; \
    mxArray *mx ## FIELD = mxCreateNumericArray(3,dims ## FIELD,mxDOUBLE_CLASS,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief initialise 4D tensor and attach to the field
 * @ param FIELD name of the field to which the tensor will be attached
 * @ param D1 number of rows in the tensor
 * @ param D2 number of columns in the tensor
 * @ param D3 number of elements in the third dimension of the tensor
 * @ param D4 number of elements in the fourth dimension of the tensor
 */
#define initField4(FIELD,D1,D2,D3,D4) \
    mwSize dims ## FIELD[] = {(mwSize)(D1), (mwSize)(D2), (mwSize)(D3), (mwSize)(D4)}; \
    mxArray *mx ## FIELD = mxCreateNumericArray(4,dims ## FIELD,mxDOUBLE_CLASS,mxREAL); \
    FIELD ## data = mxGetPr(mx ## FIELD); \
    mxSetField(mxsol,0,#FIELD,mx ## FIELD)

/**
 * @ brief extract information from a property of a matlab class (scalar)
 * @ param OPTION name of the property
 * @ param TYPE class to which the information should be cast
 */
#define readOptionScalar(OPTION,TYPE) \
    if(mxGetProperty(prhs[3],0,#OPTION)){ \
        OPTION = (TYPE)mxGetScalar(mxGetProperty(prhs[3],0,#OPTION)); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

/**
 * @ brief extract information from a property of a matlab class (matrix)
 * @ param OPTION name of the property
 */
#define readOptionData(OPTION) \
    if(mxGetProperty(prhs[3],0,#OPTION)){ \
        OPTION = (double *) mxGetData(mxGetProperty(prhs[3],0,#OPTION)); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

UserData *userDataFromMatlabCall(const mxArray *prhs[]) {
    /* User udata structure */
    UserData *udata = new UserData();
    if(udata==NULL) return NULL;

    init_modeldims(udata);

    /* time */

    if (!prhs[0]) {
        errMsgIdAndTxt("AMICI:mex:tout","No time vector provided!");
    }
    ts = mxGetPr(prhs[0]);

    nt = (int) mxGetM(prhs[0]) * mxGetN(prhs[0]);

    /* parameters */

    if (!prhs[1]) {
        errMsgIdAndTxt("AMICI:mex:theta","No parameter vector provided!");
    }
    p = mxGetPr(prhs[1]);

    /* constants */

    if (!prhs[2]) {
        errMsgIdAndTxt("AMICI:mex:kappa","No constant vector provided!");
    }
    k = mxGetPr(prhs[2]);

    if (!prhs[3]) {
        errMsgIdAndTxt("AMICI:mex:options","No options provided!");
    }

    /* plist */
    realtype *plistdata;
    if (!prhs[4]) {
        errMsgIdAndTxt("AMICI:mex:plist","No parameter list provided!");
    } else {
        nplist = (int) mxGetM(prhs[4]) * mxGetN(prhs[4]);
        plistdata = mxGetPr(prhs[4]);
    }

    plist = new int[nplist]();
    for (int ip=0; ip<nplist; ip++) {
        plist[ip] = (int)plistdata[ip];
    }

    readOptionScalar(nmaxevent,int)
    readOptionScalar(tstart,double)
    readOptionScalar(atol,double)
    readOptionScalar(rtol,double)
    readOptionScalar(maxsteps,int)
    readOptionScalar(lmm,int)
    readOptionScalar(iter,int)
    readOptionScalar(interpType,int)
    readOptionScalar(linsol,int)
    readOptionScalar(stldet,booleantype)

    if(mxGetProperty(prhs[3],0,"id")){ \
        idlist = (double *) mxGetData(mxGetProperty(prhs[3],0,"id")); \
    } else { \
        warnMsgIdAndTxt("AMICI:mex:OPTION","Provided options are not of class amioption!"); \
        return(NULL); \
    }

    readOptionData(z2event)
    readOptionData(qpositivex)
    readOptionScalar(sensi,AMI_sensi_order)
    readOptionScalar(ism,int)
    readOptionScalar(sensi_meth,AMI_sensi_meth)
    readOptionScalar(ordering,int)

    /* pbar */
    if (!prhs[5]) {
        errMsgIdAndTxt("AMICI:mex:pbar","No parameter scales provided!");
    }

    pbar = mxGetPr(prhs[5]);

    /* xscale */
    if (!prhs[6]) {
        errMsgIdAndTxt("AMICI:mex:xscale","No state scales provided!");
    }

    xbar = mxGetPr(prhs[6]);

    /* Check, if initial states and sensitivities are passed by user or must be calculated */
    x0data = NULL;
    sx0data = NULL;
    if (prhs[7]) {
        if(mxGetField(prhs[7], 0 ,"x0")) {
            if ((mxGetM(mxGetField(prhs[7], 0 ,"x0")) * mxGetN(mxGetField(prhs[7], 0 ,"x0")))>0) {
                x0data = mxGetPr(mxGetField(prhs[7], 0 ,"x0"));

                /* check dimensions */
                if(mxGetN(mxGetField(prhs[7], 0 ,"x0")) != 1) { errMsgIdAndTxt("AMICI:mex:x0","Number of rows in x0 field must be equal to 1!"); }
                if(mxGetM(mxGetField(prhs[7], 0 ,"x0")) != nx) { errMsgIdAndTxt("AMICI:mex:x0","Number of columns in x0 field does not agree with number of model states!"); }
            }
        }

        if(mxGetField(prhs[7], 0 ,"sx0")) {
            if ((mxGetM(mxGetField(prhs[7], 0 ,"sx0")) * mxGetN(mxGetField(prhs[7], 0 ,"sx0")))>0) {
                sx0data = mxGetPr(mxGetField(prhs[7], 0 ,"sx0"));

                /* check dimensions */
                if(mxGetN(mxGetField(prhs[7], 0 ,"sx0")) != nplist) { errMsgIdAndTxt("AMICI:mex:sx0","Number of rows in sx0 field does not agree with number of model parameters!"); }
                if(mxGetM(mxGetField(prhs[7], 0 ,"sx0")) != nx) { errMsgIdAndTxt("AMICI:mex:sx0","Number of columns in sx0 field does not agree with number of model states!"); }
            }
        }
    }

    processUserData(udata);

    return(udata);
}

ReturnData *setupReturnData(mxArray *plhs[], const UserData *udata, double *pstatus) {

    const char *field_names_sol[] = {"status","llh","sllh","s2llh","chi2","t","numsteps","numrhsevals","order","numstepsS","numrhsevalsS","rz","z","x","y","srz","sz","sx","sy","s2rz","sigmay","ssigmay","sigmaz","ssigmaz","xdot","J","dydp","dydx","dxdotdp"};

    /* Return rdata structure */
    ReturnData *rdata = (ReturnData*) mxMalloc(sizeof *rdata);
    if (rdata == NULL) return(NULL);

    memset(rdata, 0, sizeof(*rdata));

    mxArray *mxsol = mxCreateStructMatrix(1,1,29,field_names_sol);
    plhs[0] = mxsol;

    #include "include/amici_init_return_data_fields.h"

    mxArray *mxstatus = mxCreateDoubleMatrix(1,1,mxREAL);
    mxSetPr(mxstatus,pstatus);
    mxSetField(mxsol,0,"status",mxstatus);

    mxArray *mxts = mxCreateDoubleMatrix(nt,1,mxREAL);
    tsdata = mxGetPr(mxts);
    mxSetField(mxsol,0,"t",mxts);

    return(rdata);
}

ExpData *expDataFromMatlabCall(const mxArray *prhs[], const UserData *udata, int *status) {
    int nmyt = 0, nmyy = 0, nysigmat = 0, nysigmay = 0; /* integers with problem dimensionality */
    int nmzt = 0, nmzy = 0, nzsigmat = 0, nzsigmay = 0; /* integers with problem dimensionality */

    char *errmsg;
    errmsg = new char[200]();

    *status = -97;

    ExpData *edata; /* returned rdata struct */

    if ((mxGetM(prhs[8]) == 0 && mxGetN(prhs[8]) == 0) || !prhs[8]) {
        if(sensi >= AMI_SENSI_ORDER_FIRST && sensi_meth == AMI_SENSI_ASA) {
            errMsgIdAndTxt("AMICI:mex:data","No data provided!");
        } else {
            *status = 0;
        }
        return NULL;
    } else {
        /* Return edata structure */
        edata = new ExpData();
        if (edata == NULL) return(NULL);

        if (mxGetProperty(prhs[8], 0 ,"Y")) {
            my = mxGetPr(mxGetProperty(prhs[8], 0 ,"Y"));
            nmyy = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Y"));
            nmyt = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Y"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Y","Field Y not specified as field in data struct!");
            return NULL;
        }

        if (mxGetProperty(prhs[8], 0 ,"Sigma_Y")) {
            ysigma = mxGetPr(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
            nysigmay = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
            nysigmat = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Sigma_Y"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Sigma_Y","Field Sigma_Y not specified as field in data struct!");
            return NULL;
        }
        if (mxGetProperty(prhs[8], 0 ,"Z")) {
            mz = mxGetPr(mxGetProperty(prhs[8], 0 ,"Z"));
            nmzy = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Z"));
            nmzt = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Z"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Z","Field Z not specified as field in data struct!");
            return NULL;
        }

        if (mxGetProperty(prhs[8], 0 ,"Sigma_Z")) {
            zsigma = mxGetPr(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
            nzsigmay = (int) mxGetN(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
            nzsigmat = (int) mxGetM(mxGetProperty(prhs[8], 0 ,"Sigma_Z"));
        } else {
            errMsgIdAndTxt("AMICI:mex:data:Sigma_Z","Field Sigma_Z not specified as field in data struct!");
            return NULL;
        }

        if (nmyt != nt) {
            sprintf(errmsg,"Number of time-points in data matrix does (%i) not match provided time vector (%i)",nmyt,nt);
            errMsgIdAndTxt("AMICI:mex:data:nty",errmsg);
            return NULL;
        }

        if (nysigmat != nt) {
            sprintf(errmsg,"Number of time-points in data-sigma matrix (%i) does not match provided time vector (%i)",nysigmat,nt);
            errMsgIdAndTxt("AMICI:mex:data:ntsdy",errmsg);
            return NULL;
        }

        if (nmyy != nytrue) {
            sprintf(errmsg,"Number of observables in data matrix (%i) does not match model ny (%i)",nmyy,nytrue);
            errMsgIdAndTxt("AMICI:mex:data:nyy",errmsg);
            return NULL;
        }

        if (nysigmay != nytrue) {
            sprintf(errmsg,"Number of observables in data-sigma matrix (%i) does not match model ny (%i)",nysigmay,nytrue);
            errMsgIdAndTxt("AMICI:mex:data:nysdy",errmsg);
            return NULL;
        }

        if (nmzt != nmaxevent) {
            sprintf(errmsg,"Number of time-points in event matrix (%i) does not match provided nmaxevent (%i)",nmzt,nmaxevent);
            errMsgIdAndTxt("AMICI:mex:data:nmaxeventnz",errmsg);
            return NULL;
        }

        if (nzsigmat != nmaxevent) {
            sprintf(errmsg,"Number of time-points in event-sigma matrix (%i) does not match provided nmaxevent (%i)",nzsigmat,nmaxevent);
            errMsgIdAndTxt("AMICI:mex:data:nmaxeventnsdz",errmsg);
            return NULL;
        }

        if (nmzy != nztrue) {
            sprintf(errmsg,"Number of events in event matrix (%i) does not match provided nz (%i)",nmzy,nztrue);
            errMsgIdAndTxt("AMICI:mex:data:nenz",errmsg);
            return NULL;
        }

        if (nzsigmay != nztrue) {
            sprintf(errmsg,"Number of events in event-sigma matrix (%i) does not match provided nz (%i)",nzsigmay,nztrue);
            errMsgIdAndTxt("AMICI:mex:data:nensdz",errmsg);
            return NULL;
        }
    }

    delete[] errmsg;

    *status = 0;

    return(edata);
}

<|endoftext|>


<commit_before>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#include <Pomdog/Utility/detail/CRC32.hpp>
#include <array>
#include <utility>

namespace Pomdog {
namespace Hashing {
namespace CRC32 {
namespace {

//
// CRC-32
// Copyright (C) 1995-1998 Mark Adler
//

#if defined(POMDOG_CRC32_CREATE_CRC_TABLE)

// if you need to make crc32 table:
static std::array<std::uint32_t, 256U> MakeCRCTable()
{
#if defined(POMDOG_CRC32_MAKE_XOR_PATTERN_FROM_POLYNOMIAL)
	constexpr std::array<std::uint8_t, 14> p = {{
		0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26
	}};

	std::uint32_t poly = 0L;
	for (auto iter: p) {
		poly |= 1L << (31 - iter);
	}
#else
	constexpr std::uint32_t poly = 0xedb88320L;
#endif // defined(POMDOG_CRC32_MAKE_XOR_PATTERN_FROM_POLYNOMIAL)

	std::array<std::uint32_t, 256U> crctable;

	for (std::uint32_t i = 0; i < crctable.size(); ++i)
	{
		std::uint32_t c	= i;
		for (std::size_t j = 0; j < 8; ++j)
		{
			c = (c & 1) ? poly ^ (c >> 1) : (c >> 1);
		}
		crctable[i] = c;
	}
	return std::move(crctable);
}

static const std::array<std::uint32_t, 256U> crctable = MakeCRCTable();

#else // !defined(POMDOG_CRC32_CREATE_CRC_TABLE)

static constexpr std::array<std::uint32_t, 256U> crctable =
{{
	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
	0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
	0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
	0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
	0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
	0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
	0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
	0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
	0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
	0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
	0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
	0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
	0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
	0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
	0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
	0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
	0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
	0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
	0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
	0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
	0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
	0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
	0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
	0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
	0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
	0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
	0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
	0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
	0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
	0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
	0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
	0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
	0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
	0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
	0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
	0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
	0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
	0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
	0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
	0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
	0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
	0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
	0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
	0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
	0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
	0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
	0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
	0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
	0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
	0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
	0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
	0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
	0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
	0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
	0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
	0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
	0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
	0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
	0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
	0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
	0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
	0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
}};
#endif // !defined(POMDOG_CRC32_CREATE_CRC_TABLE)

constexpr std::uint32_t InitValueCRC32 = 0xffffffffUL;
constexpr std::uint32_t XorValueCRC32  = 0xffffffffUL;

static void UpdateChecksum(std::uint32_t & crcvalue, std::uint8_t const* data, std::size_t length)
{
	std::uint32_t crc = crcvalue;
	while (length--)
	{
		crc = crctable[(crc ^ (*data++)) & 0xff] ^ (crc >> 8);
	}
	crcvalue = crc;
}

static void FinishChecksum(std::uint32_t & crcvalue)
{
	crcvalue ^= XorValueCRC32;
}

}// unnamed namespace

std::uint32_t BlockChecksum(void const* data, std::size_t length)
{
	std::uint32_t crc = InitValueCRC32;
	UpdateChecksum(crc, reinterpret_cast<std::uint8_t const*>(data), length);
	FinishChecksum(crc);
	return crc;
}

}// namespace CRC32
}// namespace Hashing
}// namespace Pomdog
<commit_msg>Fix static keyword<commit_after>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#include <Pomdog/Utility/detail/CRC32.hpp>
#include <array>
#include <utility>

namespace Pomdog {
namespace Hashing {
namespace CRC32 {
namespace {

//
// CRC-32
// Copyright (C) 1995-1998 Mark Adler
//

#if defined(POMDOG_CRC32_CREATE_CRC_TABLE)

// if you need to make crc32 table:
static std::array<std::uint32_t, 256U> MakeCRCTable()
{
#if defined(POMDOG_CRC32_MAKE_XOR_PATTERN_FROM_POLYNOMIAL)
	constexpr std::array<std::uint8_t, 14> p = {{
		0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26
	}};

	std::uint32_t poly = 0L;
	for (auto iter: p) {
		poly |= 1L << (31 - iter);
	}
#else
	constexpr std::uint32_t poly = 0xedb88320L;
#endif // defined(POMDOG_CRC32_MAKE_XOR_PATTERN_FROM_POLYNOMIAL)

	std::array<std::uint32_t, 256U> crctable;

	for (std::uint32_t i = 0; i < crctable.size(); ++i)
	{
		std::uint32_t c	= i;
		for (std::size_t j = 0; j < 8; ++j)
		{
			c = (c & 1) ? poly ^ (c >> 1) : (c >> 1);
		}
		crctable[i] = c;
	}
	return std::move(crctable);
}

static const std::array<std::uint32_t, 256U> crctable = MakeCRCTable();

#else // !defined(POMDOG_CRC32_CREATE_CRC_TABLE)

static constexpr std::array<std::uint32_t, 256U> crctable =
{{
	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
	0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
	0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
	0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
	0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
	0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
	0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
	0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
	0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
	0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
	0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
	0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
	0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
	0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
	0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
	0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
	0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
	0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
	0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
	0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
	0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
	0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
	0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
	0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
	0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
	0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
	0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
	0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
	0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
	0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
	0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
	0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
	0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
	0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
	0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
	0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
	0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
	0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
	0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
	0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
	0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
	0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
	0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
	0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
	0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
	0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
	0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
	0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
	0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
	0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
	0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
	0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
	0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
	0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
	0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
	0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
	0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
	0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
	0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
	0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
	0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
	0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
}};
#endif // !defined(POMDOG_CRC32_CREATE_CRC_TABLE)

static constexpr std::uint32_t InitValueCRC32 = 0xffffffffUL;
static constexpr std::uint32_t XorValueCRC32  = 0xffffffffUL;

static void UpdateChecksum(std::uint32_t & crcvalue, std::uint8_t const* data, std::size_t length)
{
	std::uint32_t crc = crcvalue;
	while (length--)
	{
		crc = crctable[(crc ^ (*data++)) & 0xff] ^ (crc >> 8);
	}
	crcvalue = crc;
}

static void FinishChecksum(std::uint32_t & crcvalue)
{
	crcvalue ^= XorValueCRC32;
}

}// unnamed namespace

std::uint32_t BlockChecksum(void const* data, std::size_t length)
{
	std::uint32_t crc = InitValueCRC32;
	UpdateChecksum(crc, reinterpret_cast<std::uint8_t const*>(data), length);
	FinishChecksum(crc);
	return crc;
}

}// namespace CRC32
}// namespace Hashing
}// namespace Pomdog
<|endoftext|>


<commit_before>/*
Copyright (c) 2007, Tim Chas

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the GameCraft Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef __cplusplus
    #include <cstdlib>
#else
    #include <stdlib.h>
#endif
#include <SDL/SDL.h>
#include <SDL/SDL_draw.h>
#include <SDL/SDL_image.h>

// to be changed to <> later - mabye
#include "GC/GC.h"

using namespace GC;

int main ( int argc, char** argv )
{
    // make sure SDL cleans up before exit
    atexit(GC_Quit);

    /*int WIDTH = 640;
    int HEIGHT = 480;
    int BPP = 16;*/

    int _tmp = GC_Init(WIDTH,HEIGHT,BPP,SDL_HWSURFACE|SDL_DOUBLEBUF);
    if (_tmp > 0)
    {
        return _tmp;
    }

    // load an image
    long bmp = SpriteAdd("cb.bmp",75,60);
    long obj = ObjectAdd(bmp);
    InstanceAdd(obj,128,128);

    // program main loop
    bool done = false;
    while (!done)
    {
        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
                {
                    // exit if ESCAPE is pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE)
                        done = true;
                    break;
                }
            } // end switch
        } // end of message processing

        // DRAWING STARTS HERE

        // clear screen
        DrawClear(cBlack);
        //DrawSprite(bmp,200,300);

        // draw bitmap
        for(long i=0; i<gInstanceID; i++)
        {
            if(gInstanceArray[i].instID >= 0)
            {
                DrawSprite(gInstanceArray[i].sprSprite->id,gInstanceArray[i].x,gInstanceArray[i].y);
            }
        //SDL_BlitSurface(bmp, 0, gpScreen, &dstrect);
        }
        // DRAWING ENDS HERE

        // finally, update the screen :)
        SDL_Flip(gpScreen);
    } // end main loop

    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
<commit_msg>Added a comment<commit_after>/*
Copyright (c) 2007, Tim Chas

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the GameCraft Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef __cplusplus
    #include <cstdlib>
#else
    #include <stdlib.h>
#endif
#include <SDL/SDL.h>
#include <SDL/SDL_draw.h>
#include <SDL/SDL_image.h>

// to be changed to <> later - mabye
#include "GC/GC.h"

/*
    Dependencies:
    LibSDL
    SDL_image.h
    SDL_draw.h
*/

using namespace GC;

int main ( int argc, char** argv )
{
    // make sure SDL cleans up before exit
    atexit(GC_Quit);

    /*int WIDTH = 640;
    int HEIGHT = 480;
    int BPP = 16;*/

    int _tmp = GC_Init(WIDTH,HEIGHT,BPP,SDL_HWSURFACE|SDL_DOUBLEBUF);
    if (_tmp > 0)
    {
        return _tmp;
    }

    // load an image
    long bmp = SpriteAdd("cb.bmp",75,60);
    long obj = ObjectAdd(bmp);
    InstanceAdd(obj,128,128);

    // program main loop
    bool done = false;
    while (!done)
    {
        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
                {
                    // exit if ESCAPE is pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE)
                        done = true;
                    break;
                }
            } // end switch
        } // end of message processing

        // DRAWING STARTS HERE

        // clear screen
        DrawClear(cBlack);
        //DrawSprite(bmp,200,300);

        // draw bitmap
        for(long i=0; i<gInstanceID; i++)
        {
            if(gInstanceArray[i].instID >= 0)
            {
                DrawSprite(gInstanceArray[i].sprSprite->id,gInstanceArray[i].x,gInstanceArray[i].y);
            }
        //SDL_BlitSurface(bmp, 0, gpScreen, &dstrect);
        }
        // DRAWING ENDS HERE

        // finally, update the screen :)
        SDL_Flip(gpScreen);
    } // end main loop

    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
<|endoftext|>


<commit_before>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_BINARYXMLDECODER_HPP
#define	NDN_BINARYXMLDECODER_HPP

#include "../c/errors.h"
#include "../c/encoding/BinaryXMLDecoder.h"

namespace ndn {

/**
 * A BinaryXMLDecoder extends a C ndn_BinaryXMLDecoder struct and wraps related functions.
 */
class BinaryXMLDecoder : public ndn_BinaryXMLDecoder {
public:
  /**
   * Initialize the base ndn_BinaryXMLDecoder struct with the input.
   */
  BinaryXMLDecoder(const unsigned char *input, unsigned int inputLength)
  {
    ndn_BinaryXMLDecoder_init(this, (unsigned char *)input, inputLength);
  }

  /**
   * Decode the header from the input starting at offset, and if it is a DTAG where the value is the expectedTag,
   * then return true, else false.  Do not update offset, including if throwing an exception.
   * @param expectedTag the expected value for DTAG
   * @return true if got the expected tag, else false
   */
  bool peekDTag(unsigned int expectedTag)
  {
    int gotExpectedTag;
    ndn_Error error;
    if (error = ndn_BinaryXMLDecoder_peekDTag(this, expectedTag, &gotExpectedTag))
      throw std::runtime_error(ndn_getErrorString(error));

    return gotExpectedTag;
  }
};

}

#endif
<commit_msg>Need to include stdexcept<commit_after>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_BINARYXMLDECODER_HPP
#define	NDN_BINARYXMLDECODER_HPP

#include <stdexcept>
#include "../c/errors.h"
#include "../c/encoding/BinaryXMLDecoder.h"

namespace ndn {

/**
 * A BinaryXMLDecoder extends a C ndn_BinaryXMLDecoder struct and wraps related functions.
 */
class BinaryXMLDecoder : public ndn_BinaryXMLDecoder {
public:
  /**
   * Initialize the base ndn_BinaryXMLDecoder struct with the input.
   */
  BinaryXMLDecoder(const unsigned char *input, unsigned int inputLength)
  {
    ndn_BinaryXMLDecoder_init(this, (unsigned char *)input, inputLength);
  }

  /**
   * Decode the header from the input starting at offset, and if it is a DTAG where the value is the expectedTag,
   * then return true, else false.  Do not update offset, including if throwing an exception.
   * @param expectedTag the expected value for DTAG
   * @return true if got the expected tag, else false
   */
  bool peekDTag(unsigned int expectedTag)
  {
    int gotExpectedTag;
    ndn_Error error;
    if (error = ndn_BinaryXMLDecoder_peekDTag(this, expectedTag, &gotExpectedTag))
      throw std::runtime_error(ndn_getErrorString(error));

    return gotExpectedTag;
  }
};

}

#endif
<|endoftext|>


<commit_before>#ifndef HESIOD_LOGGER_HPP
#define HESIOD_LOGGER_HPP

#include <string>
#include <sstream>
#include <iterator>
#include <iostream>

#include "hesiod/logger_stream_proxy.hpp"
#include "hesiod/standard_formatter.hpp"

namespace hesiod {

template <class CharT, class FormatterT = standard_formatter<CharT>>
class logger {
public:

    using stream_t = std::basic_ostream<CharT>;
    using str_t = std::basic_string<CharT>;
    using buffer_t = std::basic_stringstream<CharT>;

    static const CharT format_specifier = static_cast<CharT>('%');

    logger(stream_t &stream)
        : stream_(stream)
    {}

    template <class... Args>
    void write(const str_t &str, Args... args) {
        buffer_t buffer;
        expand_impl(buffer, 0, str, std::forward<Args>(args)...);
        stream_ << buffer.str();
    }

    template <class T>
    auto operator<<(T &&value) {
        return logger_stream_proxy<stream_t, buffer_t, FormatterT>(&stream_, std::forward<T>(value));
    }

private:

    std::basic_ostream<CharT> &stream_;

    buffer_t& expand_impl(buffer_t &buffer, std::size_t start_index, const str_t &str) const {
        auto found_index = find_format_specifier(str, start_index);
        if (found_index == std::string::npos) {
            std::copy(std::cbegin(str) + start_index, std::cend(str), std::ostream_iterator<CharT>(buffer));
            return buffer;
        }
        throw std::invalid_argument("Found more specifiers then arguments.");
    }

    template <class Arg, class ...Args>
    buffer_t& expand_impl(buffer_t &buffer, std::size_t start_index, const str_t &str, const Arg &val, const Args&... args) const {
        auto found_index = find_format_specifier(str, start_index);
        if (found_index == std::string::npos) {
            throw std::invalid_argument("Found more arguments then specifiers.");
        }
        auto cit = std::cbegin(str);
        std::copy(cit + start_index, cit + found_index, std::ostream_iterator<CharT>(buffer));
        buffer << val;
        return expand_impl(buffer, found_index + 1, str, std::forward<Args>(args)...);
    }

    auto find_format_specifier(const str_t &str, std::size_t start_index) const {
        auto found_index = str.find(format_specifier, start_index);
        if (found_index == std::string::npos) {
            return std::string::npos;
        }
        if (found_index == 0 || str[found_index - 1] != static_cast<CharT>('\\')) {
            return found_index;
        }
        return find_format_specifier(str, found_index + 1);
    }
};

}

#endif
<commit_msg>Add writeln function<commit_after>#ifndef HESIOD_LOGGER_HPP
#define HESIOD_LOGGER_HPP

#include <string>
#include <sstream>
#include <iterator>
#include <iostream>

#include "hesiod/logger_stream_proxy.hpp"
#include "hesiod/standard_formatter.hpp"
#include "hesiod/formatter_dispatcher.hpp"

namespace hesiod {

template <class CharT, class FormatterT = standard_formatter<CharT>>
class logger {
public:

    using stream_t = std::basic_ostream<CharT>;
    using str_t = std::basic_string<CharT>;
    using buffer_t = std::basic_stringstream<CharT>;

    static const CharT format_specifier = static_cast<CharT>('%');

    logger(stream_t &stream)
        : stream_(stream)
    {}

    template <class... Args>
    void write(const str_t &str, Args... args) {
        buffer_t buffer;
        expand_impl(buffer, 0, str, std::forward<Args>(args)...);
        stream_ << buffer.str();
    }

    template <class... Args>
    void writeln(const str_t &str, Args... args) {
        buffer_t buffer;
        expand_impl(buffer, 0, str, std::forward<Args>(args)...);
        formatter_dispatcher::line<FormatterT, buffer_t>::call(buffer);
        stream_ << buffer.str();
    }

    template <class T>
    auto operator<<(T &&value) {
        return logger_stream_proxy<stream_t, buffer_t, FormatterT>(&stream_, std::forward<T>(value));
    }

private:

    std::basic_ostream<CharT> &stream_;

    buffer_t& expand_impl(buffer_t &buffer, std::size_t start_index, const str_t &str) const {
        auto found_index = find_format_specifier(str, start_index);
        if (found_index == std::string::npos) {
            std::copy(std::cbegin(str) + start_index, std::cend(str), std::ostream_iterator<CharT>(buffer));
            return buffer;
        }
        throw std::invalid_argument("Found more specifiers then arguments.");
    }

    template <class Arg, class ...Args>
    buffer_t& expand_impl(buffer_t &buffer, std::size_t start_index, const str_t &str, const Arg &val, const Args&... args) const {
        auto found_index = find_format_specifier(str, start_index);
        if (found_index == std::string::npos) {
            throw std::invalid_argument("Found more arguments then specifiers.");
        }
        auto cit = std::cbegin(str);
        std::copy(cit + start_index, cit + found_index, std::ostream_iterator<CharT>(buffer));
        buffer << val;
        return expand_impl(buffer, found_index + 1, str, std::forward<Args>(args)...);
    }

    auto find_format_specifier(const str_t &str, std::size_t start_index) const {
        auto found_index = str.find(format_specifier, start_index);
        if (found_index == std::string::npos) {
            return std::string::npos;
        }
        if (found_index == 0 || str[found_index - 1] != static_cast<CharT>('\\')) {
            return found_index;
        }
        return find_format_specifier(str, found_index + 1);
    }
};

}

#endif
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// transaction_test.cpp
//
// Identification: tests/concurrency/transaction_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "concurrency/transaction_tests_util.h"

namespace peloton {

namespace test {

//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//

class TransactionTests : public PelotonTest {};

void TransactionTest(concurrency::TransactionManager *txn_manager) {
  uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();

  for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
    txn_manager->BeginTransaction();
    if (thread_id % 2 == 0) {
      std::chrono::microseconds sleep_time(1);
      std::this_thread::sleep_for(sleep_time);
    }

    if (txn_itr % 25 != 0) {
      txn_manager->CommitTransaction();
    } else {
      txn_manager->AbortTransaction();
    }
  }
}

void DirtyWriteTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T1 updates (0, ?) to (0, 1)
    // T2 updates (0, ?) to (0, 2)
    // T1 commits
    // T2 commits
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddUpdate(1, 0, 2);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddUpdate(1, 0, 2);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T0 delete (0, ?)
    // T1 update (0, ?) to (0, 3)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 0);
    scheduler.AddUpdate(1, 0, 3);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T0 delete (1, ?)
    // T1 delete (1, ?)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 1);
    scheduler.AddDelete(1, 1);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }
}

void DirtyReadTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T1 updates (0, ?) to (0, 1)
    // T2 reads (0, ?)
    // T1 commit
    // T2 commit
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T1 updates (0, ?) to (0, 1)
    // T2 reads (0, ?)
    // T2 commit
    // T1 commit
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T0 delete (0, ?)
    // T1 read (0, ?)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 0);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }
}

void FuzzyReadTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    // T0 read 0
    // T1 update (0, 0) to (0, 1)
    // T1 commit
    // T0 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(1, 0, 1);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    // T0 read 0
    // T1 update (0, 0) to (0, 1)
    // T0 commit
    // T1 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(1, 0, 1);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    // T0 read 0
    // T1 delete 0
    // T0 commit
    // T1 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddDelete(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }
}

void PhantomTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddScan(0, 0);
    scheduler.AddInsert(1, 5, 0);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddScan(0, 0);
    scheduler.AddDelete(1, 4);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }
}

void WriteSkewTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(0, 1, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddUpdate(1, 1, 2);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    // Can't all success
    EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
                 RESULT_SUCCESS == scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(0, 1, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddUpdate(1, 1, 2);
    scheduler.AddCommit(1);

    scheduler.Run();

    // First txn should success
    EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
                RESULT_ABORTED == scheduler.schedules[1].txn_result);
  }
}

TEST_F(TransactionTests, TransactionTest) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();

  LaunchParallelTest(8, TransactionTest, &txn_manager);

  std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n";
}

TEST_F(TransactionTests, AbortTest) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  TransactionScheduler scheduler(2, table.get(), &txn_manager);
  scheduler.AddUpdate(0, 0, 100);
  scheduler.AddRead(1, 0);
  scheduler.AddAbort(0);
  scheduler.AddCommit(1);

  scheduler.Run();

  EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
  EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}

TEST_F(TransactionTests, SerializableTest) {
  DirtyWriteTest();
  DirtyReadTest();
  FuzzyReadTest();
  WriteSkewTest();
  //  PhantomTes();
}

}  // End test namespace
}  // End peloton namespace
<commit_msg>Add readskew test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// transaction_test.cpp
//
// Identification: tests/concurrency/transaction_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "concurrency/transaction_tests_util.h"

namespace peloton {

namespace test {

//===--------------------------------------------------------------------===//
// Transaction Tests
//===--------------------------------------------------------------------===//

class TransactionTests : public PelotonTest {};

void TransactionTest(concurrency::TransactionManager *txn_manager) {
  uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();

  for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {
    txn_manager->BeginTransaction();
    if (thread_id % 2 == 0) {
      std::chrono::microseconds sleep_time(1);
      std::this_thread::sleep_for(sleep_time);
    }

    if (txn_itr % 25 != 0) {
      txn_manager->CommitTransaction();
    } else {
      txn_manager->AbortTransaction();
    }
  }
}

void DirtyWriteTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T1 updates (0, ?) to (0, 1)
    // T2 updates (0, ?) to (0, 2)
    // T1 commits
    // T2 commits
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddUpdate(1, 0, 2);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddUpdate(1, 0, 2);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T0 delete (0, ?)
    // T1 update (0, ?) to (0, 3)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 0);
    scheduler.AddUpdate(1, 0, 3);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    // T0 delete (1, ?)
    // T1 delete (1, ?)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 1);
    scheduler.AddDelete(1, 1);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();
    auto &schedules = scheduler.schedules;

    // T1 and T2 can't both succeed
    EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_SUCCESS);
    // For MVCC, actually one and only one T should succeed?
    EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&
                 schedules[1].txn_result == RESULT_ABORTED) ||
                (schedules[0].txn_result == RESULT_ABORTED &&
                 schedules[1].txn_result == RESULT_SUCCESS));
    schedules.clear();
  }
}

void DirtyReadTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T1 updates (0, ?) to (0, 1)
    // T2 reads (0, ?)
    // T1 commit
    // T2 commit
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T1 updates (0, ?) to (0, 1)
    // T2 reads (0, ?)
    // T2 commit
    // T1 commit
    scheduler.AddUpdate(0, 0, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);

    // T0 delete (0, ?)
    // T1 read (0, ?)
    // T0 commit
    // T1 commit
    scheduler.AddDelete(0, 0);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result);
  }
}

void FuzzyReadTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    // T0 read 0
    // T1 update (0, 0) to (0, 1)
    // T1 commit
    // T0 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(1, 0, 1);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    // T0 read 0
    // T1 update (0, 0) to (0, 1)
    // T0 commit
    // T1 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(1, 0, 1);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    // T0 read 0
    // T1 delete 0
    // T0 commit
    // T1 commit
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddDelete(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }
}

void PhantomTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddScan(0, 0);
    scheduler.AddInsert(1, 5, 0);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddScan(0, 0);
    scheduler.AddDelete(1, 4);
    scheduler.AddCommit(1);
    scheduler.AddCommit(0);

    scheduler.Run();
    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }
}

void WriteSkewTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(0, 1, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddUpdate(1, 1, 2);
    scheduler.AddCommit(0);
    scheduler.AddCommit(1);

    scheduler.Run();

    // Can't all success
    EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
                 RESULT_SUCCESS == scheduler.schedules[1].txn_result);
  }

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(0, 1, 1);
    scheduler.AddRead(1, 0);
    scheduler.AddCommit(0);
    scheduler.AddUpdate(1, 1, 2);
    scheduler.AddCommit(1);

    scheduler.Run();

    // First txn should success
    EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&
                RESULT_ABORTED == scheduler.schedules[1].txn_result);
  }
}

void ReadSkewTest() {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  {
    TransactionScheduler scheduler(2, table.get(), &txn_manager);
    scheduler.AddRead(0, 0);
    scheduler.AddUpdate(1, 0, 1);
    scheduler.AddUpdate(1, 1, 1);
    scheduler.AddCommit(1);
    scheduler.AddRead(0, 1);
    scheduler.AddCommit(0);

    scheduler.Run();

    EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
    EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
  }
}

TEST_F(TransactionTests, TransactionTest) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();

  LaunchParallelTest(8, TransactionTest, &txn_manager);

  std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n";
}

TEST_F(TransactionTests, AbortTest) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  std::unique_ptr<storage::DataTable> table(
      TransactionTestsUtil::CreateTable());

  TransactionScheduler scheduler(2, table.get(), &txn_manager);
  scheduler.AddUpdate(0, 0, 100);
  scheduler.AddRead(1, 0);
  scheduler.AddAbort(0);
  scheduler.AddCommit(1);

  scheduler.Run();

  EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);
  EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);
}

TEST_F(TransactionTests, SerializableTest) {
  DirtyWriteTest();
  DirtyReadTest();
  FuzzyReadTest();
  WriteSkewTest();
  //  PhantomTes();
}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2001-2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include <cctype>
#include <fstream>
#include <iostream>
#include <string>

#include "base/misc.hh"
#include "base/output.hh"
#include "base/str.hh"
#include "base/trace.hh"
#include "base/varargs.hh"

using namespace std;

namespace Trace {

const string DefaultName("global");
bool enabled = false;

//
// This variable holds the output stream for debug information.  Other
// than setting up/redirecting this stream, do *NOT* reference this
// directly; use DebugOut() (see below) to access this stream for
// output.
//
ostream *dprintf_stream = &cerr;
ostream &
output()
{
    return *dprintf_stream;
}

void
setOutput(const string &filename)
{
    dprintf_stream = simout.find(filename);
}

ObjectMatch ignore;

void
dprintf(Tick when, const std::string &name, const char *format,
        CPRINTF_DEFINITION)
{
    if (!name.empty() && ignore.match(name))
        return;

    std::ostream &os = *dprintf_stream;

    string fmt = "";
    CPrintfArgsList args(VARARGS_ALLARGS);

    if (!name.empty()) {
        fmt = "%s: " + fmt;
        args.push_front(name);
    }

    if (when != (Tick)-1) {
        fmt = "%7d: " + fmt;
        args.push_front(when);
    }

    fmt += format;

    ccprintf(os, fmt.c_str(), args);
    os.flush();
}

void
dump(Tick when, const std::string &name, const void *d, int len)
{
    if (!name.empty() && ignore.match(name))
        return;

    std::ostream &os = *dprintf_stream;

    string fmt = "";
    CPrintfArgsList args;

    if (!name.empty()) {
        fmt = "%s: " + fmt;
        args.push_front(name);
    }

    if (when != (Tick)-1) {
        fmt = "%7d: " + fmt;
        args.push_front(when);
    }

    const char *data = static_cast<const char *>(d);
    int c, i, j;
    for (i = 0; i < len; i += 16) {
        ccprintf(os, fmt, args);
        ccprintf(os, "%08x  ", i);
        c = len - i;
        if (c > 16) c = 16;

        for (j = 0; j < c; j++) {
            ccprintf(os, "%02x ", data[i + j] & 0xff);
            if ((j & 0xf) == 7 && j > 0)
                ccprintf(os, " ");
        }

        for (; j < 16; j++)
            ccprintf(os, "   ");
        ccprintf(os, "  ");

        for (j = 0; j < c; j++) {
            int ch = data[i + j] & 0x7f;
            ccprintf(os, "%c", (char)(isprint(ch) ? ch : ' '));
        }

        ccprintf(os, "\n");

        if (c < 16)
            break;
    }
}

} // namespace Trace
<commit_msg>Trace: FIx issue with creation of trace file with output dir overhaul.<commit_after>/*
 * Copyright (c) 2001-2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Nathan Binkert
 *          Steve Reinhardt
 */

#include <cctype>
#include <fstream>
#include <iostream>
#include <string>

#include "base/misc.hh"
#include "base/output.hh"
#include "base/str.hh"
#include "base/trace.hh"
#include "base/varargs.hh"

using namespace std;

namespace Trace {

const string DefaultName("global");
bool enabled = false;

//
// This variable holds the output stream for debug information.  Other
// than setting up/redirecting this stream, do *NOT* reference this
// directly; use DebugOut() (see below) to access this stream for
// output.
//
ostream *dprintf_stream = &cerr;
ostream &
output()
{
    return *dprintf_stream;
}

void
setOutput(const string &filename)
{
    dprintf_stream = simout.find(filename);
    if (!dprintf_stream)
        dprintf_stream = simout.create(filename);
}

ObjectMatch ignore;

void
dprintf(Tick when, const std::string &name, const char *format,
        CPRINTF_DEFINITION)
{
    if (!name.empty() && ignore.match(name))
        return;

    std::ostream &os = *dprintf_stream;

    string fmt = "";
    CPrintfArgsList args(VARARGS_ALLARGS);

    if (!name.empty()) {
        fmt = "%s: " + fmt;
        args.push_front(name);
    }

    if (when != (Tick)-1) {
        fmt = "%7d: " + fmt;
        args.push_front(when);
    }

    fmt += format;

    ccprintf(os, fmt.c_str(), args);
    os.flush();
}

void
dump(Tick when, const std::string &name, const void *d, int len)
{
    if (!name.empty() && ignore.match(name))
        return;

    std::ostream &os = *dprintf_stream;

    string fmt = "";
    CPrintfArgsList args;

    if (!name.empty()) {
        fmt = "%s: " + fmt;
        args.push_front(name);
    }

    if (when != (Tick)-1) {
        fmt = "%7d: " + fmt;
        args.push_front(when);
    }

    const char *data = static_cast<const char *>(d);
    int c, i, j;
    for (i = 0; i < len; i += 16) {
        ccprintf(os, fmt, args);
        ccprintf(os, "%08x  ", i);
        c = len - i;
        if (c > 16) c = 16;

        for (j = 0; j < c; j++) {
            ccprintf(os, "%02x ", data[i + j] & 0xff);
            if ((j & 0xf) == 7 && j > 0)
                ccprintf(os, " ");
        }

        for (; j < 16; j++)
            ccprintf(os, "   ");
        ccprintf(os, "  ");

        for (j = 0; j < c; j++) {
            int ch = data[i + j] & 0x7f;
            ccprintf(os, "%c", (char)(isprint(ch) ? ch : ' '));
        }

        ccprintf(os, "\n");

        if (c < 16)
            break;
    }
}

} // namespace Trace
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;
	int time_step		= 28;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double decay_rate	 = 0.977;
	double learning_rate = 0.005;
	double noise		 = 0.001;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch **************************
	Neural_Networks NN = Neural_Networks(time_step);

	layer.push_back(NN.Add(new Layer("MNIST", 784 / time_step)));
	layer.push_back(NN.Add(new Layer("BN,LSTM", 100)));			 // batch normalization, LSTM forward direction
	layer.push_back(NN.Add(new Layer("BN,LSTM,backward", 100))); // batch normalization, LSTM backward direction
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		 // cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");			// fully connected
	layer[1]->Connect(layer[1], "W,recurrent"); // fully connected
	layer[2]->Connect(layer[0], "W");			// fully connected
	layer[2]->Connect(layer[2], "W,recurrent"); // fully connected
	layer[3]->Connect(layer[1], "W");			// fully connected
	layer[3]->Connect(layer[2], "W");			// fully connected

	srand(0); NN.Initialize(0.1, 0.1);

	{
		bool *time_mask = new bool[time_step];

		for (int t = 0; t < time_step; t++) {
			time_mask[t] = (t == 0 || t == time_step - 1);
		}
		layer[3]->Set_Time_Mask(time_mask);
	}*/
	// *********************************************

	// load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_BLSTM.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[time_step * number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&target_output[h][(time_step - 1) * number_nodes.back()], target_output[h], sizeof(float) * number_nodes.back());
	}
	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon, noise);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax, index = (time_step - 1) * number_nodes.back(); g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j] + output[g][index + j]) {
							max = output[g][argmax = j] + output[g][index + j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}<commit_msg>Update MNIST_BLSTM.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;
	int time_step		= 28;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double decay_rate	 = 0.977;
	double learning_rate = 0.005;
	double noise		 = 0.001;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch **************************
	Neural_Networks NN = Neural_Networks(time_step);

	layer.push_back(NN.Add(new Layer("MNIST", 784 / time_step)));
	layer.push_back(NN.Add(new Layer("BN,LSTM", 100)));			 // batch normalization, LSTM forward direction
	layer.push_back(NN.Add(new Layer("BN,LSTM,backward", 100))); // batch normalization, LSTM backward direction
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		 // cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");			// fully connected
	layer[1]->Connect(layer[1], "W,recurrent"); // fully connected
	layer[2]->Connect(layer[0], "W");			// fully connected
	layer[2]->Connect(layer[2], "W,recurrent"); // fully connected
	layer[3]->Connect(layer[1], "W");			// fully connected
	layer[3]->Connect(layer[2], "W");			// fully connected

	srand(0); NN.Initialize(0.1, 0.1);

	{
		bool *time_mask = new bool[time_step];

		for (int t = 0; t < time_step; t++) {
			time_mask[t] = (t == 0 || t == time_step - 1);
		}
		layer[3]->Set_Time_Mask(time_mask);
	}
	// *********************************************

	// load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_BLSTM.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[time_step * number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&target_output[h][(time_step - 1) * number_nodes.back()], target_output[h], sizeof(float) * number_nodes.back());
	}
	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon, noise);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax, index = (time_step - 1) * number_nodes.back(); g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j] + output[g][index + j]) {
							max = output[g][argmax = j] + output[g][index + j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<|endoftext|>


<commit_before>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_BINARYXMLENCODER_HPP
#define	NDN_BINARYXMLENCODER_HPP

#include <cstdlib>
#include <stdexcept>
#include <vector>
#include "../c/encoding/BinaryXMLEncoder.h"

namespace ndn {

/**
 * A BinaryXMLEncoder extends a C ndn_BinaryXMLEncoder struct and wraps related functions.
 */
class BinaryXMLEncoder : public ndn_BinaryXMLEncoder {
public:
  /**
   * Initialize the base ndn_BinaryXMLEncoder struct with an initial array of 16 bytes.  Use simpleRealloc.
   */
  BinaryXMLEncoder()
  {
    const unsigned int initialLength = 16;
    ndn_BinaryXMLEncoder_init(this, (unsigned char *)malloc(initialLength), initialLength, simpleRealloc);
  }

  /**
   * Wrap the C stdlib realloc to convert to/from void * to unsigned char *.
   * @param array the allocated array buffer to realloc
   * @param length the length for the new array buffer
   * @return the new allocated array buffer
   */
  static unsigned char *simpleRealloc(unsigned char *array, unsigned int length)
  {
    return (unsigned char *)realloc(array, length);
  }

  /**
   * Copy the encoded bytes to the end of the buffer.
   * @param buffer a vector to receive the copy
   */
  void appendTo(std::vector<unsigned char> &buffer)
  {
    buffer.insert(buffer.end(), output.array, output.array + offset);
  }
};

}

#endif
<commit_msg>Remove unneeded include<commit_after>/**
 * @author: Jeff Thompson
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_BINARYXMLENCODER_HPP
#define	NDN_BINARYXMLENCODER_HPP

#include <cstdlib>
#include <vector>
#include "../c/encoding/BinaryXMLEncoder.h"

namespace ndn {

/**
 * A BinaryXMLEncoder extends a C ndn_BinaryXMLEncoder struct and wraps related functions.
 */
class BinaryXMLEncoder : public ndn_BinaryXMLEncoder {
public:
  /**
   * Initialize the base ndn_BinaryXMLEncoder struct with an initial array of 16 bytes.  Use simpleRealloc.
   */
  BinaryXMLEncoder()
  {
    const unsigned int initialLength = 16;
    ndn_BinaryXMLEncoder_init(this, (unsigned char *)malloc(initialLength), initialLength, simpleRealloc);
  }

  /**
   * Wrap the C stdlib realloc to convert to/from void * to unsigned char *.
   * @param array the allocated array buffer to realloc
   * @param length the length for the new array buffer
   * @return the new allocated array buffer
   */
  static unsigned char *simpleRealloc(unsigned char *array, unsigned int length)
  {
    return (unsigned char *)realloc(array, length);
  }

  /**
   * Copy the encoded bytes to the end of the buffer.
   * @param buffer a vector to receive the copy
   */
  void appendTo(std::vector<unsigned char> &buffer)
  {
    buffer.insert(buffer.end(), output.array, output.array + offset);
  }
};

}

#endif
<|endoftext|>