<commit_before>#include <osg/Version>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <set>
#include <vector>
#include <iostream>
#include <fstream>

typedef std::pair<std::string, std::string> NamePair;
typedef std::set<NamePair> NameSet;

NamePair EmptyNamePair;

bool validName(const std::string& first)
{
    if (first.empty()) return false;
    if (first[0]<'A' || first[0]>'Z') return false;

    if (first.size()>=2 && (first[1]<'a' || first[1]>'z')) return false;

    if (first=="Added") return false;
    if (first=="CameraNode") return false;
    if (first=="CopyOp") return false;
    if (first=="Fixed") return false;
    if (first=="Creator") return false;
    if (first=="CullVisitor") return false;
    if (first=="Drawable") return false;
    if (first=="Geode") return false;
    if (first=="GeoSet") return false;
    if (first=="Image") return false;
    if (first=="Images/SolarSystem") return false;
    if (first=="IntersectVisitor") return false;
    if (first=="LongIDRecord") return false;
    if (first=="Makefile") return false;
    if (first=="Matrix") return false;
    if (first=="MemoryManager") return false;
    if (first=="MeshRecord") return false;
    if (first=="Multigen") return false;
    if (first=="NewCullVisitor") return false;
    if (first=="Output") return false;
    if (first=="PageLOD") return false;
    if (first=="Improved") return false;
    if (first=="PagedLOD") return false;
    if (first=="Referenced") return false;
    if (first=="StateAttribute") return false;
    if (first=="Switch") return false;
    if (first=="TechniqueEventHandler") return false;
    if (first=="Uniform") return false;
    if (first=="Vec*") return false;
    if (first=="Viewer") return false;
    if (first=="VisualStudio") return false;
    if (first=="X") return false;
    if (first=="Y") return false;
    if (first=="Producer") return false;
    if (first=="New") return false;
    if (first=="Removed") return false;
    if (first=="Ouput") return false;
    if (first=="ReaderWriters") return false;
    if (first=="NodeVisitor") return false;
    if (first=="Fixes") return false;
    if (first=="FontImplementation") return false;
    if (first=="DisplaySettings") return false;
    return true;
}

std::string typoCorrection(const std::string& name)
{
#if 0
    if (name=="") return "";
    if (name=="") return "";
    if (name=="") return "";
#endif
    if (name=="Bistroviae") return "Bistrovic";
    if (name=="Christaiansen") return "Christiansen";
    if (name=="Daust") return "Daoust";
    if (name=="Daved") return "David";
    if (name=="Fred") return "Frederic";
    if (name=="Fredrick") return "Frederic";
    if (name=="Fredric") return "Frederic";
    if (name=="Garrat") return "Garret";
    if (name=="Geof") return "Geoff";
    if (name=="Gronenger") return "Gronager";
    if (name=="Gronger") return "Gronager";
    if (name=="Heirtlein") return "Heirtlein";
    if (name=="Heirtlein") return "Hertlein";
    if (name=="Hertlien") return "Hertlein";
    if (name=="Hi") return "He";
    if (name=="Inverson") return "Iverson";
    if (name=="Iversion") return "Iverson";
    if (name=="Jeoen") return "Joran";
    if (name=="Johhansen") return "Johansen";
    if (name=="Johnansen") return "Johansen";
    if (name=="Johnasen") return "Johansen";
    if (name=="Jolley") return "Jolly";
    if (name=="Jose") return "Jos";
    if (name=="J") return "Jos";
    if (name=="Keuhne") return "Kuehne";
    if (name=="Kheune") return "Kuehne";
    if (name=="Lashari") return "Lashkari";
    if (name=="Laskari") return "Lashkari";
    if (name=="Macro") return "Marco";
    if (name=="Mammond") return "Marmond";
    if (name=="March") return "Marco";
    if (name=="Marz") return "Martz";
    if (name=="Molishtan") return "Molishtan";
    if (name=="Molishtan") return "Moloshtan";
    if (name=="Moloshton") return "Moloshtan";
    if (name=="Moloshton") return "Moloshtan";
    if (name=="Moule") return "Moiule";
    if (name=="Nicklov") return "Nikolov";
    if (name=="Olad") return "Olaf";
    if (name=="Osfied") return "Osfield";
    if (name=="Pail") return "Paul";
    if (name=="Sewel") return "Sewell";
    if (name=="Sjolie") return "Sjlie";
    if (name=="Sokolosky") return "Sokolowsky";
    if (name=="Sokolsky") return "Sokolowsky";
    if (name=="Sonda") return "Sondra";
    if (name=="Stansilav") return "Stanislav";
    if (name=="Stefan") return "Stephan";
    if (name=="Stell") return "Steel";
    if (name=="Tarantilils") return "Tarantilis";
    if (name=="Wieblen") return "Weiblen";
    if (name=="Xennon") return "Hanson";
    if (name=="Yfei") return "Yefei";
    if (name=="Oritz") return "Ortiz";
    return name;
}

void nameCorrection(NamePair& name)
{
    if (name.first=="Eric" && name.second=="Hammil")
    {
        name.first = "Chris";
        name.second = "Hanson";
    }
    if (name.first=="Nick" && name.second=="")
    {
        name.first = "Trajce";
        name.second = "Nikolov";
    }
    if (name.first=="Julia" && name.second=="Ortiz")
    {
        name.first = "Julian";
        name.second = "Ortiz";
    }
}

void lastValidCharacter(const std::string& name, unsigned int& pos,char c)
{
    for(unsigned int i=0;i<pos;++i)
    {
        if (name[i]==c)
        {
            pos = i;
            return;
        }
    }
}

void lastValidCharacter(const std::string& name, unsigned int& last)
{
    lastValidCharacter(name, last, '.');
    lastValidCharacter(name, last, ',');
    lastValidCharacter(name, last, '\'');
    lastValidCharacter(name, last, '/');
    lastValidCharacter(name, last, '\\');
    lastValidCharacter(name, last, ':');
    lastValidCharacter(name, last, ';');
    lastValidCharacter(name, last, ')');
}

NamePair createName(const std::string& first, const std::string& second)
{
    if (first.empty()) return EmptyNamePair;

    unsigned int last = first.size();

    lastValidCharacter(first, last);

    if (last==0) return EmptyNamePair;

    std::string name;

    name.append(first.begin(), first.begin()+last);

    if (!validName(name)) return EmptyNamePair;

    name = typoCorrection(name);

    if (second.empty()) return NamePair(name,"");

    if (!validName(second)) return NamePair(name,"");

    last = second.size();

    lastValidCharacter(second, last);

    if (last>0)
    {
        std::string surname(second.begin(), second.begin()+last);
        surname = typoCorrection(surname);

        return NamePair(name, surname);
    }

    return NamePair(name,"");
}

void readContributors(NameSet& names, const std::string& file)
{
    std::cout<<"readContributions(names,"<<file<<")"<<std::endl;

    std::ifstream fin(file.c_str());

    typedef std::vector< std::string > Words;
    Words words;
    while(fin)
    {
        std::string keyword;
        fin >> keyword;
        words.push_back(keyword);
    }

    std::string blank_string;

    for(unsigned int i=0; i< words.size(); ++i)
    {
        if (words[i]=="From" ||
            words[i]=="from" ||
            words[i]=="From:" ||
            words[i]=="from:")
        {
            if (i+2<words.size() && validName(words[i+1]))
            {
                NamePair name = createName(words[i+1], words[i+2]);
                nameCorrection(name);
                if (!name.first.empty()) names.insert(name);
                i+=2;
            }
            else if (i+1<words.size() && validName(words[i+1]))
            {
                NamePair name = createName(words[i+1], blank_string);
                nameCorrection(name);
                if (!name.first.empty()) names.insert(name);
                i+=1;
            }
        }
    }

    if (names.size()>1)
    {
        for(NameSet::iterator itr = names.begin();
            itr != names.end();
            )
        {
            if (itr->second.empty())
            {
                NameSet::iterator next_itr = itr;
                ++next_itr;

                if (next_itr!=names.end() && itr->first==next_itr->first)
                {
                    names.erase(itr);
                    itr = next_itr;
                }
                else
                {
                    ++itr;
                }
            }
            else
            {
                ++itr;
            }
        }
    }
}

void buildContributors(NameSet& names)
{
    names.insert(NamePair("Robert","Osfield"));
    names.insert(NamePair("Don","Burns"));
    names.insert(NamePair("Marco","Jez"));
}

int main( int argc, char **argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-c or --contributors","Print out the contributors list.");
    arguments.getApplicationUsage()->addCommandLineOption("-r <file> or --read <file>","Read the changelog to generate an estimated contributors list.");

    printf( "%s\n", osgGetVersion() );

    bool printContributors = false;
    while ( arguments.read("-c") || arguments.read("--contributors")) printContributors = true;

    std::string changeLog;
    while ( arguments.read("-r",changeLog) || arguments.read("--read",changeLog)) printContributors = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    if (printContributors)
    {
        NameSet names;
        buildContributors(names);
        if (!changeLog.empty())
        {
            readContributors(names, changeLog);
        }

        std::cout<<names.size()<<" Contributors:"<<std::endl;
        for(NameSet::iterator itr = names.begin();
            itr != names.end();
            ++itr)
        {
            std::cout<<"  "<<itr->first<<" "<<itr->second<<std::endl;
        }
    }

    return 0;
}
<commit_msg>Added more typo catches.<commit_after>#include <osg/Version>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>

#include <set>
#include <vector>
#include <iostream>
#include <fstream>

typedef std::pair<std::string, std::string> NamePair;
typedef std::set<NamePair> NameSet;
typedef std::vector< std::string > Words;

NamePair EmptyNamePair;

bool validName(const std::string& first)
{
    if (first.empty()) return false;
    if (first[0]<'A' || first[0]>'Z') return false;

    if (first.size()>=2 && (first[1]<'a' || first[1]>'z')) return false;

    if (first=="Added") return false;
    if (first=="CameraNode") return false;
    if (first=="CopyOp") return false;
    if (first=="Fixed") return false;
    if (first=="Creator") return false;
    if (first=="CullVisitor") return false;
    if (first=="Drawable") return false;
    if (first=="Geode") return false;
    if (first=="GeoSet") return false;
    if (first=="Image") return false;
    if (first=="Images/SolarSystem") return false;
    if (first=="IntersectVisitor") return false;
    if (first=="LongIDRecord") return false;
    if (first=="Makefile") return false;
    if (first=="Matrix") return false;
    if (first=="MemoryManager") return false;
    if (first=="MeshRecord") return false;
    if (first=="Multigen") return false;
    if (first=="NewCullVisitor") return false;
    if (first=="Output") return false;
    if (first=="PageLOD") return false;
    if (first=="Improved") return false;
    if (first=="PagedLOD") return false;
    if (first=="Referenced") return false;
    if (first=="StateAttribute") return false;
    if (first=="Switch") return false;
    if (first=="TechniqueEventHandler") return false;
    if (first=="Uniform") return false;
    if (first=="Vec*") return false;
    if (first=="Viewer") return false;
    if (first=="VisualStudio") return false;
    if (first=="X") return false;
    if (first=="Y") return false;
    if (first=="Producer") return false;
    if (first=="New") return false;
    if (first=="Removed") return false;
    if (first=="Ouput") return false;
    if (first=="ReaderWriters") return false;
    if (first=="NodeVisitor") return false;
    if (first=="Fixes") return false;
    if (first=="FontImplementation") return false;
    if (first=="DisplaySettings") return false;
    if (first=="AnimationPath") return false;
    if (first=="AnimationPathCallback") return false;
    if (first=="AnimationPathManipulator") return false;
    if (first=="ArgumentParser") return false;
    if (first=="AttrData") return false;
    if (first=="Azimuth") return false;
    if (first=="CluserCullingCallback") return false;
    if (first=="ClusterCullingCallback") return false;
    if (first=="CoordinateSystem") return false;
    if (first=="CoordinateSystemNode") return false;
    if (first=="CoordinateSystemNode&") return false;
    if (first=="Copyright") return false;
    if (first=="Cygwin") return false;
    if (first=="CullCallbacks") return false;
    if (first=="CullingSettngs") return false;
    if (first=="DataVariance") return false;
    if (first=="DatabasePager") return false;
    if (first=="DrawElementsUByte") return false;
    if (first=="Escape") return false;
    if (first=="FluidProgram") return false;
    if (first=="FrameStats") return false;
    if (first=="FreeBSD") return false;
    if (first=="GraphicsContextImplementation") return false;
    if (first=="GraphicsThread") return false;
    if (first=="Images") return false;
    if (first=="IndexBlock") return false;
    if (first=="Inventor") return false;
    if (first=="Make") return false;
    if (first=="Material") return false;
    if (first=="MergeGeometryVisitor") return false;
    if (first=="Mode") return false;
    if (first=="Prodcuer") return false;
    if (first=="ProxyNode") return false;
    if (first=="ReentrantMutex") return false;
    if (first=="ReferenceFrame") return false;
    if (first=="RemoveLoadedProxyNodes") return false;
    if (first=="RenderTargetFallback") return false;
    if (first=="RenderToTextureStage") return false;
    if (first=="Sequence") return false;
    if (first=="Shape") return false;
    if (first=="TessellationHints") return false;
    if (first=="Support") return false;
    if (first=="State") return false;
    if (first=="SmokeTrailEffect") return false;
    if (first=="TexEnv") return false;
    if (first=="Texture3D") return false;
    if (first=="TextureCubeMap") return false;
    if (first=="TextureObjectManager") return false;
    if (first=="TextureRectangle(Image*") return false;
    if (first=="TextureType") return false;
    if (first=="Texuture") return false;
    if (first=="TriStripVisitor") return false;
    if (first=="UserData") return false;
    if (first=="Viewport") return false;
    if (first=="Visual") return false;
    if (first=="Studio") return false;
    if (first=="Vec2d") return false;
    if (first=="Vec3d") return false;
    if (first=="Windows") return false;
    if (first=="Version") return false;
    if (first=="Viewport") return false;
    if (first=="Core") return false;
    if (first=="DataSet") return false;
    if (first=="Endian") return false;
    if (first=="ImageOptions") return false;
    if (first=="ImageStream") return false;
    if (first=="KeyboardMouse") return false;
    if (first=="KeyboardMouseCallback") return false;
    if (first=="AutoTransform") return false;
    if (first=="LightModel") return false;
    if (first=="MatrixManipulator") return false;
    if (first=="MatrixTransform") return false;
    if (first=="OpenDX") return false;
    if (first=="ParentList") return false;
    if (first=="TerraPage") return false;
    if (first=="OveralyNode") return false;
    if (first=="OpenThreads") return false;
    if (first=="PolygonStipple") return false;
    if (first=="SceneView") return false;
    if (first=="PrimitiveIndexFunctor") return false;
    if (first=="PolytopeVisitor") return false;
    if (first=="Performer") return false;
    if (first=="Paging") return false;
    return true;
}

std::string typoCorrection(const std::string& name)
{
#if 0
    if (name=="") return "";
    if (name=="") return "";
    if (name=="") return "";
#endif
    if (name=="Micheal") return "Michael";
    if (name=="Heirtlein") return "Hertlein";
    if (name=="Yefrei") return "Yefei";
    if (name=="Randal") return "Randall";
    if (name=="Hooper") return "Hopper";
    if (name=="Molishtan") return "Moloshtan";
    if (name=="Vines") return "Vine";
    if (name=="Connel") return "Connell";
    if (name=="Bistroviae") return "Bistrovic";
    if (name=="Christaiansen") return "Christiansen";
    if (name=="Daust") return "Daoust";
    if (name=="Daved") return "David";
    if (name=="Fred") return "Frederic";
    if (name=="Fredrick") return "Frederic";
    if (name=="Fredric") return "Frederic";
    if (name=="Garrat") return "Garret";
    if (name=="Geof") return "Geoff";
    if (name=="Gronenger") return "Gronager";
    if (name=="Gronger") return "Gronager";
    if (name=="Heirtlein") return "Heirtlein";
    if (name=="Heirtlein") return "Hertlein";
    if (name=="Hertlien") return "Hertlein";
    if (name=="Hi") return "He";
    if (name=="Inverson") return "Iverson";
    if (name=="Iversion") return "Iverson";
    if (name=="Jeoen") return "Joran";
    if (name=="Johhansen") return "Johansen";
    if (name=="Johnansen") return "Johansen";
    if (name=="Johnasen") return "Johansen";
    if (name=="Jolley") return "Jolly";
    if (name=="Jose") return "Jos";
    if (name=="J") return "Jos";
    if (name=="Keuhne") return "Kuehne";
    if (name=="Kheune") return "Kuehne";
    if (name=="Lashari") return "Lashkari";
    if (name=="Laskari") return "Lashkari";
    if (name=="Macro") return "Marco";
    if (name=="Mammond") return "Marmond";
    if (name=="March") return "Marco";
    if (name=="Marz") return "Martz";
    if (name=="Molishtan") return "Molishtan";
    if (name=="Molishtan") return "Moloshtan";
    if (name=="Moloshton") return "Moloshtan";
    if (name=="Moloshton") return "Moloshtan";
    if (name=="Moule") return "Moiule";
    if (name=="Nicklov") return "Nikolov";
    if (name=="Olad") return "Olaf";
    if (name=="Osfied") return "Osfield";
    if (name=="Pail") return "Paul";
    if (name=="Sewel") return "Sewell";
    if (name=="Sjolie") return "Sjlie";
    if (name=="Sokolosky") return "Sokolowsky";
    if (name=="Sokolsky") return "Sokolowsky";
    if (name=="Sonda") return "Sondra";
    if (name=="Stansilav") return "Stanislav";
    if (name=="Stefan") return "Stephan";
    if (name=="Stell") return "Steel";
    if (name=="Tarantilils") return "Tarantilis";
    if (name=="Wieblen") return "Weiblen";
    if (name=="Xennon") return "Hanson";
    if (name=="Yfei") return "Yefei";
    if (name=="Oritz") return "Ortiz";
    if (name=="Cobin") return "Corbin";
    return name;
}

void nameCorrection(NamePair& name)
{
    if (name.first=="Eric" && name.second=="Hammil")
    {
        name.first = "Chris";
        name.second = "Hanson";
    }
    if (name.first=="Nick" && name.second=="")
    {
        name.first = "Trajce";
        name.second = "Nikolov";
    }
    if (name.first=="Julia" && name.second=="Ortiz")
    {
        name.first = "Julian";
        name.second = "Ortiz";
    }
    if (name.first=="Rune" && name.second=="Schmidt")
    {
        name.first = "Rune";
        name.second = "Schmidt Jensen";
    }
    if (name.first=="Romano" && name.second=="Jos")
    {
        name.first = "Romano";
        name.second = "Jos Magacho da Silva";
    }
    if (name.first=="Rommano" && name.second=="Silva")
    {
        name.first = "Romano";
        name.second = "Jos Magacho da Silva";
    }
}

void lastValidCharacter(const std::string& name, unsigned int& pos,char c)
{
    for(unsigned int i=0;i<pos;++i)
    {
        if (name[i]==c)
        {
            pos = i;
            return;
        }
    }
}

void lastValidCharacter(const std::string& name, unsigned int& last)
{
    lastValidCharacter(name, last, '.');
    lastValidCharacter(name, last, ',');
    lastValidCharacter(name, last, '\'');
    lastValidCharacter(name, last, '/');
    lastValidCharacter(name, last, '\\');
    lastValidCharacter(name, last, ':');
    lastValidCharacter(name, last, ';');
    lastValidCharacter(name, last, ')');
}

NamePair createName(const std::string& first, const std::string& second)
{
    if (first.empty()) return EmptyNamePair;

    unsigned int last = first.size();

    lastValidCharacter(first, last);

    if (last==0) return EmptyNamePair;

    std::string name;

    name.append(first.begin(), first.begin()+last);

    if (!validName(name)) return EmptyNamePair;

    name = typoCorrection(name);

    if (second.empty()) return NamePair(name,"");

    if (!validName(second)) return NamePair(name,"");

    last = second.size();

    lastValidCharacter(second, last);

    if (last>0)
    {
        std::string surname(second.begin(), second.begin()+last);
        surname = typoCorrection(surname);

        return NamePair(name, surname);
    }

    return NamePair(name,"");
}

bool submissionsSequence(const Words& words, unsigned int& i)
{
    if (i+1>=words.size()) return false;

    if (words[i]=="From" ||
        words[i]=="from" ||
        words[i]=="From:" ||
        words[i]=="from:" ||
        words[i]=="Added" ||
        words[i]=="Merged" ||
        words[i]=="Integrated") return true;

    if (i+2>=words.size()) return false;

    if (words[i]=="submitted" && words[i+1]=="by")
    {
        i+=1;
        return true;
    }

    if (words[i]=="Folded" && words[i+1]=="in")
    {
        i+=1;
        return true;
    }

    if (words[i]=="Checked" && words[i+1]=="in")
    {
        i+=1;
        return true;
    }

    if (i+3>=words.size()) return false;

    if (words[i]=="sent" && words[i+1]=="in" && words[i+2]=="by")
    {
        i+=2;
        return true;
    }

    return false;
}

void readContributors(NameSet& names, const std::string& file)
{
    std::ifstream fin(file.c_str());

    Words words;
    while(fin)
    {
        std::string keyword;
        fin >> keyword;
        words.push_back(keyword);
    }

    std::string blank_string;

    for(unsigned int i=0; i< words.size(); ++i)
    {
        if (submissionsSequence(words,i))
        {
            if (i+2<words.size() && validName(words[i+1]))
            {
                NamePair name = createName(words[i+1], words[i+2]);
                nameCorrection(name);
                if (!name.first.empty()) names.insert(name);
                i+=2;
            }
            else if (i+1<words.size() && validName(words[i+1]))
            {
                NamePair name = createName(words[i+1], blank_string);
                nameCorrection(name);
                if (!name.first.empty()) names.insert(name);
                i+=1;
            }
        }
    }

    if (names.size()>1)
    {
        for(NameSet::iterator itr = names.begin();
            itr != names.end();
            )
        {
            if (itr->second.empty())
            {
                NameSet::iterator next_itr = itr;
                ++next_itr;

                if (next_itr!=names.end() && itr->first==next_itr->first)
                {
                    names.erase(itr);
                    itr = next_itr;
                }
                else
                {
                    ++itr;
                }
            }
            else
            {
                ++itr;
            }
        }
    }
}

void buildContributors(NameSet& names)
{
    names.insert(NamePair("Robert","Osfield"));
    names.insert(NamePair("Don","Burns"));
    names.insert(NamePair("Marco","Jez"));
    names.insert(NamePair("Karsten","Weiss"));
    names.insert(NamePair("Graeme","Harkness"));
    names.insert(NamePair("Axel","Volley"));
    names.insert(NamePair("Nikolaus","Hanekamp"));
    names.insert(NamePair("Kristopher","Bixler"));
    names.insert(NamePair("Tanguy","Fautr"));
    names.insert(NamePair("J.E.","Hoffmann"));
}

int main( int argc, char **argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-c or --contributors","Print out the contributors list.");
    arguments.getApplicationUsage()->addCommandLineOption("-r <file> or --read <file>","Read the changelog to generate an estimated contributors list.");

    std::cout<<osgGetLibraryName()<< " "<< osgGetVersion()<<std::endl<<std::endl;

    bool printContributors = false;
    while ( arguments.read("-c") || arguments.read("--contributors")) printContributors = true;

    std::string changeLog;
    while ( arguments.read("-r",changeLog) || arguments.read("--read",changeLog)) printContributors = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    if (printContributors)
    {
        NameSet names;
        buildContributors(names);
        if (!changeLog.empty())
        {
            readContributors(names, changeLog);
        }

        std::cout<<names.size()<<" Contributors:"<<std::endl<<std::endl;
        for(NameSet::iterator itr = names.begin();
            itr != names.end();
            ++itr)
        {
            std::cout<<"  "<<itr->first<<" "<<itr->second<<std::endl;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * @file MeldBlockCode.cpp
 * @brief Unique blockCode for any meld program. Target module type is determined from command line by meld.cpp
 * @autor Pierre Thalamy
 * @date 20/07/2016
 */

#include <iostream>
#include <sstream>

#include "scheduler.h"
#include "network.h"

#include "meldBlockCode.h"
#include "meldInterpretEvents.h"
#include "meldInterpretMessages.h"
#include "meldInterpretVM.h"
#include "lattice.h"

#include "trace.h"

using namespace std;
using namespace MeldInterpret;

ModuleType MeldBlockCode::moduleType;

MeldBlockCode::MeldBlockCode(BuildingBlock *host): BlockCode(host) {
	OUTPUT << "MeldBlockCode constructor" << endl;
	vm = new MeldInterpretVM(hostBlock);
	hasWork = true; // mode fastest
	polling = false; // mode fastest
	currentLocalDate = 0; // mode fastest
}

MeldBlockCode::~MeldBlockCode() {
	delete vm;
	OUTPUT << "MeldBlockCode destructor" << endl;
}

void MeldBlockCode::init() {
	stringstream info;

	if((vm != NULL)) {
		for (int i = 0; i < hostBlock->getNbInterfaces(); i++) {
			vm->neighbors[i] = vm->get_neighbor_ID(i);
			OUTPUT << "Adding neighbor " << vm->neighbors[i] << " on face " << i << endl;
			vm->enqueue_face(vm->neighbors[i], i, 1);
		}

		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));

		if((getScheduler()->getMode() == SCHEDULER_MODE_FASTEST) && !vm->deterministicSet) {
			vm->deterministicSet = true;
			/*SetDeterministicModeVMCommand determinismCommand(c, hostBlock->blockId);
			  vm->sendCommand(determinismCommand);*/
			info << "deterministic mode set";
			getScheduler()->trace(info.str(),hostBlock->blockId);
			OUTPUT << "deterministic mode enable on the VM " << hostBlock->blockId << endl;
		}
	}
}

void MeldBlockCode::startup() {
	stringstream info;

	currentLocalDate = BaseSimulator::getScheduler()->now();
	info << "  Starting MeldBlockCode in block " << hostBlock->blockId;
	getScheduler()->trace(info.str(),hostBlock->blockId);
	init();
}

void MeldBlockCode::handleDeterministicMode(/*VMCommand &command*/){
	currentLocalDate = max(BaseSimulator::getScheduler()->now(), currentLocalDate);
	/*if(!hasWork && (command.getType() != VM_COMMAND_STOP)) {
	  hasWork = true;
	  #ifdef TEST_DETER
	  //cout << hostBlock->blockId << " has work again at " << BaseSimulator::getScheduler()->now() << endl;
	  #endif
	  }*/
}

void MeldBlockCode::processLocalEvent(EventPtr pev) {
	stringstream info;
	assert(vm != NULL);
	info.str("");
	OUTPUT << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now()
		   << " process event " << pev->getEventName() << "(" << pev->eventType << ")"
		   << ", random number : " << pev->randomNumber << endl;

#ifdef TEST_DETER
	cout << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now()
		 << " process event " << pev->getEventName() << "(" << pev->eventType << ")"
		 << ", random number : " << pev->randomNumber << endl;
#endif
	switch (pev->eventType) {
	case EVENT_COMPUTE_PREDICATE:
	{
		//Call the VM function to process one rule
		vm->processOneRule();
		//Add another compute event on condition
		//if...
		if(vm->isWaiting()){
			// random delay before recomputing a predicate
			// between 0.1 ms and 1ms
			int delay = (hostBlock->getNextRandomNumber() % (1000 - 100 +1 )) + 100;
			BaseSimulator::getScheduler()->schedule(
				new ComputePredicateEvent(BaseSimulator::getScheduler()->now()+delay, hostBlock));
		}
		//else info << " Block is no longer waiting";
		//info << "Compute predicate event";
	}
	break;
	case EVENT_STOP:
	{
		//getDebugger()->sendTerminateMsg(hostBlock->blockId);
		delete vm;
		info << "VM stopped";
	}
	break;
	case EVENT_ADD_NEIGHBOR:
	{
		//Should not be used by itself, presence of another block is tested by P2PNetworkInterface
		unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face;
		vm->neighbors[face] = (std::static_pointer_cast<AddNeighborEvent>(pev))->target;
		vm->enqueue_face(vm->neighbors[face], face, 1);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "Add neighbor "<< (std::static_pointer_cast<AddNeighborEvent>(pev))->target
			 << " at face "
			 << lattice->getDirectionString(lattice->getOppositeDirection(
										 (std::static_pointer_cast<AddNeighborEvent>(pev))->face));
	}
	break;
	case EVENT_REMOVE_NEIGHBOR:
	{
		unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face;
		vm->neighbors[face] = VACANT;
		vm->enqueue_face(vm->neighbors[face], face, -1);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "Remove neighbor at face " << lattice->getDirectionString(lattice->getOppositeDirection(face));
	}
	break;
	case EVENT_TAP:
	{
		vm->enqueue_tap();
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "tapped";
	}
	break;
	case EVENT_SET_COLOR:
	{
		hostBlock->getTime();
		//Called by the VM, no need to enqueue things
		Color color = (std::static_pointer_cast<SetColorEvent>(pev))->color;
		hostBlock->setColor(color);
#ifdef TEST_DETER
		cout << hostBlock->blockId << " SET_COLOR_EVENT" << endl;
#endif
		info << "set color "<< color;
	}
	break;

	/*The interface being connected is tested in function tuple_send of the MeldInterpVM*/
	case EVENT_SEND_MESSAGE:
	{
		MessagePtr message = (std::static_pointer_cast<VMSendMessageEvent>(pev))->message;
		P2PNetworkInterface *interface = (std::static_pointer_cast<VMSendMessageEvent>(pev))->sourceInterface;
		getScheduler()->schedule(
			new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(),
													 message, interface));
		info << "sends a message at face " << lattice->getDirectionString(hostBlock->getDirection(interface))  << " to " << interface->connectedInterface->hostBlock->blockId;
	}
	break;
	case EVENT_RECEIVE_MESSAGE: /*EVENT_NI_RECEIVE: */
	{
		MessagePtr mes = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message;
		switch(mes->type){
		case ADD_TUPLE_MSG_ID:
			getScheduler()->schedule(
				new AddTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock,
								  std::static_pointer_cast<AddTupleMessage>(mes)->tuple,
								  hostBlock->getDirection(mes->sourceInterface->connectedInterface)));
			break;
		case REMOVE_TUPLE_MSG_ID:
			getScheduler()->schedule(
				new RemoveTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock,
									 std::static_pointer_cast<RemoveTupleMessage>(mes)->tuple,
									 hostBlock->getDirection(mes->sourceInterface->connectedInterface)));
			break;
		}
#ifdef TEST_DETER
		cout << "message received from " << command->sourceInterface->hostBlock->blockId << endl;
#endif
		//info << "message received at face " << NeighborDirection::getString(hostBlock->getDirection(mes->sourceInterface->connectedInterface)) << " from " << mes->sourceInterface->hostBlock->blockId;
	}
	break;
	case EVENT_ACCEL:
	{
		/*Not written yet, have to check how the vm handle accel (tuple, etc)*/
		info << "accel";
	}
	break;
	case EVENT_SHAKE:
	{
		/*Not written yet, same as accel*/

		info << "shake";
	}
	break;
	case EVENT_SET_DETERMINISTIC:
	{
		/*Not sure how to handle that with MeldInterp*/
		OUTPUT << "VM set in deterministic mode " << hostBlock->blockId << endl;
		info << "VM set in deterministic mode";
	}
	break;
	case EVENT_END_POLL:
	{
		polling = false;
		/*Not written yet
		  Need to check what this is for*/
		info << "Polling time period ended";
	}
	break;
	case EVENT_ADD_TUPLE:
		this->vm->receive_tuple(1, std::static_pointer_cast<AddTupleEvent>(pev)->tuple,
								std::static_pointer_cast<AddTupleEvent>(pev)->face);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		//info << "Adding tuple";
		break;
	case EVENT_REMOVE_TUPLE:
		this->vm->receive_tuple(-1, std::static_pointer_cast<RemoveTupleEvent>(pev)->tuple,
								std::static_pointer_cast<RemoveTupleEvent>(pev)->face);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		//info << "Removing tuple";
		break;
	default:
		ERRPUT << "*** ERROR *** : unknown local event";
		break;
	}
	if(info.str() != "") {
		getScheduler()->trace(info.str(),hostBlock->blockId);
	}
}

BlockCode* MeldBlockCode::buildNewBlockCode(BuildingBlock *host) {
	return(new MeldBlockCode(host));
}
<commit_msg>Fix issues due to the merge operation with the refactoring branch.<commit_after>/*
 * @file MeldBlockCode.cpp
 * @brief Unique blockCode for any meld program. Target module type is determined from command line by meld.cpp
 * @autor Pierre Thalamy
 * @date 20/07/2016
 */

#include <iostream>
#include <sstream>

#include "scheduler.h"
#include "network.h"

#include "meldBlockCode.h"
#include "meldInterpretEvents.h"
#include "meldInterpretMessages.h"
#include "meldInterpretVM.h"
#include "lattice.h"

#include "trace.h"

using namespace std;
using namespace MeldInterpret;

ModuleType MeldBlockCode::moduleType;

MeldBlockCode::MeldBlockCode(BuildingBlock *host): BlockCode(host) {
	OUTPUT << "MeldBlockCode constructor" << endl;
	vm = new MeldInterpretVM(hostBlock);
	hasWork = true; // mode fastest
	polling = false; // mode fastest
	currentLocalDate = 0; // mode fastest
}

MeldBlockCode::~MeldBlockCode() {
	delete vm;
	OUTPUT << "MeldBlockCode destructor" << endl;
}

void MeldBlockCode::init() {
	stringstream info;

	if((vm != NULL)) {
		for (int i = 0; i < hostBlock->getNbInterfaces(); i++) {
			vm->neighbors[i] = vm->get_neighbor_ID(i);
			OUTPUT << "Adding neighbor " << vm->neighbors[i] << " on face " << i << endl;
			vm->enqueue_face(vm->neighbors[i], i, 1);
		}

		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));

		if((getScheduler()->getMode() == SCHEDULER_MODE_FASTEST) && !vm->deterministicSet) {
			vm->deterministicSet = true;
			/*SetDeterministicModeVMCommand determinismCommand(c, hostBlock->blockId);
			  vm->sendCommand(determinismCommand);*/
			info << "deterministic mode set";
			getScheduler()->trace(info.str(),hostBlock->blockId);
			OUTPUT << "deterministic mode enable on the VM " << hostBlock->blockId << endl;
		}
	}
}

void MeldBlockCode::startup() {
	stringstream info;

	currentLocalDate = BaseSimulator::getScheduler()->now();
	info << "  Starting MeldBlockCode in block " << hostBlock->blockId;
	getScheduler()->trace(info.str(),hostBlock->blockId);
	init();
}

void MeldBlockCode::handleDeterministicMode(/*VMCommand &command*/){
	currentLocalDate = max(BaseSimulator::getScheduler()->now(), currentLocalDate);
	/*if(!hasWork && (command.getType() != VM_COMMAND_STOP)) {
	  hasWork = true;
	  #ifdef TEST_DETER
	  //cout << hostBlock->blockId << " has work again at " << BaseSimulator::getScheduler()->now() << endl;
	  #endif
	  }*/
}

void MeldBlockCode::processLocalEvent(EventPtr pev) {
	stringstream info;
	assert(vm != NULL);
	info.str("");
	OUTPUT << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now()
		   << " process event " << pev->getEventName() << "(" << pev->eventType << ")"
		   << ", random number : " << pev->randomNumber << endl;

#ifdef TEST_DETER
	cout << hostBlock->blockId << " processLocalEvent: date: "<< BaseSimulator::getScheduler()->now()
		 << " process event " << pev->getEventName() << "(" << pev->eventType << ")"
		 << ", random number : " << pev->randomNumber << endl;
#endif
	switch (pev->eventType) {
	case EVENT_COMPUTE_PREDICATE:
	{
		//Call the VM function to process one rule
		vm->processOneRule();
		//Add another compute event on condition
		//if...
		if(vm->isWaiting()){
			// random delay before recomputing a predicate
			// between 0.1 ms and 1ms
			int delay = (hostBlock->getNextRandomNumber() % (1000 - 100 +1 )) + 100;
			BaseSimulator::getScheduler()->schedule(
				new ComputePredicateEvent(BaseSimulator::getScheduler()->now()+delay, hostBlock));
		}
		//else info << " Block is no longer waiting";
		//info << "Compute predicate event";
	}
	break;
	case EVENT_STOP:
	{
		//getDebugger()->sendTerminateMsg(hostBlock->blockId);
		delete vm;
		info << "VM stopped";
	}
	break;
	case EVENT_ADD_NEIGHBOR:
	{
		//Should not be used by itself, presence of another block is tested by P2PNetworkInterface
		unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face;
		vm->neighbors[face] = (std::static_pointer_cast<AddNeighborEvent>(pev))->target;
		vm->enqueue_face(vm->neighbors[face], face, 1);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "Add neighbor "<< (std::static_pointer_cast<AddNeighborEvent>(pev))->target
			 << " at face "
			 << lattice->getDirectionString(lattice->getOppositeDirection(
										 (std::static_pointer_cast<AddNeighborEvent>(pev))->face));
	}
	break;
	case EVENT_REMOVE_NEIGHBOR:
	{
		unsigned int face = (std::static_pointer_cast<AddNeighborEvent>(pev))->face;
		vm->neighbors[face] = VACANT;
		vm->enqueue_face(vm->neighbors[face], face, -1);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "Remove neighbor at face " << lattice->getDirectionString(lattice->getOppositeDirection(face));
	}
	break;
	case EVENT_TAP:
	{
		vm->enqueue_tap();
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		info << "tapped";
	}
	break;
	case EVENT_SET_COLOR:
	{
		hostBlock->getLocalTime();
		//Called by the VM, no need to enqueue things
		Color color = (std::static_pointer_cast<SetColorEvent>(pev))->color;
		hostBlock->setColor(color);
#ifdef TEST_DETER
		cout << hostBlock->blockId << " SET_COLOR_EVENT" << endl;
#endif
		info << "set color "<< color;
	}
	break;

	/*The interface being connected is tested in function tuple_send of the MeldInterpVM*/
	case EVENT_SEND_MESSAGE:
	{
		MessagePtr message = (std::static_pointer_cast<VMSendMessageEvent>(pev))->message;
		P2PNetworkInterface *interface = (std::static_pointer_cast<VMSendMessageEvent>(pev))->sourceInterface;
		getScheduler()->schedule(
			new NetworkInterfaceEnqueueOutgoingEvent(BaseSimulator::getScheduler()->now(),
													 message, interface));
		info << "sends a message at face " << lattice->getDirectionString(hostBlock->getDirection(interface))  << " to " << interface->connectedInterface->hostBlock->blockId;
	}
	break;
	case EVENT_RECEIVE_MESSAGE: /*EVENT_NI_RECEIVE: */
	{
		MessagePtr mes = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message;
		switch(mes->type){
		case ADD_TUPLE_MSG_ID:
			getScheduler()->schedule(
				new AddTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock,
								  std::static_pointer_cast<AddTupleMessage>(mes)->tuple,
								  hostBlock->getDirection(mes->sourceInterface->connectedInterface)));
			break;
		case REMOVE_TUPLE_MSG_ID:
			getScheduler()->schedule(
				new RemoveTupleEvent(BaseSimulator::getScheduler()->now(), hostBlock,
									 std::static_pointer_cast<RemoveTupleMessage>(mes)->tuple,
									 hostBlock->getDirection(mes->sourceInterface->connectedInterface)));
			break;
		}
#ifdef TEST_DETER
		cout << "message received from " << command->sourceInterface->hostBlock->blockId << endl;
#endif
		//info << "message received at face " << NeighborDirection::getString(hostBlock->getDirection(mes->sourceInterface->connectedInterface)) << " from " << mes->sourceInterface->hostBlock->blockId;
	}
	break;
	case EVENT_ACCEL:
	{
		/*Not written yet, have to check how the vm handle accel (tuple, etc)*/
		info << "accel";
	}
	break;
	case EVENT_SHAKE:
	{
		/*Not written yet, same as accel*/

		info << "shake";
	}
	break;
	case EVENT_SET_DETERMINISTIC:
	{
		/*Not sure how to handle that with MeldInterp*/
		OUTPUT << "VM set in deterministic mode " << hostBlock->blockId << endl;
		info << "VM set in deterministic mode";
	}
	break;
	case EVENT_END_POLL:
	{
		polling = false;
		/*Not written yet
		  Need to check what this is for*/
		info << "Polling time period ended";
	}
	break;
	case EVENT_ADD_TUPLE:
		this->vm->receive_tuple(1, std::static_pointer_cast<AddTupleEvent>(pev)->tuple,
								std::static_pointer_cast<AddTupleEvent>(pev)->face);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		//info << "Adding tuple";
		break;
	case EVENT_REMOVE_TUPLE:
		this->vm->receive_tuple(-1, std::static_pointer_cast<RemoveTupleEvent>(pev)->tuple,
								std::static_pointer_cast<RemoveTupleEvent>(pev)->face);
		BaseSimulator::getScheduler()->schedule(
			new ComputePredicateEvent(BaseSimulator::getScheduler()->now(), hostBlock));
		//info << "Removing tuple";
		break;
	default:
		ERRPUT << "*** ERROR *** : unknown local event";
		break;
	}
	if(info.str() != "") {
		getScheduler()->trace(info.str(),hostBlock->blockId);
	}
}

BlockCode* MeldBlockCode::buildNewBlockCode(BuildingBlock *host) {
	return(new MeldBlockCode(host));
}
<|endoftext|>


<commit_before>#ifndef MYSLICER_HPP
#define MYSLICER_HPP
#include "distribution.hpp"
#include "error_handler.hpp"
#include "base_urand.hpp"
#include <algorithm>
#include <limits>
//#define DEBUG
#ifdef DEBUG
#include <fstream>
#endif
#include <cassert>
#include <list>
#include <utility>
#include <limits>
#include <cmath>

namespace mcmc_utilities
{

  template <typename T>
  class slice_sampler
  {
  private:
    bool adapt;
    T width;
    size_t nmax;
    size_t nmin;
    size_t niter;
    T sumdiff;
    const size_t min_adapt;
    const probability_density_1d<T>& pd;

  public:
    slice_sampler(const probability_density_1d<T>& _pd, const T& _width,size_t _nmax,size_t _nmin)
      :adapt(true),width(_width),nmax(_nmax),nmin(_nmin),niter(0),sumdiff(0),min_adapt(50),pd(_pd)
    {
    }

  private:
    T exponential(base_urand<T>& rnd)const
    {
      T result=0;
      do
	{
	  result=-std::log(1-rnd());
	}
      while(std::isinf(result));
      return result;
    }

    bool accept(const T& xold,const T& xnew,const T& z,T L, T R,
		const T& lower, const T& upper)const
    {
      bool d = false;
      while ((R - L) > static_cast<T>(1.1) * width)
	{
	  T M = (L + R)/2;
	  if ((xold < M && xnew >= M) || (xold >= M && xnew < M))
	    d = true;
	  if (xnew < M)
	    {
	      R = M;
	    }
	  else
	    {
	      L = M;
	    }
	  if (d)
	    {
	      bool right_ok = true;
	      if (R <= upper)
		{
		  right_ok = pd.eval_log(R) < z;
		}
	      bool left_ok = true;
	      if (L >= lower)
		{
		  left_ok = pd.eval_log(L) < z;
		}
	      if (left_ok && right_ok)
		{
		  return false;
		}
	    }
	}
      return true;
    }

  public:
    T sample_double(T& xcur,base_urand<T>& rng)
    {
      for(size_t i=0;i<nmin;++i)
	{
	  sample1_double(xcur,rng);
	}
      return xcur;
    }

    T sample1_double(T& xcur,base_urand<T>& rng)
    {
      T lower = 0;
      T upper = 0;

      auto xrange=pd.var_range();
      lower=xrange.first;
      upper=xrange.second;

      if(xcur<xrange.first||xcur>xrange.second)
      {
	throw var_out_of_range();
      }

      T g0 = pd.eval_log(xcur);
      if (std::isnan(g0)||std::isinf(g0))
	{
	  throw nan_or_inf();
	}

      // Generate auxiliary variable
      T z = g0 - exponential(rng);

      // Generate random interval of width "_width" about current value
      T xold = xcur;
      T L = xold - rng() * width;
      T R = L + width;

      // Doubling
      bool left_ok = false, right_ok = false;
      for (size_t i = 0; i < nmax; ++i) {
	if (rng() < static_cast<T>(0.5))
	  {
	    if (L >= lower)
	      {
		L = 2*L - R;
		if (L < lower)
		  {
		    left_ok = true;
		  }
		else
		  {
		    xcur=L;
		    left_ok = pd.eval_log(xcur) < z;
		  }
	      }
	    else
	      {
		left_ok = true;
	      }
	  }
	else
	  {
	    if (R <= upper)
	      {
		R = 2*R - L;
		if (R > upper)
		  {
		    right_ok = true;
		  }
		else
		  {
		    xcur=R;
		    right_ok = pd.eval_log(xcur) < z;
		  }
	      }
	    else
	      {
		right_ok = true;
	      }
	  }
	if (left_ok && right_ok)
	  {
	    break;
	  }
      }

      T Lbar = L, Rbar = R;
      T xnew;
      for(;;)
	{
	  xnew =  Lbar + rng() * (Rbar - Lbar);
	  if (xnew >= lower && xnew <= upper)
	    {
	      xcur=xnew;
	      T g = pd.eval_log(xnew);
	      if (g >= z && accept(xold, xnew, z, L, R, lower, upper))
		{
		  xcur=xnew;
		  break;
		}
	    }

	  if (xnew <= xold)
	    {
	      Lbar = xnew;
	    }
	  else
	    {
	      Rbar = xnew;
	    }
	}

      if (adapt)
	{
	  sumdiff += niter * std::abs(xnew - xold);
	  ++niter;
	  if (niter > min_adapt)
	    {
	      width = 2 * sumdiff / niter / (niter - 1);
	    }
	}

      return xcur;
    }

    T sample_step(T& xcur,base_urand<T>& rng)
    {
      for(size_t i=0;i<nmin;++i)
	{
	  sample1_step(xcur,rng);
	}
      return xcur;
    }

    T sample1_step(T& xcur,base_urand<T>& rng)
    {
      T lower = 0;
      T upper = 0;
      auto xrange=pd.var_range();
      lower=xrange.first;
      upper=xrange.second;
      if(xcur<xrange.first||xcur>xrange.second)
	{
	  throw var_out_of_range();
	}

      T g0 = pd.eval_log(xcur);
      if (std::isinf(g0))
	{
	  throw nan_or_inf();
	}

      // Generate auxiliary variable
      T z = g0 - exponential(rng);

      // Generate random interval of width "_width" about current value
      T xold = xcur;
      T L = xold - rng() * width;
      T R = L + width;

      size_t j = static_cast<size_t>(rng() * nmax);
      size_t k = nmax - 1 - j;

      if (L < lower)
	{
	  L = lower;
	}
      else
	{
	  //setValue(L);
	  xcur=L;
	  while (j-- > 0 && pd.eval_log(xcur) > z)
	    {
	      L -= width;
	      if (L < lower)
		{
		  L = lower;
		  break;
		}
	      //setValue(L);
	      xcur=L;
	    }
	}

      if (R > upper)
	{
	  R = upper;
	}
      else
	{
	  //setValue(R);
	  xcur=R;
	  while (k-- > 0 && pd.eval_log(xcur) > z)
	    {
	      R += width;
	      if (R > upper)
		{
		  R = upper;
		  break;
		}
	      xcur = R;
	    }
	}

      T xnew;
      for(;;)
	{
	  xnew =  L + rng() * (R - L);
	  xcur=xnew;
	  T g = pd.eval_log(xcur);
	  if (g >= z - std::numeric_limits<T>::epsilon())
	    {
	      break;
	    }
	  else
	    {
	      if (xnew < xold)
		{
		  L = xnew;
		}
	      else
		{
		  R = xnew;
		}
	    }
	}

      if (adapt)
	{
	  sumdiff += niter * std::abs(xnew - xold);
	  ++niter;
	  if ( niter > min_adapt)
	    {
	      width = 2 * sumdiff / niter / (niter - 1);
	    }
	}

      return xcur;
    }

  };
}

#endif
<commit_msg>	modified:   core/slicer.hpp<commit_after>#ifndef MYSLICER_HPP
#define MYSLICER_HPP
#include "distribution.hpp"
#include "error_handler.hpp"
#include "base_urand.hpp"
#include <algorithm>
#include <limits>
//#define DEBUG
#ifdef DEBUG
#include <fstream>
#endif
#include <cassert>
#include <list>
#include <utility>
#include <limits>
#include <cmath>

namespace mcmc_utilities
{

  template <typename T>
  class slice_sampler
  {
  private:
    bool adapt;
    T width;
    size_t nmax;
    size_t nmin;
    size_t niter;
    T sumdiff;
    const size_t min_adapt;
    const probability_density_1d<T>& pd;

  public:
    slice_sampler(const probability_density_1d<T>& _pd, const T& _width,size_t _nmax,size_t _nmin)
      :adapt(true),width(_width),nmax(_nmax),nmin(_nmin),niter(0),sumdiff(0),min_adapt(50),pd(_pd)
    {
    }

  private:
    T exponential(base_urand<T>& rnd)const
    {
      T result=0;
      do
	{
	  result=-std::log(1-rnd());
	}
      while(std::isinf(result));
      return result;
    }

    bool accept(const T& xold,const T& xnew,const T& z,T L, T R,
		const T& lower, const T& upper)const
    {
      bool d = false;
      while ((R - L) > static_cast<T>(1.1) * width)
	{
	  T M = (L + R)/2;
	  if ((xold < M && xnew >= M) || (xold >= M && xnew < M))
	    d = true;
	  if (xnew < M)
	    {
	      R = M;
	    }
	  else
	    {
	      L = M;
	    }
	  if (d)
	    {
	      bool right_ok = true;
	      if (R <= upper)
		{
		  right_ok = pd.eval_log(R) < z;
		}
	      bool left_ok = true;
	      if (L >= lower)
		{
		  left_ok = pd.eval_log(L) < z;
		}
	      if (left_ok && right_ok)
		{
		  return false;
		}
	    }
	}
      return true;
    }

  public:
    T sample_double(T& xcur,base_urand<T>& rng)
    {
      for(size_t i=0;i<nmin;++i)
	{
	  sample1_double(xcur,rng);
	}
      return xcur;
    }

    T sample1_double(T& xcur,base_urand<T>& rng)
    {
      T lower = 0;
      T upper = 0;

      auto xrange=pd.var_range();
      lower=xrange.first;
      upper=xrange.second;

      if(xcur<xrange.first||xcur>xrange.second)
      {
	std::cerr<<"xcur="<<xcur<<" ("<<xrange.first<<" , "<<xrange.second<<")"<<std::endl;
	throw var_out_of_range();
      }

      T g0 = pd.eval_log(xcur);
      if (std::isnan(g0)||std::isinf(g0))
	{
	  throw nan_or_inf();
	}

      // Generate auxiliary variable
      T z = g0 - exponential(rng);

      // Generate random interval of width "_width" about current value
      T xold = xcur;
      T L = xold - rng() * width;
      T R = L + width;

      // Doubling
      bool left_ok = false, right_ok = false;
      for (size_t i = 0; i < nmax; ++i) {
	if (rng() < static_cast<T>(0.5))
	  {
	    if (L >= lower)
	      {
		L = 2*L - R;
		if (L < lower)
		  {
		    left_ok = true;
		  }
		else
		  {
		    xcur=L;
		    left_ok = pd.eval_log(xcur) < z;
		  }
	      }
	    else
	      {
		left_ok = true;
	      }
	  }
	else
	  {
	    if (R <= upper)
	      {
		R = 2*R - L;
		if (R > upper)
		  {
		    right_ok = true;
		  }
		else
		  {
		    xcur=R;
		    right_ok = pd.eval_log(xcur) < z;
		  }
	      }
	    else
	      {
		right_ok = true;
	      }
	  }
	if (left_ok && right_ok)
	  {
	    break;
	  }
      }

      T Lbar = L, Rbar = R;
      T xnew;
      for(;;)
	{
	  xnew =  Lbar + rng() * (Rbar - Lbar);
	  if (xnew >= lower && xnew <= upper)
	    {
	      xcur=xnew;
	      T g = pd.eval_log(xnew);
	      if (g >= z && accept(xold, xnew, z, L, R, lower, upper))
		{
		  xcur=xnew;
		  break;
		}
	    }

	  if (xnew <= xold)
	    {
	      Lbar = xnew;
	    }
	  else
	    {
	      Rbar = xnew;
	    }
	}

      if (adapt)
	{
	  sumdiff += niter * std::abs(xnew - xold);
	  ++niter;
	  if (niter > min_adapt)
	    {
	      width = 2 * sumdiff / niter / (niter - 1);
	    }
	}

      return xcur;
    }

    T sample_step(T& xcur,base_urand<T>& rng)
    {
      for(size_t i=0;i<nmin;++i)
	{
	  sample1_step(xcur,rng);
	}
      return xcur;
    }

    T sample1_step(T& xcur,base_urand<T>& rng)
    {
      T lower = 0;
      T upper = 0;
      auto xrange=pd.var_range();
      lower=xrange.first;
      upper=xrange.second;
      if(xcur<xrange.first||xcur>xrange.second)
	{
	  std::cerr<<"xcur="<<xcur<<" ("<<xrange.first<<" , "<<xrange.second<<")"<<std::endl;
	  throw var_out_of_range();
	}

      T g0 = pd.eval_log(xcur);
      if (std::isinf(g0))
	{
	  std::cerr<<"xcur="<<xcur<<std::endl;
	  throw nan_or_inf();
	}

      // Generate auxiliary variable
      T z = g0 - exponential(rng);

      // Generate random interval of width "_width" about current value
      T xold = xcur;
      T L = xold - rng() * width;
      T R = L + width;

      size_t j = static_cast<size_t>(rng() * nmax);
      size_t k = nmax - 1 - j;

      if (L < lower)
	{
	  L = lower;
	}
      else
	{
	  //setValue(L);
	  xcur=L;
	  while (j-- > 0 && pd.eval_log(xcur) > z)
	    {
	      L -= width;
	      if (L < lower)
		{
		  L = lower;
		  break;
		}
	      //setValue(L);
	      xcur=L;
	    }
	}

      if (R > upper)
	{
	  R = upper;
	}
      else
	{
	  //setValue(R);
	  xcur=R;
	  while (k-- > 0 && pd.eval_log(xcur) > z)
	    {
	      R += width;
	      if (R > upper)
		{
		  R = upper;
		  break;
		}
	      xcur = R;
	    }
	}

      T xnew;
      for(;;)
	{
	  xnew =  L + rng() * (R - L);
	  xcur=xnew;
	  T g = pd.eval_log(xcur);
	  if (g >= z - std::numeric_limits<T>::epsilon())
	    {
	      break;
	    }
	  else
	    {
	      if (xnew < xold)
		{
		  L = xnew;
		}
	      else
		{
		  R = xnew;
		}
	    }
	}

      if (adapt)
	{
	  sumdiff += niter * std::abs(xnew - xold);
	  ++niter;
	  if ( niter > min_adapt)
	    {
	      width = 2 * sumdiff / niter / (niter - 1);
	    }
	}

      return xcur;
    }

  };
}

#endif
<|endoftext|>


<commit_before>#include "main.h"
#include <chrono>

int num_rows;
int num_cols;
int num_nonzeros;

std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;

#include "utils.h"

void ReadSparse(COO& data, const std::string filename) {
  std::cout << "Reading: " << filename << std::endl;
  std::stringstream ss(ReadFileAsString(filename));
  size_t i, j;
  double v;

  while (true) {
    ss >> i;
    // Make sure that after reading things are still valid
    // If so then the line is good and continue
    if (ss.fail() == true) {
      break;
    }
    ss >> j >> v;
    data.row.push_back(i);
    data.col.push_back(j);
    data.val.push_back(v);
  }
  data.update();
}

void ReadVector(std::vector<double>& data, const std::string filename) {
  std::cout << "Reading: " << filename << std::endl;
  std::stringstream ss(ReadFileAsString(filename));
  double v;

  while (true) {
    ss >> v;
    // Make sure that after reading things are still valid
    // If so then the line is good and continue
    if (ss.fail() == true) {
      break;
    }
    data.push_back(v);
  }
}

int main(int argc, char* argv[]) {
  COO D_T, M_invD;
  std::vector<double> gamma;
  std::cout << " Read in data to sparse COO structure: \n";
  start = std::chrono::system_clock::now();
  ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
  ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
  ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to read data from file: " << elapsed.count();

  start = std::chrono::system_clock::now();
  blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Blaze: " << elapsed.count();

  start = std::chrono::system_clock::now();
  blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load M_invD Blaze: " << elapsed.count();

  blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);

  {
    std::cout << "Blaze Test:\n";
    BlazeTest blaze_test;
    start = std::chrono::system_clock::now();
    blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
    end = std::chrono::system_clock::now();
    elapsed = end - start;
    std::cout << "Blaze Time: " << elapsed.count();
  }

  std::cout << "Eigen Convert:\n";
  // Convert the COO into Eigen triplets
  // Timing this part isn't important, in practice you would not need to do this
  std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
  std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);

  start = std::chrono::system_clock::now();
  Eigen::SparseMatrix<double> D_T_eigen = EigenTest::ConvertMatrix(D_T_triplet, D_T);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Eigen: " << elapsed.count();

  start = std::chrono::system_clock::now();
  Eigen::SparseMatrix<double> M_invD_eigen = EigenTest::ConvertMatrix(M_invD_triplet, M_invD);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Eigen: " << elapsed.count();

  Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);

  {
    std::cout << "Eigen Test:\n";
    start = std::chrono::system_clock::now();
    EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
    end = std::chrono::system_clock::now();
    elapsed = end - start;
    std::cout << "Eigen Time: " << elapsed.count();
  }

  //
  //  {
  //    VexCLTest vexcl_test;
  //    vexcl_test.CreateContext();
  //    vexcl_test.WarmUp();
  //    CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
  //    CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
  //    vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
  //    vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
  //    vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
  //
  //    start = std::chrono::system_clock::now();
  //    vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
  //    end = std::chrono::system_clock::now();
  //    vexcl_time = end - start;
  //  }

  //
  //  // Compute some metrics and print them out
  //  num_rows = D_T_blaze.rows();
  //  num_cols = D_T_blaze.columns();
  //  num_nonzeros = D_T_blaze.nonZeros();
  //  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
  //  printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
  //         ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
  //
  //  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  //  printf("b: size: %d\n", rhs_blaze.size());

  //
  //  {
  //    ViennaCLTest viennacl_test;
  //    viennacl_test.WarmUp();
  //
  //    viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
  //    viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
  //    viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
  //
  //    start = std::chrono::system_clock::now();
  //    viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
  //    end = std::chrono::system_clock::now();
  //    vcl_time = end - start;
  //  }
  //

  //
  //  // Two Spmv each with 2*nnz operations
  //  uint operations = 2 * 2 * num_nonzeros;
  //  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
  //
  //  double blaze_single = blaze_time.count() / RUNS;
  //  double vex_single = vexcl_time.count() / RUNS;
  //  double vcl_single = vcl_time.count() / RUNS;
  //  // double eig_single = eigen_time.count() / RUNS;
  //
  //  printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
  //  printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
  //  printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
  //
  //  //  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  //  //  printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
  //  //         moved / vex_single / GFLOP);
  //  //  //
  //  //  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
  //  //  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
  //  //  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
  //  //  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
  //  //
  //  //  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
  //  //  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<commit_msg>Add some endless after text output<commit_after>#include "main.h"
#include <chrono>

int num_rows;
int num_cols;
int num_nonzeros;

std::chrono::duration<double> blaze_time;
std::chrono::duration<double> vcl_time;
std::chrono::duration<double> vexcl_time;
std::chrono::duration<double> elapsed;
std::chrono::time_point<std::chrono::system_clock> start, end;

#include "utils.h"

void ReadSparse(COO& data, const std::string filename) {
  std::cout << "Reading: " << filename << std::endl;
  std::stringstream ss(ReadFileAsString(filename));
  size_t i, j;
  double v;

  while (true) {
    ss >> i;
    // Make sure that after reading things are still valid
    // If so then the line is good and continue
    if (ss.fail() == true) {
      break;
    }
    ss >> j >> v;
    data.row.push_back(i);
    data.col.push_back(j);
    data.val.push_back(v);
  }
  data.update();
}

void ReadVector(std::vector<double>& data, const std::string filename) {
  std::cout << "Reading: " << filename << std::endl;
  std::stringstream ss(ReadFileAsString(filename));
  double v;

  while (true) {
    ss >> v;
    // Make sure that after reading things are still valid
    // If so then the line is good and continue
    if (ss.fail() == true) {
      break;
    }
    data.push_back(v);
  }
}

int main(int argc, char* argv[]) {
  COO D_T, M_invD;
  std::vector<double> gamma;
  std::cout << "Read in data to sparse COO structure: \n";
  start = std::chrono::system_clock::now();
  ReadSparse(D_T, "D_T_" + std::string(argv[1]) + ".mat");
  ReadSparse(M_invD, "M_invD_" + std::string(argv[1]) + ".mat");
  ReadVector(gamma, "gamma_" + std::string(argv[1]) + ".mat");
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to read data from file: " << elapsed.count()<<std::endl;

  start = std::chrono::system_clock::now();
  blaze::CompressedMatrix<double> D_T_blaze = BlazeTest::ConvertMatrix(D_T);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Blaze: " << elapsed.count()<<std::endl;

  start = std::chrono::system_clock::now();
  blaze::CompressedMatrix<double> M_invD_blaze = BlazeTest::ConvertMatrix(M_invD);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load M_invD Blaze: " << elapsed.count()<<std::endl;

  blaze::DynamicVector<double> gamma_blaze = BlazeTest::ConvertVector(gamma);

  {
    std::cout << "Blaze Test:\n";
    BlazeTest blaze_test;
    start = std::chrono::system_clock::now();
    blaze_test.RunSPMV(D_T_blaze, M_invD_blaze, gamma_blaze);
    end = std::chrono::system_clock::now();
    elapsed = end - start;
    std::cout << "Blaze Time: " << elapsed.count()<<std::endl;
  }

  std::cout << "Eigen Triplet:\n";
  // Convert the COO into Eigen triplets
  // Timing this part isn't important, in practice you would not need to do this
  std::vector<Eigen::Triplet<double> > D_T_triplet = EigenTest::ConvertCOO(D_T);
  std::vector<Eigen::Triplet<double> > M_invD_triplet = EigenTest::ConvertCOO(M_invD);
  std::cout << "Eigen Convert:\n";
  start = std::chrono::system_clock::now();
  Eigen::SparseMatrix<double> D_T_eigen = EigenTest::ConvertMatrix(D_T_triplet, D_T);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Eigen: " << elapsed.count()<<std::endl;

  start = std::chrono::system_clock::now();
  Eigen::SparseMatrix<double> M_invD_eigen = EigenTest::ConvertMatrix(M_invD_triplet, M_invD);
  end = std::chrono::system_clock::now();
  elapsed = end - start;
  std::cout << "Time to load D_T Eigen: " << elapsed.count()<<std::endl;

  Eigen::VectorXd gamma_eigen = EigenTest::ConvertVector(gamma);

  {
    std::cout << "Eigen Test:\n";
    start = std::chrono::system_clock::now();
    EigenTest::RunSPMV(D_T_eigen, M_invD_eigen, gamma_eigen);
    end = std::chrono::system_clock::now();
    elapsed = end - start;
    std::cout << "Eigen Time: " << elapsed.count()<<std::endl;
  }

  //
  //  {
  //    VexCLTest vexcl_test;
  //    vexcl_test.CreateContext();
  //    vexcl_test.WarmUp();
  //    CSR D_T_csr = BlazeTest::ConvertSparse(D_T_blaze);
  //    CSR M_invD_csr = BlazeTest::ConvertSparse(M_invD_blaze);
  //    vex::SpMat<double> D_T_vex = vexcl_test.ConvertMatrix(D_T_csr);
  //    vex::SpMat<double> M_invD_vex = vexcl_test.ConvertMatrix(M_invD_csr);
  //    vex::vector<double> gamma_vex = vexcl_test.ConvertVector(gamma);
  //
  //    start = std::chrono::system_clock::now();
  //    vexcl_test.RunSPMV(D_T_vex, M_invD_vex, gamma_vex);
  //    end = std::chrono::system_clock::now();
  //    vexcl_time = end - start;
  //  }

  //
  //  // Compute some metrics and print them out
  //  num_rows = D_T_blaze.rows();
  //  num_cols = D_T_blaze.columns();
  //  num_nonzeros = D_T_blaze.nonZeros();
  //  printf("D_T: rows:, columns:, non zeros:,M_invD: rows:, columns:, non zeros:, gamma: size:, b: size: Memory\n");
  //  printf("%d, %d, %d, %d, %d, %d, %d, %d %f\n", num_rows, num_cols, num_nonzeros, M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros(), gamma_blaze.size(), rhs_blaze.size(),
  //         ((num_nonzeros + M_invD_blaze.nonZeros() + gamma_blaze.size() + rhs_blaze.size()) / double(GFLOP)) * sizeof(double) );
  //
  //  //  printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T_blaze.rows(), D_T_blaze.columns(), D_T_blaze.nonZeros());
  //  //  printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD_blaze.rows(), M_invD_blaze.columns(), M_invD_blaze.nonZeros());
  //  //  printf("gamma: size: %d\n", gamma_blaze.size());
  //  //  printf("b: size: %d\n", rhs_blaze.size());

  //
  //  {
  //    ViennaCLTest viennacl_test;
  //    viennacl_test.WarmUp();
  //
  //    viennacl::compressed_matrix<double> D_T_vcl = viennacl_test.ConvertMatrix(D_T_csr);
  //    viennacl::compressed_matrix<double> M_invD_vcl = viennacl_test.ConvertMatrix(M_invD_csr);
  //    viennacl::vector<double> gamma_vcl = viennacl_test.ConvertVector(gamma_blaze);
  //
  //    start = std::chrono::system_clock::now();
  //    viennacl_test.RunSPMV(D_T_vcl, M_invD_vcl, gamma_vcl);
  //    end = std::chrono::system_clock::now();
  //    vcl_time = end - start;
  //  }
  //

  //
  //  // Two Spmv each with 2*nnz operations
  //  uint operations = 2 * 2 * num_nonzeros;
  //  uint moved = 2 * (num_nonzeros + 2 * num_rows) * sizeof(double);
  //
  //  double blaze_single = blaze_time.count() / RUNS;
  //  double vex_single = vexcl_time.count() / RUNS;
  //  double vcl_single = vcl_time.count() / RUNS;
  //  // double eig_single = eigen_time.count() / RUNS;
  //
  //  printf("Blaze: %f %f %f", blaze_single, operations / blaze_single / GFLOP, moved / blaze_single / GFLOP);
  //  printf("VexCL: %f %f %f", vex_single, operations / vex_single / GFLOP, moved / vex_single / GFLOP);
  //  printf("VCL: %f %f %f", vcl_single, operations / vcl_single / GFLOP, moved / vcl_single / GFLOP);
  //
  //  //  printf("Blaze sec, VexCL sec, Speedup, Blaze Flops, VexCL Flops, Bandwidth Blaze, Bandwidth VexCL \n");
  //  //  printf("%f, %f, %f, %f, %f, %f, %f\n", blaze_single, vex_single, blaze_single / vex_single, operations / blaze_single / GFLOP, operations / vex_single / GFLOP, moved / blaze_single / GFLOP,
  //  //         moved / vex_single / GFLOP);
  //  //  //
  //  //  printf("Blaze %f sec. Eigen %f sec. VexCL %f sec.\n", blaze_single, eig_single, vex_single);
  //  //  printf("Speedup: Blaze vs Eigen %f\n", blaze_single / eig_single);
  //  //  printf("Speedup: Blaze vs VexCL %f\n", blaze_single / vex_single);
  //  //  printf("Speedup: Eigen vs VexCL %f\n", eig_single / vex_single);
  //  //
  //  //  printf("Flops: Blaze %f Eigen %f VexCL %f\n", operations / blaze_single / GFLOP, operations / eig_single / GFLOP, operations / vex_single / GFLOP);
  //  //  printf("Bandwidth: Blaze %f Eigen %f VexCL %f\n", moved / blaze_single / GFLOP, moved / eig_single / GFLOP, moved / vex_single / GFLOP);

  return 0;
}
<|endoftext|>


<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
//#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

bool checkShaderCompileStatus(GLuint obj) {
  GLint status;
  glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetShaderInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

bool checkProgramLinkStatus(GLuint obj) {
  GLint status;
  glGetProgramiv(obj, GL_LINK_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetProgramInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

GLuint prepareProgram(bool *errorFlagPtr) {
  *errorFlagPtr = false;

  std::string vertexShaderSource = ""
          "#version 330 core\n"
          "layout(location = 0) in vec3 vertexPosition_modelspace;\n"
          "void main(){\n"
          "  gl_Position.xyz = vertexPosition_modelspace;\n"
          "  gl_Position.w = 1.0;\n"
          "}";

  GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
  char const * vertexShaderSourcePtr = vertexShaderSource.c_str();
  glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
  glCompileShader(vertexShaderId);

  *errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
  if(*errorFlagPtr) return 0;

  std::string fragmentShaderSource = ""
          "#version 330 core\n"
          "out vec3 color;\n"
          "void main() { color = vec3(1,0,0); }\n";

  GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
  char const * fragmentShaderSourcePtr = fragmentShaderSource.c_str();
  glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
  glCompileShader(fragmentShaderId);

  *errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
  if(*errorFlagPtr) return 0;

  GLuint programId = glCreateProgram();
  glAttachShader(programId, vertexShaderId);
  glAttachShader(programId, fragmentShaderId);
  glLinkProgram(programId);

  *errorFlagPtr = checkProgramLinkStatus(programId);
  if(*errorFlagPtr) return 0;

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  return programId;
}

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    glfwDestroyWindow(window);
    glfwTerminate();
    return 1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

//  glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
//  glMatrixMode(GL_PROJECTION);
//  glLoadMatrixf(glm::value_ptr(m));

  bool errorFlag;
  GLuint programId = prepareProgram(&errorFlag);
  if(errorFlag) {
    glfwDestroyWindow(window);
    glfwTerminate();
    return -1;
  }

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            nullptr             // array buffer offset
    );

    // Draw the triangle !
    glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle

    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);

//  glDetachShader(shader_program, vertex_shader);
//  glDetachShader(shader_program, fragment_shader);
//  glDeleteShader(vertex_shader);
//  glDeleteShader(fragment_shader);

  glDeleteProgram(programId);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}<commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
//#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

bool checkShaderCompileStatus(GLuint obj) {
  GLint status;
  glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetShaderInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

bool checkProgramLinkStatus(GLuint obj) {
  GLint status;
  glGetProgramiv(obj, GL_LINK_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetProgramInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

GLuint prepareProgram(bool *errorFlagPtr) {
  *errorFlagPtr = false;

  std::string vertexShaderSource = ""
          "#version 330 core\n"
          "layout(location = 0) in vec3 vertexPosition_modelspace;\n"
          "void main(){\n"
          "  gl_Position.xyz = vertexPosition_modelspace;\n"
          "  gl_Position.w = 1.0;\n"
          "}";

  GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
  const GLchar * const vertexShaderSourcePtr = vertexShaderSource.c_str();
  glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
  glCompileShader(vertexShaderId);

  *errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
  if(*errorFlagPtr) return 0;

  std::string fragmentShaderSource = ""
          "#version 330 core\n"
          "out vec3 color;\n"
          "void main() { color = vec3(1,0,0); }\n";

  GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
  const GLchar * const fragmentShaderSourcePtr = fragmentShaderSource.c_str();
  glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
  glCompileShader(fragmentShaderId);

  *errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
  if(*errorFlagPtr) return 0;

  GLuint programId = glCreateProgram();
  glAttachShader(programId, vertexShaderId);
  glAttachShader(programId, fragmentShaderId);
  glLinkProgram(programId);

  *errorFlagPtr = checkProgramLinkStatus(programId);
  if(*errorFlagPtr) return 0;

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  return programId;
}

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    glfwDestroyWindow(window);
    glfwTerminate();
    return 1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

//  glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
//  glMatrixMode(GL_PROJECTION);
//  glLoadMatrixf(glm::value_ptr(m));

  bool errorFlag;
  GLuint programId = prepareProgram(&errorFlag);
  if(errorFlag) {
    glfwDestroyWindow(window);
    glfwTerminate();
    return -1;
  }

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            nullptr             // array buffer offset
    );

    // Draw the triangle !
    glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle

    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}<|endoftext|>


<commit_before>// PDTK
#include <application.h>
#include <cxxutils/syslogstream.h>

// project
#include "configserver.h"

constexpr const char* const appname = "SXconfigd";
constexpr const char* const username = "config";

void exiting(void)
{
  posix::syslog << posix::priority::notice << "daemon has exited." << posix::eom;
}

int main(int argc, char *argv[]) noexcept
{
  (void)argc;
  (void)argv;
  ::atexit(exiting);

  posix::syslog.open(appname, posix::facility::daemon);
  if(posix::getusername(::getuid()) != username)
  {
    posix::syslog << posix::priority::critical << "daemon must be launched as username " << '"' << username << '"' << posix::eom;
    ::exit(-1);
  }

  Application app;
  ConfigServer server(username, "file_monitor");

  return app.exec();
}

#if 0
// STL
#include <iostream>

// C++
#include <cassert>

// PDTK
#include <cxxutils/configmanip.h>

int main(int argc, char *argv[]) noexcept
{
  std::string data = "[config]\nkey=original value\n # ORLY?\nKey = Value; yeah rly\n/config/key=\"overwritten\"; stuff\n[config]key=\"oh my\"\n";
  ConfigManip conf;
  assert(conf.read(data));

  std::string dout;
  assert(conf.write(dout));
  std::cout << "OUTPUT" << std::endl << '"' << dout << '"' << std::endl;
  //return 0;

  auto node = conf.findNode("/config/1/key");
  if(node != nullptr)
    std::cout << "node: " << '"' << node->value << '"' << std::endl;
  else
    std::cout << "not found!" << std::endl;
  return 0;
}
#endif
<commit_msg>socket demo code<commit_after>// PDTK
#include <application.h>
#include <object.h>
#include <cxxutils/syslogstream.h>

// project
#include "configserver.h"

constexpr const char* const appname = "SXconfigd";
constexpr const char* const username = "config";

void exiting(void)
{
  posix::syslog << posix::priority::notice << "daemon has exited." << posix::eom;
}

void allfunc(void)
{
  posix::syslog << "tada!" << posix::eom;
}

int main(int argc, char *argv[]) noexcept
{
  (void)argc;
  (void)argv;
  ::atexit(exiting);

  posix::syslog.open(appname, posix::facility::daemon);
  if(posix::getusername(::getuid()) != username)
  {
    posix::syslog << posix::priority::critical << "daemon must be launched as username " << '"' << username << '"' << posix::eom;
    ::exit(-1);
  }

  Application app;
  ConfigServer server(username, "file_monitor");

  Object::connect(server.getAllCall, allfunc);

  return app.exec();
}

#if 0
// STL
#include <iostream>

// C++
#include <cassert>

// PDTK
#include <cxxutils/configmanip.h>

int main(int argc, char *argv[]) noexcept
{
  std::string data = "[config]\nkey=original value\n # ORLY?\nKey = Value; yeah rly\n/config/key=\"overwritten\"; stuff\n[config]key=\"oh my\"\n";
  ConfigManip conf;
  assert(conf.read(data));

  std::string dout;
  assert(conf.write(dout));
  std::cout << "OUTPUT" << std::endl << '"' << dout << '"' << std::endl;
  //return 0;

  auto node = conf.findNode("/config/1/key");
  if(node != nullptr)
    std::cout << "node: " << '"' << node->value << '"' << std::endl;
  else
    std::cout << "not found!" << std::endl;
  return 0;
}
#endif
<|endoftext|>