<commit_before>// Copyright (c) 2016 Ansho Enigu
#include "crypto/lamport.h"

#include "crypto/ripemd160.h"
#include "crypto/common.h"
#include "uint256.h"
bool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[])
{

  char exmerklewit[8][20]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/
  char pubkey[20][2][20];
  bool merklecheckfin = false;

  //start converting merkle wit to exmerklewit and public key
  char merklebuffer[800]; //size of publickey is the max size of the buffer
  unsigned int i;
  for(i = 0; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/
      break;
    merklebuffer[i] = merklewit[i];
  }

  memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer));
  int o = 0;
  int r = 0; //number of times we have reset o count
  for(; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)
    {
      memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer));
      r++;
      i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle
      o = 0;
    }
    else
    {
      merklebuffer[o] = merklewit[i];
      o++;
    }
  }
  //end decoding merkle wit format

  //start checking if new publickey is a part of the root key
  for(int i = 0; !merklecheckfin; i++) //to end if false we will use return to lower processing time
  {
    return false;
  }
  //end checking if new publickey is a part of the root key

  /*
      unsigned char* datapart;
      unsigned char[(160/LAMPORT::chuncksize)]* datahashs;
      for(int i = 0; i < (160/LAMPORT::chuncksize); i++)
      {

        for(int o = 0; o < chuncksizeinbyte; o++)
        {
          datapart[o] = data[(i * LAMPORT::chuncksize) + o];
        }

        CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i]));
      }
      */
      return true; // if compleats all tests return true
}
    char *LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey)
    {
      /* the signing will happen under this */

      return &sig;
    }
<commit_msg>Update lamport.cpp<commit_after>// Copyright (c) 2016 Ansho Enigu
#include "crypto/lamport.h"

#include "crypto/ripemd160.h"
#include "crypto/common.h"
#include "uint256.h"
bool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[])
{

  char exmerklewit[8][20]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/
  char pubkey[20][2][20];
  bool merklecheckfin = false;

  //start converting merkle wit to exmerklewit and public key
  char merklebuffer[800]; //size of publickey is the max size of the buffer
  unsigned int i;
  for(i = 0; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/
      break;
    merklebuffer[i] = merklewit[i];
  }

  memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer));
  int o = 0;
  int r = 0; //number of times we have reset o count
  for(; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)
    {
      memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer));
      r++;
      i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle
      o = 0;
    }
    else
    {
      merklebuffer[o] = merklewit[i];
      o++;
    }
  }
  //end decoding merkle wit format

  //start checking if new publickey is a part of the root key
  for(int i = 0; !merklecheckfin; i++) //to end if false we will use return to lower processing time
  {
    return false;
  }
  //end checking if new publickey is a part of the root key

  /*
      unsigned char* datapart;
      unsigned char[(160/LAMPORT::chuncksize)]* datahashs;
      for(int i = 0; i < (160/LAMPORT::chuncksize); i++)
      {

        for(int o = 0; o < chuncksizeinbyte; o++)
        {
          datapart[o] = data[(i * LAMPORT::chuncksize) + o];
        }

        CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i]));
      }
      */
      return true; // if compleats all tests return true
}
    char *LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey)
    {
      /* the signing will happen under this */
      char* sigpoint = sig;
      return sigpoint;
    }
<|endoftext|>


<commit_before>
#include "ImguiWindowsFileIO.hpp"

#include <algorithm>
#include <cstdlib>
#include <sstream>

#include <iostream>

#if defined(WIN32)
    #include <windows.h>
    #include <direct.h>
    #include <tchar.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

#define IM_ARRAYSIZE(_ARR)  ((int)(sizeof(_ARR)/sizeof(*_ARR)))

#if defined(ICON_FA_CARET_DOWN)
    #define CARET_DOWN ICON_FA_CARET_DOWN
#else
    #define CARET_DOWN "v"
#endif

using namespace std;
using namespace ImGui;

#if defined(WIN32)
vector<string> getWindowsDrives()
{
    vector<string> result;
    TCHAR g_szDrvMsg[] = _T("A:");

    ULONG uDriveMask = _getdrives();

    if (uDriveMask == 0)
    {}
    else
    {
        while (uDriveMask)
        {
            if (uDriveMask & 1)
                result.push_back( g_szDrvMsg );

            ++g_szDrvMsg[0];
            uDriveMask >>= 1;
        }
   }

    return result;
}
#endif

vector<string> stringSplit(const string &s, char delim)
{
vector<string> elems;
string item;

// use stdlib to tokenize the string
stringstream ss(s);
    while (getline(ss, item, delim))
        if(!item.empty())
        {
            elems.push_back(item);
        }

    return elems;
}

string MiniPath::filePath() const
{
    return path + name;
}

void MiniPath::fromString (const string& file_path, char delim)
{
    int last_delim_pos = file_path.find_last_of (delim);
    name = file_path.substr (last_delim_pos+1);
    path = file_path.substr (0, last_delim_pos+1);
}

MiniPath::MiniPath()
{}

MiniPath::MiniPath( const string& some_path )
{
    string s = some_path;
    if (MiniPath::isAbsoluteFilePath (s))
    {
        if (s.find ("/") != string::npos) // linux style
            fromString (s ,'/');
        else if (s.find ("\\") != string::npos) // windows style
            fromString (s ,'\\');
    }
    else
    {
        string current = MiniPath::getCurrentDir();

        if (current.find ("/") != string::npos)
        {
            std::replace( s.begin(), s.end(), '\\', '/');
            fromString (current + "/" + s ,'/');
        }
        else if (current.find ("\\") != string::npos)
        {
            std::replace( s.begin(), s.end(), '/', '\\');
            fromString (current + "\\" + s ,'\\');
        }
        else
            fromNameInCurrentDir( s );
    }
}

string MiniPath::getDelim() const
{
    if (path.find ("/") != string::npos) // linux style
            return "/";
    else if (path.find ("\\") != string::npos) // windows style
            return "\\";
    else
    {
        return MiniPath::getSystemDelim();
    }
}

std::string MiniPath::getSystemDelim()
{
        string current = MiniPath::getCurrentDir();
        if (current.find ("/") != string::npos) // linux style
            return "/";
        else if (current.find ("\\") != string::npos) // windows style
            return "\\";
        else
            return "/";
}

string MiniPath::prefix() const
{
    return name.substr (0, name.find_last_of ('.'));
}

string MiniPath::extension() const
{
    if (name.find (".") == string::npos)
        return "";

    return name.substr (name.find_last_of ('.')+1);
}

string MiniPath::getCurrentDir()
{
    char cCurrentPath[FILENAME_MAX];
    if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
        return 0;
    cCurrentPath[sizeof(cCurrentPath) - 1] = '\0';
    return string (cCurrentPath);
}

void MiniPath::fromNameInCurrentDir( const string& file_name )
{
    path = getCurrentDir();
    name = file_name;
}

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

string MiniPath::getPath() const
{
    return path;
}

vector<string> MiniPath::getPathTokens() const
{
    if( !getDelim().empty() )
        return stringSplit( path + getDelim(), getDelim()[0] );

    vector<string> tmp;
    return tmp;
}

void MiniPath::setName( const string& name )
{
    string tmp;
    unsigned last_delim_pos = name.find_last_of ('/');
    if( last_delim_pos != string::npos )
        tmp = name.substr (last_delim_pos+1);
    else
        tmp = name;

    unsigned last_delim_pos2 = tmp.find_last_of ('\\');
    if( last_delim_pos2 != string::npos )
        tmp = tmp.substr (last_delim_pos2+1);

    this->name = tmp;
}

bool MiniPath::setPath( const string& absolut_path )
{
    if (isAbsoluteFilePath( absolut_path ))
    {
        path = absolut_path;
        return true;
    }
    return false;
}

bool MiniPath::isAbsoluteFilePath( const string& s )
{
    if (s.size() > 0)
    {
        if (s.at(0) == '/' || s.at(1) == ':')
            return true;
        else
            return false;
    }
    else
        return false;
}

std::list<string> MiniPath::listDirectories( const string& s )
{
    list<string> directories;

    struct _finddata_t c_file;
    intptr_t hFile;

    string filter = s + MiniPath::getSystemDelim() + "*.*";

    if( (hFile = _findfirst( filter.c_str(), &c_file )) == -1L )
    {}
    else
    {
        do
        {
            char buffer[256];
            if( ( c_file.attrib & _A_SUBDIR ) )
                directories.push_back( string( c_file.name ) );
        } while( _findnext( hFile, &c_file ) == 0 );
    }

    return directories;
}

std::list<string> MiniPath::listFiles( const string& s, string filter )
{
    list<string> files;

    struct _finddata_t c_file;
    intptr_t hFile;

    string find_filter = s + MiniPath::getSystemDelim() + filter;

    if( (hFile = _findfirst( find_filter.c_str(), &c_file )) == -1L )
    {}
    else
    {
        do
        {
            char buffer[256];
            if( !( c_file.attrib & _A_SUBDIR ) )
                files.push_back( string( c_file.name ) );
        } while( _findnext( hFile, &c_file ) == 0 );
    }

    return files;
}

bool MiniPath::pathExists( const std::string& s )
{
    struct _finddata_t c_file;
    intptr_t hFile;

    if( (hFile = _findfirst( s.c_str(), &c_file )) != -1L )
        return true;

    return false;
}

vector<const char*> toCStringVec( const vector<string>& vs )
{
    std::vector<const char*> tmp;
    for( const string& s : vs )
        tmp.push_back( s.c_str() );
    return tmp;
}

vector<const char*> toCStringVec( const list<string>& vs )
{
    std::vector<const char*> tmp;
    for( const string& s : vs )
        tmp.push_back( s.c_str() );
    return tmp;
}

bool fileIOWindow(
    string& file_path,
    std::vector<string>& recently_used_files,
    const string& button_text,
    std::vector<std::string> file_filter,
    bool ensure_file_exists,
    ImVec2 size )
{
    bool close_it = false;

    vector<const char*> extension_cstrings = toCStringVec( file_filter );

    static string current_folder = "x";
    static char c_current_folder[ 2048 ];

    if( current_folder == "x" )
        current_folder = MiniPath::getCurrentDir();

    static char current_file[ 256 ] = "Test.usr";
    static int  file_type_selected = 0;
    static int  file_selected = 0;
    static int  directory_selected = 0;
    static int  drive_selected = 0;
    static bool directory_browsing = false;
    static int  recent_selected = 0;

    string sys_delim = MiniPath::getSystemDelim();

    string tmp = current_folder + sys_delim + current_file;
    MiniPath current_mini_path( tmp );

    list<string> directories = MiniPath::listDirectories( current_mini_path.getPath() );
    std::vector<const char*> dir_list;
    for( const string& s : directories )
    {
        if( s == "." ) continue;
        dir_list.push_back( s.c_str() );
    }

    list<string> local_files = MiniPath::listFiles( current_mini_path.getPath(), string( extension_cstrings[file_type_selected] ) );
    vector<const char*> file_list = toCStringVec( local_files );

    if ( directory_browsing )
        size.y += std::min( size_t( 8 ), std::max( dir_list.size(), file_list.size() ) ) *  GetFontSize();

    SetNextWindowSize( size );
    Begin( "FileIO" );

    Text("Directory: "); SameLine();
    PushItemWidth( GetWindowWidth() - 145 );

    strcpy( c_current_folder, current_folder.c_str() );
    if( InputText( " ", c_current_folder, IM_ARRAYSIZE( c_current_folder ) ) )
    {
        string tmp = c_current_folder;
        if( MiniPath::pathExists( tmp ) )
            current_folder = c_current_folder;
    }
    SameLine();

    std::vector<const char*> recent = toCStringVec( recently_used_files );

    if( Button(" " CARET_DOWN " ") )
        ImGui::OpenPopup("RecentFiles");

    if (ImGui::BeginPopup("RecentFiles"))
    {
        if( ListBox( "", &recent_selected, recent.data(), recent.size() ) )
        {
            current_mini_path.fromString( string( recent[recent_selected] ), sys_delim[0] );
            if( !current_mini_path.getName().empty() )
                strcpy( current_file, current_mini_path.getName().c_str() );
            current_folder = current_mini_path.getPath();
            CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }

    Text("           "); SameLine();
    vector<string> split_directories = current_mini_path.getPathTokens();
    for( int i = 0; i < split_directories.size(); ++i )
    {
        if( Button( split_directories[i].c_str() ) )
        {
            string chosen_dir;
            for( int j ; j <= i; ++j)
            {
                chosen_dir += split_directories[j];
                if( j != i )
                    chosen_dir += sys_delim;
            }
            current_folder = chosen_dir;
        }
        if( i != split_directories.size()-1 )
            SameLine();
    }

    if( CollapsingHeader("Browse Directories") )
    {
        directory_browsing = true;

#if defined(WIN32)
        vector<const char*> drive_list = toCStringVec( getWindowsDrives() );

        Text( "  " ); SameLine();
        PushItemWidth( 40 );
        if( ListBox( "  ", &drive_selected, drive_list.data(), drive_list.size() ) )
        {
            string new_path = drive_list[drive_selected];
            current_folder = new_path;
        }
#else
        Text( "           " );
#endif
        SameLine();

        PushItemWidth( GetWindowWidth()/2 - 60 );
        if( ListBox( " ", &directory_selected, dir_list.data(), dir_list.size() ) )
        {
            string new_path;

            if( string(dir_list[directory_selected]).find( ".." ) != std::string::npos )
            {
                vector<string> split_directories = current_mini_path.getPathTokens();
                current_folder.clear();
                for( int i = 0; i < split_directories.size() - 1; ++i )
                {
                    current_folder += split_directories[i];
                    if( i < split_directories.size() - 2 )
                        current_folder += sys_delim;
                }
            }
            else
                current_folder = current_folder + sys_delim + dir_list[directory_selected];
        }

        SameLine();
        PushItemWidth( GetWindowWidth()/2 - 60 );
        if( ListBox( "", &file_selected, file_list.data(), file_list.size() ) )
        {
            strcpy( current_file, file_list[file_selected] );
        }
    }
    else
         directory_browsing = false;

    Text(" ");

    Text("File Name: "); SameLine();
    InputText( "  ", current_file, IM_ARRAYSIZE( current_file ) );

    Text( "File Type: " ); SameLine(); Text( extension_cstrings[file_type_selected] ); SameLine();
    if (Button( CARET_DOWN ) )
        ImGui::OpenPopup("FileType");

    if (ImGui::BeginPopup("FileType"))
    {
        if( ListBox( "", &file_type_selected, extension_cstrings.data(), extension_cstrings.size() ) )
        {
            CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }

    ImVec2 pos = GetCursorPos();

    pos.x += GetWindowWidth() - 75 - button_text.size() * ( GetFontSize() * 0.7 );
    pos.y  = GetWindowHeight() - 30;

    SetCursorPos( pos );
    if( Button( button_text.c_str() ) )
    {
        vector<string> ext_filter_v = stringSplit( extension_cstrings[file_type_selected], '.');
        if( ext_filter_v.size() == 2 &&
            ext_filter_v[1] != "*" )
        {
            string ext_filter = ext_filter_v[1];
            if( current_mini_path.extension() == ext_filter )
                file_path = current_mini_path.filePath();
        }
        else
            file_path = current_mini_path.filePath();

        if( ensure_file_exists )
        {
            if( MiniPath::pathExists( file_path ) )
                close_it = true;
        }
        else
            close_it = true;
    }

    SameLine();
    if( Button( "Cancel" ) )
        close_it = true;
    End();

    return close_it;
}
<commit_msg>fix deleted initialization<commit_after>#include "ImguiWindowsFileIO.hpp"

#include <algorithm>
#include <cstdlib>
#include <sstream>

#if defined(WIN32)
    #include <windows.h>
    #include <direct.h>
    #include <tchar.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

#define IM_ARRAYSIZE(_ARR)  ((int)(sizeof(_ARR)/sizeof(*_ARR)))

#if defined(ICON_FA_CARET_DOWN)
    #define CARET_DOWN ICON_FA_CARET_DOWN
#else
    #define CARET_DOWN "v"
#endif

using namespace std;
using namespace ImGui;

#if defined(WIN32)
vector<string> getWindowsDrives()
{
    vector<string> result;
    TCHAR g_szDrvMsg[] = _T("A:");

    ULONG uDriveMask = _getdrives();

    if (uDriveMask == 0)
    {}
    else
    {
        while (uDriveMask)
        {
            if (uDriveMask & 1)
                result.push_back( g_szDrvMsg );

            ++g_szDrvMsg[0];
            uDriveMask >>= 1;
        }
   }

    return result;
}
#endif

vector<string> stringSplit(const string &s, char delim)
{
vector<string> elems;
string item;

// use stdlib to tokenize the string
stringstream ss(s);
    while (getline(ss, item, delim))
        if(!item.empty())
        {
            elems.push_back(item);
        }

    return elems;
}

string MiniPath::filePath() const
{
    return path + name;
}

void MiniPath::fromString (const string& file_path, char delim)
{
    int last_delim_pos = file_path.find_last_of (delim);
    name = file_path.substr (last_delim_pos+1);
    path = file_path.substr (0, last_delim_pos+1);
}

MiniPath::MiniPath()
{}

MiniPath::MiniPath( const string& some_path )
{
    string s = some_path;
    if (MiniPath::isAbsoluteFilePath (s))
    {
        if (s.find ("/") != string::npos) // linux style
            fromString (s ,'/');
        else if (s.find ("\\") != string::npos) // windows style
            fromString (s ,'\\');
    }
    else
    {
        string current = MiniPath::getCurrentDir();

        if (current.find ("/") != string::npos)
        {
            std::replace( s.begin(), s.end(), '\\', '/');
            fromString (current + "/" + s ,'/');
        }
        else if (current.find ("\\") != string::npos)
        {
            std::replace( s.begin(), s.end(), '/', '\\');
            fromString (current + "\\" + s ,'\\');
        }
        else
            fromNameInCurrentDir( s );
    }
}

string MiniPath::getDelim() const
{
    if (path.find ("/") != string::npos) // linux style
            return "/";
    else if (path.find ("\\") != string::npos) // windows style
            return "\\";
    else
    {
        return MiniPath::getSystemDelim();
    }
}

std::string MiniPath::getSystemDelim()
{
        string current = MiniPath::getCurrentDir();
        if (current.find ("/") != string::npos) // linux style
            return "/";
        else if (current.find ("\\") != string::npos) // windows style
            return "\\";
        else
            return "/";
}

string MiniPath::prefix() const
{
    return name.substr (0, name.find_last_of ('.'));
}

string MiniPath::extension() const
{
    if (name.find (".") == string::npos)
        return "";

    return name.substr (name.find_last_of ('.')+1);
}

string MiniPath::getCurrentDir()
{
    char cCurrentPath[FILENAME_MAX];
    if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
        return 0;
    cCurrentPath[sizeof(cCurrentPath) - 1] = '\0';
    return string (cCurrentPath);
}

void MiniPath::fromNameInCurrentDir( const string& file_name )
{
    path = getCurrentDir();
    name = file_name;
}

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

string MiniPath::getPath() const
{
    return path;
}

vector<string> MiniPath::getPathTokens() const
{
    if( !getDelim().empty() )
        return stringSplit( path + getDelim(), getDelim()[0] );

    vector<string> tmp;
    return tmp;
}

void MiniPath::setName( const string& name )
{
    string tmp;
    unsigned last_delim_pos = name.find_last_of ('/');
    if( last_delim_pos != string::npos )
        tmp = name.substr (last_delim_pos+1);
    else
        tmp = name;

    unsigned last_delim_pos2 = tmp.find_last_of ('\\');
    if( last_delim_pos2 != string::npos )
        tmp = tmp.substr (last_delim_pos2+1);

    this->name = tmp;
}

bool MiniPath::setPath( const string& absolut_path )
{
    if (isAbsoluteFilePath( absolut_path ))
    {
        path = absolut_path;
        return true;
    }
    return false;
}

bool MiniPath::isAbsoluteFilePath( const string& s )
{
    if (s.size() > 0)
    {
        if (s.at(0) == '/' || s.at(1) == ':')
            return true;
        else
            return false;
    }
    else
        return false;
}

std::list<string> MiniPath::listDirectories( const string& s )
{
    list<string> directories;

    struct _finddata_t c_file;
    intptr_t hFile;

    string filter = s + MiniPath::getSystemDelim() + "*.*";

    if( (hFile = _findfirst( filter.c_str(), &c_file )) == -1L )
    {}
    else
    {
        do
        {
            char buffer[256];
            if( ( c_file.attrib & _A_SUBDIR ) )
                directories.push_back( string( c_file.name ) );
        } while( _findnext( hFile, &c_file ) == 0 );
    }

    return directories;
}

std::list<string> MiniPath::listFiles( const string& s, string filter )
{
    list<string> files;

    struct _finddata_t c_file;
    intptr_t hFile;

    string find_filter = s + MiniPath::getSystemDelim() + filter;

    if( (hFile = _findfirst( find_filter.c_str(), &c_file )) == -1L )
    {}
    else
    {
        do
        {
            char buffer[256];
            if( !( c_file.attrib & _A_SUBDIR ) )
                files.push_back( string( c_file.name ) );
        } while( _findnext( hFile, &c_file ) == 0 );
    }

    return files;
}

bool MiniPath::pathExists( const std::string& s )
{
    struct _finddata_t c_file;
    intptr_t hFile;

    if( (hFile = _findfirst( s.c_str(), &c_file )) != -1L )
        return true;

    return false;
}

vector<const char*> toCStringVec( const vector<string>& vs )
{
    std::vector<const char*> tmp;
    for( const string& s : vs )
        tmp.push_back( s.c_str() );
    return tmp;
}

vector<const char*> toCStringVec( const list<string>& vs )
{
    std::vector<const char*> tmp;
    for( const string& s : vs )
        tmp.push_back( s.c_str() );
    return tmp;
}

bool fileIOWindow(
    string& file_path,
    std::vector<string>& recently_used_files,
    const string& button_text,
    std::vector<std::string> file_filter,
    bool ensure_file_exists,
    ImVec2 size )
{
    bool close_it = false;

    vector<const char*> extension_cstrings = toCStringVec( file_filter );

    static string current_folder = "x";
    static char c_current_folder[ 2048 ];

    if( current_folder == "x" )
        current_folder = MiniPath::getCurrentDir();

    static char current_file[ 256 ] = "Test.usr";
    static int  file_type_selected = 0;
    static int  file_selected = 0;
    static int  directory_selected = 0;
    static int  drive_selected = 0;
    static bool directory_browsing = false;
    static int  recent_selected = 0;

    string sys_delim = MiniPath::getSystemDelim();

    string tmp = current_folder + sys_delim + current_file;
    MiniPath current_mini_path( tmp );

    list<string> directories = MiniPath::listDirectories( current_mini_path.getPath() );
    std::vector<const char*> dir_list;
    for( const string& s : directories )
    {
        if( s == "." ) continue;
        dir_list.push_back( s.c_str() );
    }

    list<string> local_files = MiniPath::listFiles( current_mini_path.getPath(), string( extension_cstrings[file_type_selected] ) );
    vector<const char*> file_list = toCStringVec( local_files );

    if ( directory_browsing )
        size.y += std::min( size_t( 8 ), std::max( dir_list.size(), file_list.size() ) ) *  GetFontSize();

    SetNextWindowSize( size );
    Begin( "FileIO" );

    Text("Directory: "); SameLine();
    PushItemWidth( GetWindowWidth() - 145 );

    strcpy( c_current_folder, current_folder.c_str() );
    if( InputText( " ", c_current_folder, IM_ARRAYSIZE( c_current_folder ) ) )
    {
        string tmp = c_current_folder;
        if( MiniPath::pathExists( tmp ) )
            current_folder = c_current_folder;
    }
    SameLine();

    std::vector<const char*> recent = toCStringVec( recently_used_files );

    if( Button(" " CARET_DOWN " ") )
        ImGui::OpenPopup("RecentFiles");

    if (ImGui::BeginPopup("RecentFiles"))
    {
        if( ListBox( "", &recent_selected, recent.data(), recent.size() ) )
        {
            current_mini_path.fromString( string( recent[recent_selected] ), sys_delim[0] );
            if( !current_mini_path.getName().empty() )
                strcpy( current_file, current_mini_path.getName().c_str() );
            current_folder = current_mini_path.getPath();
            CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }

    Text("           "); SameLine();
    vector<string> split_directories = current_mini_path.getPathTokens();
    for( int i = 0; i < split_directories.size(); ++i )
    {
        if( Button( split_directories[i].c_str() ) )
        {
            string chosen_dir;
            for( int j = 0; j <= i; ++j)
            {
                chosen_dir += split_directories[j];
                if( j != i )
                    chosen_dir += sys_delim;
            }
            current_folder = chosen_dir;
        }
        if( i != split_directories.size()-1 )
            SameLine();
    }

    if( CollapsingHeader("Browse Directories") )
    {
        directory_browsing = true;

#if defined(WIN32)
        vector<const char*> drive_list = toCStringVec( getWindowsDrives() );

        Text( "  " ); SameLine();
        PushItemWidth( 40 );
        if( ListBox( "  ", &drive_selected, drive_list.data(), drive_list.size() ) )
        {
            string new_path = drive_list[drive_selected];
            current_folder = new_path;
        }
#else
        Text( "           " );
#endif
        SameLine();

        PushItemWidth( GetWindowWidth()/2 - 60 );
        if( ListBox( " ", &directory_selected, dir_list.data(), dir_list.size() ) )
        {
            string new_path;

            if( string(dir_list[directory_selected]).find( ".." ) != std::string::npos )
            {
                vector<string> split_directories = current_mini_path.getPathTokens();
                current_folder.clear();
                for( int i = 0; i < split_directories.size() - 1; ++i )
                {
                    current_folder += split_directories[i];
                    if( i < split_directories.size() - 2 )
                        current_folder += sys_delim;
                }
            }
            else
                current_folder = current_folder + sys_delim + dir_list[directory_selected];
        }

        SameLine();
        PushItemWidth( GetWindowWidth()/2 - 60 );
        if( ListBox( "", &file_selected, file_list.data(), file_list.size() ) )
        {
            strcpy( current_file, file_list[file_selected] );
        }
    }
    else
         directory_browsing = false;

    Text(" ");

    Text("File Name: "); SameLine();
    InputText( "  ", current_file, IM_ARRAYSIZE( current_file ) );

    Text( "File Type: " ); SameLine(); Text( extension_cstrings[file_type_selected] ); SameLine();
    if (Button( CARET_DOWN ) )
        ImGui::OpenPopup("FileType");

    if (ImGui::BeginPopup("FileType"))
    {
        if( ListBox( "", &file_type_selected, extension_cstrings.data(), extension_cstrings.size() ) )
        {
            CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }

    ImVec2 pos = GetCursorPos();

    pos.x += GetWindowWidth() - 75 - button_text.size() * ( GetFontSize() * 0.7 );
    pos.y  = GetWindowHeight() - 30;

    SetCursorPos( pos );
    if( Button( button_text.c_str() ) )
    {
        vector<string> ext_filter_v = stringSplit( extension_cstrings[file_type_selected], '.');
        if( ext_filter_v.size() == 2 &&
            ext_filter_v[1] != "*" )
        {
            string ext_filter = ext_filter_v[1];
            if( current_mini_path.extension() == ext_filter )
                file_path = current_mini_path.filePath();
        }
        else
            file_path = current_mini_path.filePath();

        if( ensure_file_exists )
        {
            if( MiniPath::pathExists( file_path ) )
                close_it = true;
        }
        else
            close_it = true;
    }

    SameLine();
    if( Button( "Cancel" ) )
        close_it = true;
    End();

    return close_it;
}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     noiseestimate.cpp
* @author   Limin Sun <liminsun@nmr.mgh.harvard.edu>;
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     July, 2014
*
* @section  LICENSE
*
* Copyright (C) 2014, Limin Sun, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief    Contains the implementation of the NoiseEstimate class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "noiseestimate.h"
#include "FormFiles/noiseestimatesetupwidget.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QtPlugin>
#include <QDebug>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace NoiseEstimatePlugin;
using namespace MNEX;
using namespace XMEASLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

NoiseEstimate::NoiseEstimate()
: m_bIsRunning(false)
, m_bProcessData(false)
, m_pRTMSAInput(NULL)
, m_pFSOutput(NULL)
, m_pBuffer(CircularMatrixBuffer<double>::SPtr())
, m_Fs(600)
, m_iFFTlength(16384)
, m_DataLen(6)
{
}

//*************************************************************************************************************

NoiseEstimate::~NoiseEstimate()
{
    if(this->isRunning())
        stop();
}

//*************************************************************************************************************

QSharedPointer<IPlugin> NoiseEstimate::clone() const
{
    QSharedPointer<NoiseEstimate> pNoiseEstimateClone(new NoiseEstimate);
    return pNoiseEstimateClone;
}

//*************************************************************************************************************
//=============================================================================================================
// Creating required display instances and set configurations
//=============================================================================================================

void NoiseEstimate::init()
{
    //
    // Load Settings
    //
    QSettings settings;
    m_iFFTlength = settings.value(QString("Plugin/%1/FFTLength").arg(this->getName()), 16384).toInt();
    m_DataLen = settings.value(QString("Plugin/%1/DataLen").arg(this->getName()), 6).toInt();

    // Input
    m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, "Noise Estimatge In", "Noise Estimate input data");
    connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &NoiseEstimate::update, Qt::DirectConnection);
    m_inputConnectors.append(m_pRTMSAInput);

    // Output
    m_pFSOutput = PluginOutputData<FrequencySpectrum>::create(this, "Noise Estimate Out", "Noise Estimate output data");
    m_pFSOutput->data()->setName(this->getName());//Provide name to auto store widget settings
    m_outputConnectors.append(m_pFSOutput);

    //init channels when fiff info is available
    connect(this, &NoiseEstimate::fiffInfoAvailable, this, &NoiseEstimate::initConnector);

    //Delete Buffer - will be initailzed with first incoming data
    if(!m_pBuffer.isNull())
        m_pBuffer = CircularMatrixBuffer<double>::SPtr();
}

//*************************************************************************************************************

void NoiseEstimate::unload()
{
    //
    // Store Settings
    //
    QSettings settings;
    settings.setValue(QString("Plugin/%1/FFTLength").arg(this->getName()), m_iFFTlength);
    settings.setValue(QString("Plugin/%1/DataLen").arg(this->getName()), m_DataLen);
}

//*************************************************************************************************************

void NoiseEstimate::initConnector()
{
    qDebug() << "void NoiseEstimate::initConnector()";
    if(m_pFiffInfo)
        m_pFSOutput->data()->initFromFiffInfo(m_pFiffInfo);
}

//*************************************************************************************************************

bool NoiseEstimate::start()
{
    //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.
    if(this->isRunning())
        QThread::wait();

    m_bIsRunning = true;

    // Start threads
    QThread::start();

    return true;
}

//*************************************************************************************************************

bool NoiseEstimate::stop()
{
    //Wait until this thread is stopped
    m_bIsRunning = false;

    m_pRtNoise->stop();

    if(m_bProcessData)
    {

        //In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)
        m_pBuffer->releaseFromPop();
        m_pBuffer->releaseFromPush();

        m_pBuffer->clear();

//        m_pNEOutput->data()->clear();
    }

    return true;
}

//*************************************************************************************************************

IPlugin::PluginType NoiseEstimate::getType() const
{
    return _IAlgorithm;
}

//*************************************************************************************************************

QString NoiseEstimate::getName() const
{
    return "Noise Estimation";
}

//*************************************************************************************************************

QWidget* NoiseEstimate::setupWidget()
{
    NoiseEstimateSetupWidget* setupWidget = new NoiseEstimateSetupWidget(this);//widget is later distroyed by CentralWidget - so it has to be created everytime new

    connect(this,&NoiseEstimate::SetNoisePara,setupWidget,&NoiseEstimateSetupWidget::init);
    //connect(this,&NoiseEstimate::RePlot,setupWidget,&NoiseEstimateSetupWidget::Update);

    return setupWidget;

}

//*************************************************************************************************************

void NoiseEstimate::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)
{
    QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>();

    if(pRTMSA)
    {
        //Check if buffer initialized

        mutex.lock();
        if(!m_pBuffer)
            m_pBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTMSA->getNumChannels(), pRTMSA->getMultiSampleArray()[0].cols()));

        //Fiff information
        if(!m_pFiffInfo)
        {
            m_pFiffInfo = pRTMSA->info();
            emit fiffInfoAvailable();
        }
        mutex.unlock();

        if(m_bProcessData)
        {
            MatrixXd t_mat;

            for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i)
            {
                t_mat = pRTMSA->getMultiSampleArray()[i];
                m_pBuffer->push(&t_mat);
            }
        }
    }
}

//*************************************************************************************************************

void NoiseEstimate::appendNoiseSpectrum(MatrixXd t_send)
{
    qDebug()<<"Spectrum"<<t_send(0,1)<<t_send(0,2)<<t_send(0,3);
    mutex.lock();
    m_qVecSpecData.push_back(t_send);
    mutex.unlock();
    qDebug()<<"---------------------------------appendNoiseSpectrum--------------------------------";
}

//*************************************************************************************************************

void NoiseEstimate::run()
{
    //
    // Read Fiff Info
    //
    bool waitForFiffInfo = true;
    while(!m_pFiffInfo)
    {
        mutex.lock();
        if(m_pFiffInfo)
            waitForFiffInfo = false;
        mutex.unlock();
        msleep(10);// Wait for fiff Info
    }

    // Init Real-Time Noise Spectrum estimator
    //
    // calculate the segments according to the requested data length
    // here 500 is the number of samples for a block specified in babyMEG plugin
    m_Fs = m_pFiffInfo->sfreq;
    int segments =  (qint32) ((m_DataLen * m_pFiffInfo->sfreq)/500.0);

    qDebug()<<"+++++++++++segments :"<<segments<< "m_DataLen"<<m_DataLen<<"m_Fs"<<m_Fs<<"++++++++++++++++++++++++";

    m_pRtNoise = RtNoise::SPtr(new RtNoise(m_iFFTlength, m_pFiffInfo, segments));
    connect(m_pRtNoise.data(), &RtNoise::SpecCalculated, this, &NoiseEstimate::appendNoiseSpectrum);

    // Start Spectrum estimation

    m_pRtNoise->start();

    m_bProcessData = true;

    while (m_bIsRunning)
    {
        if(m_bProcessData)
        {
            /* Dispatch the inputs */
            MatrixXd t_mat = m_pBuffer->pop();

            //ToDo: Implement your algorithm here
            m_pRtNoise->append(t_mat);

           if(m_qVecSpecData.size() > 0)
           {
               mutex.lock();
               qDebug()<<"%%%%%%%%%%%%%%%% send spectrum for display %%%%%%%%%%%%%%%%%%%";
                //send spectrum to the output data
               m_pFSOutput->data()->setValue(m_qVecSpecData[0]);
               m_qVecSpecData.pop_front();
               mutex.unlock();

            }
        }//m_bProcessData
    }//m_bIsRunning
    m_pRtNoise->stop();
//    delete m_pRtNoise;
}

<commit_msg>decrease matrix size<commit_after>//=============================================================================================================
/**
* @file     noiseestimate.cpp
* @author   Limin Sun <liminsun@nmr.mgh.harvard.edu>;
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     July, 2014
*
* @section  LICENSE
*
* Copyright (C) 2014, Limin Sun, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief    Contains the implementation of the NoiseEstimate class.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "noiseestimate.h"
#include "FormFiles/noiseestimatesetupwidget.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QtPlugin>
#include <QDebug>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace NoiseEstimatePlugin;
using namespace MNEX;
using namespace XMEASLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

NoiseEstimate::NoiseEstimate()
: m_bIsRunning(false)
, m_bProcessData(false)
, m_pRTMSAInput(NULL)
, m_pFSOutput(NULL)
, m_pBuffer(CircularMatrixBuffer<double>::SPtr())
, m_Fs(600)
, m_iFFTlength(16384)
, m_DataLen(6)
{
}

//*************************************************************************************************************

NoiseEstimate::~NoiseEstimate()
{
    if(this->isRunning())
        stop();
}

//*************************************************************************************************************

QSharedPointer<IPlugin> NoiseEstimate::clone() const
{
    QSharedPointer<NoiseEstimate> pNoiseEstimateClone(new NoiseEstimate);
    return pNoiseEstimateClone;
}

//*************************************************************************************************************
//=============================================================================================================
// Creating required display instances and set configurations
//=============================================================================================================

void NoiseEstimate::init()
{
    //
    // Load Settings
    //
    QSettings settings;
    m_iFFTlength = settings.value(QString("Plugin/%1/FFTLength").arg(this->getName()), 16384).toInt();
    m_DataLen = settings.value(QString("Plugin/%1/DataLen").arg(this->getName()), 6).toInt();

    // Input
    m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, "Noise Estimatge In", "Noise Estimate input data");
    connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &NoiseEstimate::update, Qt::DirectConnection);
    m_inputConnectors.append(m_pRTMSAInput);

    // Output
    m_pFSOutput = PluginOutputData<FrequencySpectrum>::create(this, "Noise Estimate Out", "Noise Estimate output data");
    m_pFSOutput->data()->setName(this->getName());//Provide name to auto store widget settings
    m_outputConnectors.append(m_pFSOutput);

    //init channels when fiff info is available
    connect(this, &NoiseEstimate::fiffInfoAvailable, this, &NoiseEstimate::initConnector);

    //Delete Buffer - will be initailzed with first incoming data
    if(!m_pBuffer.isNull())
        m_pBuffer = CircularMatrixBuffer<double>::SPtr();
}

//*************************************************************************************************************

void NoiseEstimate::unload()
{
    //
    // Store Settings
    //
    QSettings settings;
    settings.setValue(QString("Plugin/%1/FFTLength").arg(this->getName()), m_iFFTlength);
    settings.setValue(QString("Plugin/%1/DataLen").arg(this->getName()), m_DataLen);
}

//*************************************************************************************************************

void NoiseEstimate::initConnector()
{
    qDebug() << "void NoiseEstimate::initConnector()";
    if(m_pFiffInfo)
        m_pFSOutput->data()->initFromFiffInfo(m_pFiffInfo);
}

//*************************************************************************************************************

bool NoiseEstimate::start()
{
    //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.
    if(this->isRunning())
        QThread::wait();

    m_bIsRunning = true;

    // Start threads
    QThread::start();

    return true;
}

//*************************************************************************************************************

bool NoiseEstimate::stop()
{
    //Wait until this thread is stopped
    m_bIsRunning = false;

    m_pRtNoise->stop();

    if(m_bProcessData)
    {

        //In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)
        m_pBuffer->releaseFromPop();
        m_pBuffer->releaseFromPush();

        m_pBuffer->clear();

//        m_pNEOutput->data()->clear();
    }

    return true;
}

//*************************************************************************************************************

IPlugin::PluginType NoiseEstimate::getType() const
{
    return _IAlgorithm;
}

//*************************************************************************************************************

QString NoiseEstimate::getName() const
{
    return "Noise Estimation";
}

//*************************************************************************************************************

QWidget* NoiseEstimate::setupWidget()
{
    NoiseEstimateSetupWidget* setupWidget = new NoiseEstimateSetupWidget(this);//widget is later distroyed by CentralWidget - so it has to be created everytime new

    connect(this,&NoiseEstimate::SetNoisePara,setupWidget,&NoiseEstimateSetupWidget::init);
    //connect(this,&NoiseEstimate::RePlot,setupWidget,&NoiseEstimateSetupWidget::Update);

    return setupWidget;

}

//*************************************************************************************************************

void NoiseEstimate::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)
{
    QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>();

    if(pRTMSA)
    {
        //Check if buffer initialized

        mutex.lock();
        if(!m_pBuffer)
            m_pBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(8, pRTMSA->getNumChannels(), pRTMSA->getMultiSampleArray()[0].cols()));

        //Fiff information
        if(!m_pFiffInfo)
        {
            m_pFiffInfo = pRTMSA->info();
            emit fiffInfoAvailable();
        }
        mutex.unlock();

        if(m_bProcessData)
        {
            MatrixXd t_mat;

            for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i)
            {
                t_mat = pRTMSA->getMultiSampleArray()[i];
                m_pBuffer->push(&t_mat);
            }
        }
    }
}

//*************************************************************************************************************

void NoiseEstimate::appendNoiseSpectrum(MatrixXd t_send)
{
    qDebug()<<"Spectrum"<<t_send(0,1)<<t_send(0,2)<<t_send(0,3);
    mutex.lock();
    m_qVecSpecData.push_back(t_send);
    mutex.unlock();
    qDebug()<<"---------------------------------appendNoiseSpectrum--------------------------------";
}

//*************************************************************************************************************

void NoiseEstimate::run()
{
    //
    // Read Fiff Info
    //
    bool waitForFiffInfo = true;
    while(waitForFiffInfo)
    {
        mutex.lock();
        if(m_pFiffInfo)
            waitForFiffInfo = false;
        mutex.unlock();
        msleep(10);// Wait for fiff Info
    }

    // Init Real-Time Noise Spectrum estimator
    //
    // calculate the segments according to the requested data length
    // here 500 is the number of samples for a block specified in babyMEG plugin
    m_Fs = m_pFiffInfo->sfreq;
    int segments =  (qint32) ((m_DataLen * m_pFiffInfo->sfreq)/500.0);

    qDebug()<<"+++++++++++segments :"<<segments<< "m_DataLen"<<m_DataLen<<"m_Fs"<<m_Fs<<"++++++++++++++++++++++++";

    m_pRtNoise = RtNoise::SPtr(new RtNoise(m_iFFTlength, m_pFiffInfo, segments));
    connect(m_pRtNoise.data(), &RtNoise::SpecCalculated, this, &NoiseEstimate::appendNoiseSpectrum);

    // Start Spectrum estimation

    m_pRtNoise->start();

    m_bProcessData = true;

    while (m_bIsRunning)
    {
        if(m_bProcessData)
        {
            /* Dispatch the inputs */
            MatrixXd t_mat = m_pBuffer->pop();

            //ToDo: Implement your algorithm here
            m_pRtNoise->append(t_mat);

           if(m_qVecSpecData.size() > 0)
           {
               mutex.lock();
               qDebug()<<"%%%%%%%%%%%%%%%% send spectrum for display %%%%%%%%%%%%%%%%%%%";
                //send spectrum to the output data
               m_pFSOutput->data()->setValue(m_qVecSpecData[0]);
               m_qVecSpecData.pop_front();
               mutex.unlock();

            }
        }//m_bProcessData
    }//m_bIsRunning
    m_pRtNoise->stop();
//    delete m_pRtNoise;
}

<|endoftext|>


<commit_before>//
// Copyright (C) 2011-13, DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#include <Python.h>

#include <dynd/dtypes/fixedstring_dtype.hpp>
#include <dynd/dtypes/fixedstruct_dtype.hpp>
#include <dynd/dtypes/fixed_dim_dtype.hpp>
#include <dynd/dtypes/struct_dtype.hpp>
#include <dynd/dtypes/strided_dim_dtype.hpp>
#include <dynd/dtypes/pointer_dtype.hpp>
#include <dynd/dtypes/dtype_alignment.hpp>

#include "ctypes_interop.hpp"
#include "dtype_functions.hpp"
#include "utility_functions.hpp"

using namespace std;
using namespace dynd;
using namespace pydynd;

ctypes_info pydynd::ctypes;

void pydynd::init_ctypes_interop()
{
    memset(&ctypes, 0, sizeof(ctypes));

    // The C _ctypes module
    ctypes._ctypes = PyImport_ImportModule("_ctypes");
    if (ctypes._ctypes == NULL) {
        throw runtime_error("Could not import module _ctypes");
    }

    // The internal type objects used by ctypes
    ctypes.PyCStructType_Type = PyObject_GetAttrString(ctypes._ctypes, "Structure");
    // _ctypes doesn't expose PyCData_Type, but we know it's the base class of PyCStructType_Type
    ctypes.PyCData_Type = (PyObject *)((PyTypeObject *)ctypes.PyCStructType_Type)->tp_base;
    ctypes.UnionType_Type = PyObject_GetAttrString(ctypes._ctypes, "Union");
    ctypes.PyCPointerType_Type = PyObject_GetAttrString(ctypes._ctypes, "_Pointer");
    ctypes.PyCArrayType_Type = PyObject_GetAttrString(ctypes._ctypes, "Array");
    ctypes.PyCSimpleType_Type = PyObject_GetAttrString(ctypes._ctypes, "_SimpleCData");
    ctypes.PyCFuncPtrType_Type = PyObject_GetAttrString(ctypes._ctypes, "CFuncPtr");

    if (PyErr_Occurred()) {
        Py_XDECREF(ctypes._ctypes);

        Py_XDECREF(ctypes.PyCData_Type);
        Py_XDECREF(ctypes.PyCStructType_Type);
        Py_XDECREF(ctypes.UnionType_Type);
        Py_XDECREF(ctypes.PyCPointerType_Type);
        Py_XDECREF(ctypes.PyCArrayType_Type);
        Py_XDECREF(ctypes.PyCSimpleType_Type);
        Py_XDECREF(ctypes.PyCFuncPtrType_Type);

        memset(&ctypes, 0, sizeof(ctypes));
        throw std::runtime_error("Error initializing ctypes C-level data for low level interop");
    }
}

calling_convention_t pydynd::get_ctypes_calling_convention(PyCFuncPtrObject* cfunc)
{
    // This is the internal StgDictObject "flags" attribute, which is
    // custom-placed in the typeobject's dict by ctypes.
    pyobject_ownref flags_obj(PyObject_GetAttrString((PyObject *)Py_TYPE(cfunc), "_flags_"));

    long flags = PyInt_AsLong(flags_obj);
    if (flags == -1 && PyErr_Occurred()) {
        throw std::runtime_error("Error getting ctypes function flags");
    }

    if (flags&0x02) { // 0x02 is FUNCFLAG_HRESULT
        throw std::runtime_error("Functions returning an HRESULT are not supported");
    }

    //if (flags&0x04) { // 0x04 is FUNCFLAG_PYTHONAPI, may need special handling
    //}

    if (flags&0x08) { // 0x08 is FUNCFLAG_USE_ERRNO
        throw std::runtime_error("Functions using errno are not yet supported");
    }

    if (flags&0x10) { // 0x10 is FUNCFLAG_USE_LASTERROR
        throw std::runtime_error("Functions using lasterror are not yet supported");
    }

#if defined(_WIN32)
    if (cfunc->index) {
        throw std::runtime_error("COM functions are not supported");
    }
# if !defined(_M_X64)
    // Only on 32-bit Windows are non-CDECL calling conventions supported
    if (flags&0x01) { // 0x01 is FUNCFLAG_CDECL from cpython's internal ctypes.h
        return cdecl_callconv;
    } else {
        return win32_stdcall_callconv;
    }
# endif
#else
    return cdecl_callconv;
#endif
}

void pydynd::get_ctypes_signature(PyCFuncPtrObject* cfunc, dtype& out_returntype, std::vector<dynd::dtype>& out_paramtypes)
{
    // The fields restype and argtypes are not always stored at the C level,
    // so must use the higher level getattr.
    pyobject_ownref restype(PyObject_GetAttrString((PyObject *)cfunc, "restype"));
    pyobject_ownref argtypes(PyObject_GetAttrString((PyObject *)cfunc, "argtypes"));

    if (argtypes == Py_None) {
        throw std::runtime_error("The argtypes and restype of a ctypes function pointer must be specified to get its signature");
    }

    // Get the return type
    if (restype == Py_None) {
        // No return type
        out_returntype = make_dtype<void>();
    } else {
        out_returntype = dtype_from_ctypes_cdatatype(restype);
    }

    Py_ssize_t argcount = PySequence_Size(argtypes);
    if (argcount < 0) {
        throw runtime_error("The argtypes of the ctypes function pointer has the wrong type");
    }

    // Set the output size
    out_paramtypes.resize(argcount);

    // Get the argument types
    for (intptr_t i = 0; i < argcount; ++i) {
        pyobject_ownref element(PySequence_GetItem(argtypes, i));
        out_paramtypes[i] = dtype_from_ctypes_cdatatype(element);
    }
}

dynd::dtype pydynd::dtype_from_ctypes_cdatatype(PyObject *d)
{
    if (!PyObject_IsSubclass(d, ctypes.PyCData_Type)) {
        throw runtime_error("requested a dtype from a ctypes c data type, but the given object has the wrong type");
    }

    // If the ctypes type has a _dynd_type_ property, that should be
    // a pydynd dtype instance corresponding to the type. This is how
    // the complex type is supported, for example.
    PyObject *dynd_type_obj = PyObject_GetAttrString(d, "_dynd_type_");
    if (dynd_type_obj == NULL) {
        PyErr_Clear();
    } else {
        pyobject_ownref dynd_type(dynd_type_obj);
        return make_dtype_from_pyobject(dynd_type);
    }

    // The simple C data types
    if (PyObject_IsSubclass(d, ctypes.PyCSimpleType_Type)) {
        char *proto_str = NULL;
        Py_ssize_t proto_len = 0;
        pyobject_ownref proto(PyObject_GetAttrString(d, "_type_"));
        if (PyString_AsStringAndSize(proto, &proto_str, &proto_len) < 0 ||
                            proto_len != 1) {
            throw std::runtime_error("invalid ctypes type");
        }

        switch (proto_str[0]) {
            case 'b':
                return make_dtype<int8_t>();
            case 'B':
                return make_dtype<uint8_t>();
            case 'c':
                return make_fixedstring_dtype(1, string_encoding_ascii);
            case 'd':
                return make_dtype<double>();
            case 'f':
                return make_dtype<float>();
            case 'h':
                return make_dtype<int16_t>();
            case 'H':
                return make_dtype<uint16_t>();
            case 'i':
                return make_dtype<int32_t>();
            case 'I':
                return make_dtype<uint32_t>();
            case 'l':
                return make_dtype<long>();
            case 'L':
                return make_dtype<unsigned long>();
            case 'q':
                return make_dtype<int64_t>();
            case 'Q':
                return make_dtype<uint64_t>();
            default: {
                stringstream ss;
                ss << "The ctypes type code '" << proto_str[0] << "' cannot be converted to a dynd::dtype";
                throw runtime_error(ss.str());
            }
        }
    } else if (PyObject_IsSubclass(d, ctypes.PyCPointerType_Type)) {
        // Translate into a blockref pointer dtype
        pyobject_ownref target_dtype_obj(PyObject_GetAttrString(d, "_type_"));
        dtype target_dtype = dtype_from_ctypes_cdatatype(target_dtype_obj);
        return make_pointer_dtype(target_dtype);
    } else if (PyObject_IsSubclass(d, ctypes.PyCStructType_Type)) {
        // Translate into a fixedstruct or struct dtype
        pyobject_ownref fields_list_obj(PyObject_GetAttrString(d, "_fields_"));
        if (!PyList_Check(fields_list_obj.get())) {
            throw runtime_error("The _fields_ member of the ctypes C struct is not a list");
        }
        vector<dtype> field_types;
        vector<string> field_names;
        vector<size_t> field_offsets;
        Py_ssize_t field_count = PyList_GET_SIZE(fields_list_obj.get());
        for (Py_ssize_t i = 0; i < field_count; ++i) {
            PyObject *item = PyList_GET_ITEM(fields_list_obj.get(), i);
            if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
                stringstream ss;
                ss << "The _fields_[" << i << "] member of the ctypes C struct is not a tuple of size 2";
                throw runtime_error(ss.str());
            }
            field_types.push_back(dtype_from_ctypes_cdatatype(PyTuple_GET_ITEM(item, 1)));
            PyObject *key = PyTuple_GET_ITEM(item, 0);
            field_names.push_back(pystring_as_string(key));
            pyobject_ownref field_data_obj(PyObject_GetAttr(d, key));
            pyobject_ownref field_data_offset_obj(PyObject_GetAttrString(field_data_obj.get(), "offset"));
            field_offsets.push_back(pyobject_as_index(field_data_offset_obj.get()));
            // If the field isn't aligned as the dtype requires, make it into an unaligned version
            if (!offset_is_aligned(field_offsets.back(), field_types.back().get_alignment())) {
                field_types.back() = make_unaligned_dtype(field_types.back());
            }
        }
        pyobject_ownref total_size_obj(PyObject_CallMethod(ctypes._ctypes, (char *)"sizeof", (char *)"N", d));
        size_t total_size = pyobject_as_index(total_size_obj.get());

        if (is_fixedstruct_compatible_offsets(field_count, &field_types[0],
                        &field_offsets[0], total_size)) {
            return make_fixedstruct_dtype(field_count, &field_types[0], &field_names[0]);
        } else {
            return make_struct_dtype(field_types, field_names);
        }
    } else if (PyObject_IsSubclass(d, ctypes.PyCArrayType_Type)) {
        // Translate into a either a fixed_dim or strided_dim
        pyobject_ownref element_dtype_obj(PyObject_GetAttrString(d, "_type_"));
        dtype element_dtype = dtype_from_ctypes_cdatatype(element_dtype_obj);
        if (element_dtype.get_data_size() != 0) {
            pyobject_ownref array_length_obj(PyObject_GetAttrString(d, "_length_"));
            intptr_t array_length = pyobject_as_index(array_length_obj.get());
            return make_fixed_dim_dtype(array_length, element_dtype);
        } else {
            return make_strided_dim_dtype(element_dtype);
        }
    }

    throw runtime_error("Ctypes type object is not supported by dynd::dtype");
}
<commit_msg>Fix code which doesn't compile on windows 64-bitg<commit_after>//
// Copyright (C) 2011-13, DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#include <Python.h>

#include <dynd/dtypes/fixedstring_dtype.hpp>
#include <dynd/dtypes/fixedstruct_dtype.hpp>
#include <dynd/dtypes/fixed_dim_dtype.hpp>
#include <dynd/dtypes/struct_dtype.hpp>
#include <dynd/dtypes/strided_dim_dtype.hpp>
#include <dynd/dtypes/pointer_dtype.hpp>
#include <dynd/dtypes/dtype_alignment.hpp>

#include "ctypes_interop.hpp"
#include "dtype_functions.hpp"
#include "utility_functions.hpp"

using namespace std;
using namespace dynd;
using namespace pydynd;

ctypes_info pydynd::ctypes;

void pydynd::init_ctypes_interop()
{
    memset(&ctypes, 0, sizeof(ctypes));

    // The C _ctypes module
    ctypes._ctypes = PyImport_ImportModule("_ctypes");
    if (ctypes._ctypes == NULL) {
        throw runtime_error("Could not import module _ctypes");
    }

    // The internal type objects used by ctypes
    ctypes.PyCStructType_Type = PyObject_GetAttrString(ctypes._ctypes, "Structure");
    // _ctypes doesn't expose PyCData_Type, but we know it's the base class of PyCStructType_Type
    ctypes.PyCData_Type = (PyObject *)((PyTypeObject *)ctypes.PyCStructType_Type)->tp_base;
    ctypes.UnionType_Type = PyObject_GetAttrString(ctypes._ctypes, "Union");
    ctypes.PyCPointerType_Type = PyObject_GetAttrString(ctypes._ctypes, "_Pointer");
    ctypes.PyCArrayType_Type = PyObject_GetAttrString(ctypes._ctypes, "Array");
    ctypes.PyCSimpleType_Type = PyObject_GetAttrString(ctypes._ctypes, "_SimpleCData");
    ctypes.PyCFuncPtrType_Type = PyObject_GetAttrString(ctypes._ctypes, "CFuncPtr");

    if (PyErr_Occurred()) {
        Py_XDECREF(ctypes._ctypes);

        Py_XDECREF(ctypes.PyCData_Type);
        Py_XDECREF(ctypes.PyCStructType_Type);
        Py_XDECREF(ctypes.UnionType_Type);
        Py_XDECREF(ctypes.PyCPointerType_Type);
        Py_XDECREF(ctypes.PyCArrayType_Type);
        Py_XDECREF(ctypes.PyCSimpleType_Type);
        Py_XDECREF(ctypes.PyCFuncPtrType_Type);

        memset(&ctypes, 0, sizeof(ctypes));
        throw std::runtime_error("Error initializing ctypes C-level data for low level interop");
    }
}

calling_convention_t pydynd::get_ctypes_calling_convention(PyCFuncPtrObject* cfunc)
{
    // This is the internal StgDictObject "flags" attribute, which is
    // custom-placed in the typeobject's dict by ctypes.
    pyobject_ownref flags_obj(PyObject_GetAttrString((PyObject *)Py_TYPE(cfunc), "_flags_"));

    long flags = PyInt_AsLong(flags_obj);
    if (flags == -1 && PyErr_Occurred()) {
        throw std::runtime_error("Error getting ctypes function flags");
    }

    if (flags&0x02) { // 0x02 is FUNCFLAG_HRESULT
        throw std::runtime_error("Functions returning an HRESULT are not supported");
    }

    //if (flags&0x04) { // 0x04 is FUNCFLAG_PYTHONAPI, may need special handling
    //}

    if (flags&0x08) { // 0x08 is FUNCFLAG_USE_ERRNO
        throw std::runtime_error("Functions using errno are not yet supported");
    }

    if (flags&0x10) { // 0x10 is FUNCFLAG_USE_LASTERROR
        throw std::runtime_error("Functions using lasterror are not yet supported");
    }

#if defined(_WIN32)
    if (cfunc->index) {
        throw std::runtime_error("COM functions are not supported");
    }
# if !defined(_M_X64)
    // Only on 32-bit Windows are non-CDECL calling conventions supported
    if (flags&0x01) { // 0x01 is FUNCFLAG_CDECL from cpython's internal ctypes.h
        return cdecl_callconv;
    } else {
        return win32_stdcall_callconv;
    }
# else
    return cdecl_callconv;
# endif
#else
    return cdecl_callconv;
#endif
}

void pydynd::get_ctypes_signature(PyCFuncPtrObject* cfunc, dtype& out_returntype, std::vector<dynd::dtype>& out_paramtypes)
{
    // The fields restype and argtypes are not always stored at the C level,
    // so must use the higher level getattr.
    pyobject_ownref restype(PyObject_GetAttrString((PyObject *)cfunc, "restype"));
    pyobject_ownref argtypes(PyObject_GetAttrString((PyObject *)cfunc, "argtypes"));

    if (argtypes == Py_None) {
        throw std::runtime_error("The argtypes and restype of a ctypes function pointer must be specified to get its signature");
    }

    // Get the return type
    if (restype == Py_None) {
        // No return type
        out_returntype = make_dtype<void>();
    } else {
        out_returntype = dtype_from_ctypes_cdatatype(restype);
    }

    Py_ssize_t argcount = PySequence_Size(argtypes);
    if (argcount < 0) {
        throw runtime_error("The argtypes of the ctypes function pointer has the wrong type");
    }

    // Set the output size
    out_paramtypes.resize(argcount);

    // Get the argument types
    for (intptr_t i = 0; i < argcount; ++i) {
        pyobject_ownref element(PySequence_GetItem(argtypes, i));
        out_paramtypes[i] = dtype_from_ctypes_cdatatype(element);
    }
}

dynd::dtype pydynd::dtype_from_ctypes_cdatatype(PyObject *d)
{
    if (!PyObject_IsSubclass(d, ctypes.PyCData_Type)) {
        throw runtime_error("requested a dtype from a ctypes c data type, but the given object has the wrong type");
    }

    // If the ctypes type has a _dynd_type_ property, that should be
    // a pydynd dtype instance corresponding to the type. This is how
    // the complex type is supported, for example.
    PyObject *dynd_type_obj = PyObject_GetAttrString(d, "_dynd_type_");
    if (dynd_type_obj == NULL) {
        PyErr_Clear();
    } else {
        pyobject_ownref dynd_type(dynd_type_obj);
        return make_dtype_from_pyobject(dynd_type);
    }

    // The simple C data types
    if (PyObject_IsSubclass(d, ctypes.PyCSimpleType_Type)) {
        char *proto_str = NULL;
        Py_ssize_t proto_len = 0;
        pyobject_ownref proto(PyObject_GetAttrString(d, "_type_"));
        if (PyString_AsStringAndSize(proto, &proto_str, &proto_len) < 0 ||
                            proto_len != 1) {
            throw std::runtime_error("invalid ctypes type");
        }

        switch (proto_str[0]) {
            case 'b':
                return make_dtype<int8_t>();
            case 'B':
                return make_dtype<uint8_t>();
            case 'c':
                return make_fixedstring_dtype(1, string_encoding_ascii);
            case 'd':
                return make_dtype<double>();
            case 'f':
                return make_dtype<float>();
            case 'h':
                return make_dtype<int16_t>();
            case 'H':
                return make_dtype<uint16_t>();
            case 'i':
                return make_dtype<int32_t>();
            case 'I':
                return make_dtype<uint32_t>();
            case 'l':
                return make_dtype<long>();
            case 'L':
                return make_dtype<unsigned long>();
            case 'q':
                return make_dtype<int64_t>();
            case 'Q':
                return make_dtype<uint64_t>();
            default: {
                stringstream ss;
                ss << "The ctypes type code '" << proto_str[0] << "' cannot be converted to a dynd::dtype";
                throw runtime_error(ss.str());
            }
        }
    } else if (PyObject_IsSubclass(d, ctypes.PyCPointerType_Type)) {
        // Translate into a blockref pointer dtype
        pyobject_ownref target_dtype_obj(PyObject_GetAttrString(d, "_type_"));
        dtype target_dtype = dtype_from_ctypes_cdatatype(target_dtype_obj);
        return make_pointer_dtype(target_dtype);
    } else if (PyObject_IsSubclass(d, ctypes.PyCStructType_Type)) {
        // Translate into a fixedstruct or struct dtype
        pyobject_ownref fields_list_obj(PyObject_GetAttrString(d, "_fields_"));
        if (!PyList_Check(fields_list_obj.get())) {
            throw runtime_error("The _fields_ member of the ctypes C struct is not a list");
        }
        vector<dtype> field_types;
        vector<string> field_names;
        vector<size_t> field_offsets;
        Py_ssize_t field_count = PyList_GET_SIZE(fields_list_obj.get());
        for (Py_ssize_t i = 0; i < field_count; ++i) {
            PyObject *item = PyList_GET_ITEM(fields_list_obj.get(), i);
            if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
                stringstream ss;
                ss << "The _fields_[" << i << "] member of the ctypes C struct is not a tuple of size 2";
                throw runtime_error(ss.str());
            }
            field_types.push_back(dtype_from_ctypes_cdatatype(PyTuple_GET_ITEM(item, 1)));
            PyObject *key = PyTuple_GET_ITEM(item, 0);
            field_names.push_back(pystring_as_string(key));
            pyobject_ownref field_data_obj(PyObject_GetAttr(d, key));
            pyobject_ownref field_data_offset_obj(PyObject_GetAttrString(field_data_obj.get(), "offset"));
            field_offsets.push_back(pyobject_as_index(field_data_offset_obj.get()));
            // If the field isn't aligned as the dtype requires, make it into an unaligned version
            if (!offset_is_aligned(field_offsets.back(), field_types.back().get_alignment())) {
                field_types.back() = make_unaligned_dtype(field_types.back());
            }
        }
        pyobject_ownref total_size_obj(PyObject_CallMethod(ctypes._ctypes, (char *)"sizeof", (char *)"N", d));
        size_t total_size = pyobject_as_index(total_size_obj.get());

        if (is_fixedstruct_compatible_offsets(field_count, &field_types[0],
                        &field_offsets[0], total_size)) {
            return make_fixedstruct_dtype(field_count, &field_types[0], &field_names[0]);
        } else {
            return make_struct_dtype(field_types, field_names);
        }
    } else if (PyObject_IsSubclass(d, ctypes.PyCArrayType_Type)) {
        // Translate into a either a fixed_dim or strided_dim
        pyobject_ownref element_dtype_obj(PyObject_GetAttrString(d, "_type_"));
        dtype element_dtype = dtype_from_ctypes_cdatatype(element_dtype_obj);
        if (element_dtype.get_data_size() != 0) {
            pyobject_ownref array_length_obj(PyObject_GetAttrString(d, "_length_"));
            intptr_t array_length = pyobject_as_index(array_length_obj.get());
            return make_fixed_dim_dtype(array_length, element_dtype);
        } else {
            return make_strided_dim_dtype(element_dtype);
        }
    }

    throw runtime_error("Ctypes type object is not supported by dynd::dtype");
}
<|endoftext|>


<commit_before>#include <Core/Game.h>
#include <Core/Resources.h>
#include <Core/World.h>
#include <Core/Device.h>
#include <Input/Input.h>
#include <Audio/Audio.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <imgui.h>
#include <imgui/imgui_impl_glfw_gl3.h>
#include <Tools/Profiler.h>
#include <cereal/archives/json.hpp>
#include <fstream>

using namespace Osm;
using namespace std;

CGame Osm::Game;

void GameSettings::LoadFromFile(const std::string& file)
{
	FilePath = file;
	ifstream fs;
	fs.open(FilePath);
	if (fs.is_open())
	{
		cereal::JSONInputArchive iarchive(fs);
		iarchive(cereal::make_nvp("Setttings", *this));
	}
	fs.close();
}

void GameSettings::SaveToFile()
{
	ofstream fs;
	fs.open(FilePath);

	{
		cereal::JSONOutputArchive oarchive(fs);
		oarchive(cereal::make_nvp("Setttings", *this));
	}
	fs.close();
}

void GameSettings::Inspect()
{
	ImGui::InputInt("Screen Width", &ScreenWidth, 320, 5600);
	ImGui::InputInt("Screen Height", &ScreenHeight, 240, 5600);
	ImGui::Checkbox("Full Screen", &FullScreen);
	ImGui::Checkbox("Native Resolution", &UseNativeResolution);
	ImGui::SliderFloat("Inspector Font Size", &InspectorFontSize, 0.5f, 2.0f);

	if (ImGui::Button("Save Settings"))
	{
		SaveToFile();
	}
}

void CGame::InitializeInternal()
{
	_initialized = true;

	_resources = CreateComponent<ResourceManager>();

	_device = CreateComponent<GraphicsDevice>();

	_input = CreateComponent<InputManager>();

	_profiler = CreateComponent<Profiler>();

	_audio = CreateComponent<AudioManager>();

	ImGui_ImplGlfwGL3_Init(_device->GetWindow(), true);
}

void CGame::Initialize(const GameSettings& options)
{
	_settings = options;
	InitializeInternal();
}

void CGame::Shutdown()
{
	ASSERT(_initialized);

	// Remove component in the reverse order they were created
	while (_components.size() != 0)
		_components.erase(_components.end() - 1);
}

void CGame::Run()
{
	ASSERT(_initialized);

	auto lastFrame = glfwGetTime();
	while (!glfwWindowShouldClose(_device->GetWindow()) ||
			glfwGetKey(_device->GetWindow(), GLFW_KEY_ESCAPE))
	{
		glfwPollEvents();

		if (_event)
		{
			_event();
			_event = nullptr;
		}

		if (!_world)
			continue;

		auto currentFrame = glfwGetTime();
		float deltaTime = (float)(currentFrame - lastFrame);
		lastFrame = currentFrame;
		if (deltaTime > 0.033f)
			deltaTime = 0.033f;

		// Update
		if (!_paused || _advanceFrame)
		{
			_profiler->StartFrame();
			uint updateID = _profiler->StartSection("Update");
			_input->Update();
			_world->Update(deltaTime);
			_profiler->EndSection(updateID);
			_advanceFrame = false;
		}

		uint renderID = _profiler->StartSection("Render");
		glViewport(0, 0, _device->GetScreenWidth(), _device->GetScreenHeight());
		_world->Render();
		_profiler->EndSection(renderID);

		_profiler->EndFrame();

#ifdef INSPECTOR
		Inspect();
#endif

		glfwSwapBuffers(_device->GetWindow());

		// Escape hack
		auto joysticks = _input->GetActiveJoysticks();
		for (auto& j : joysticks)
		{
			if(_input->GetJoystickButtonPressed(j, JOYSTICK_BUTTON_BACK))
				return;
		}
	}
}

void CGame::SwapWorld(World* world)
{
	QueueEvent([this, world]()
	{
		if (_world)
			delete _world;
		_world = world;
	});
}

#ifdef INSPECTOR
void CGame::Inspect()
{
	if(_close_inspector)
		return;

	ImGui::GetIO().FontGlobalScale = _settings.InspectorFontSize;

	ImGuiWindowFlags window_flags = 0;
	//window_flags |= ImGuiWindowFlags_NoTitleBar;
	window_flags |= ImGuiWindowFlags_MenuBar;

	ImGui_ImplGlfwGL3_NewFrame();

	bool p_open = true;

	ImGui::BeginMainMenuBar();
	if (ImGui::BeginMenu("Tools"))
	{
		ImGui::MenuItem("Game Inspector", nullptr, &_show_engine_compoents);
		// Just a reminder that this might be useful
		// ImGui::MenuItem("Log", NULL, &show_app_log);
		ImGui::MenuItem("World Inspector", nullptr, &_show_world_inspector);
		ImGui::MenuItem("Settings Inspector", nullptr, &_show_settings);
		ImGui::MenuItem("Profiler", nullptr, &_show_profiler);
		ImGui::MenuItem("ImGui Test", nullptr, &_show_imgui_test);
		ImGui::EndMenu();
	}

	// Paused button
	if (!_paused)
		_paused = ImGui::Button("||");
	else
		_paused = !ImGui::Button("[>");
	ImGui::SameLine();
	_advanceFrame = ImGui::Button(">|");
	ImGui::SameLine();
	_close_inspector = ImGui::Button("X");
	ImGui::SameLine();
	ImGui::LabelText("Frame Time", "");
	ImGui::SameLine();
	ImGui::ProgressBar(_profiler->GetTimePerFrame() / (1.0 / 60.0));
	ImGui::EndMainMenuBar();

	if (_show_world_inspector)
	{
		ImGui::Begin("World Inspector");
		_world->Inspect();
		ImGui::End();
	}

	if(_show_profiler)
	{
		_profiler->Inspect();
	}

	if (_show_imgui_test)
	{
		ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
		ImGui::ShowTestWindow(&_show_imgui_test);
	}

	if(_show_engine_compoents)
	{
		ImGui::Begin("Game Inspector");
		for (auto& c : _components)
		{
			string name = typeid(*c).name();
			name = StringReplace(name, "class ", "");
			if (ImGui::CollapsingHeader(name.c_str()))
			{
				c->Inspect();
			}
		}
		ImGui::End();
	}

	if (_show_settings)
	{
		ImGui::Begin("Settings Inspector");
		_settings.Inspect();
		ImGui::End();
	}

	ImGui::Render();
}
#endif

/*
void CGame::Update()
{
	ASSERT(_initialized);
}

void CGame::Render()
{
	ASSERT(_initialized);
}
*/<commit_msg>Added copyright in Toolbox (should move to settings)<commit_after>#include <Core/Game.h>
#include <Core/Resources.h>
#include <Core/World.h>
#include <Core/Device.h>
#include <Input/Input.h>
#include <Audio/Audio.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <imgui.h>
#include <imgui/imgui_impl_glfw_gl3.h>
#include <Tools/Profiler.h>
#include <cereal/archives/json.hpp>
#include <fstream>

using namespace Osm;
using namespace std;

CGame Osm::Game;

#define SHOW_IMGUI 0

void GameSettings::LoadFromFile(const std::string& file)
{
	FilePath = file;
	ifstream fs;
	fs.open(FilePath);
	if (fs.is_open())
	{
		cereal::JSONInputArchive iarchive(fs);
		iarchive(cereal::make_nvp("Setttings", *this));
	}
	fs.close();
}

void GameSettings::SaveToFile()
{
	ofstream fs;
	fs.open(FilePath);

	{
		cereal::JSONOutputArchive oarchive(fs);
		oarchive(cereal::make_nvp("Setttings", *this));
	}
	fs.close();
}

void GameSettings::Inspect()
{
	ImGui::InputInt("Screen Width", &ScreenWidth, 320, 5600);
	ImGui::InputInt("Screen Height", &ScreenHeight, 240, 5600);
	ImGui::Checkbox("Full Screen", &FullScreen);
	ImGui::Checkbox("Native Resolution", &UseNativeResolution);
	ImGui::SliderFloat("Inspector Font Size", &InspectorFontSize, 0.5f, 2.0f);

	if (ImGui::Button("Save Settings"))
	{
		SaveToFile();
	}
}

void CGame::InitializeInternal()
{
	_initialized = true;

	_resources = CreateComponent<ResourceManager>();

	_device = CreateComponent<GraphicsDevice>();

	_input = CreateComponent<InputManager>();

	_profiler = CreateComponent<Profiler>();

	_audio = CreateComponent<AudioManager>();

	ImGui_ImplGlfwGL3_Init(_device->GetWindow(), true);
}

void CGame::Initialize(const GameSettings& options)
{
	_settings = options;
	InitializeInternal();
}

void CGame::Shutdown()
{
	ASSERT(_initialized);

	// Remove component in the reverse order they were created
	while (_components.size() != 0)
		_components.erase(_components.end() - 1);
}

void CGame::Run()
{
	ASSERT(_initialized);

	auto lastFrame = glfwGetTime();
	while (!glfwWindowShouldClose(_device->GetWindow()) ||
			glfwGetKey(_device->GetWindow(), GLFW_KEY_ESCAPE))
	{
		glfwPollEvents();

		if (_event)
		{
			_event();
			_event = nullptr;
		}

		if (!_world)
			continue;

		auto currentFrame = glfwGetTime();
		float deltaTime = (float)(currentFrame - lastFrame);
		lastFrame = currentFrame;
		if (deltaTime > 0.033f)
			deltaTime = 0.033f;

		// Update
		if (!_paused || _advanceFrame)
		{
			_profiler->StartFrame();
			uint updateID = _profiler->StartSection("Update");
			_input->Update();
			_world->Update(deltaTime);
			_profiler->EndSection(updateID);
			_advanceFrame = false;
		}

		uint renderID = _profiler->StartSection("Render");
		glViewport(0, 0, _device->GetScreenWidth(), _device->GetScreenHeight());
		_world->Render();
		_profiler->EndSection(renderID);

		_profiler->EndFrame();

#ifdef INSPECTOR
		Inspect();
#endif

		glfwSwapBuffers(_device->GetWindow());

		// Escape hack
		auto joysticks = _input->GetActiveJoysticks();
		for (auto& j : joysticks)
		{
			if(_input->GetJoystickButtonPressed(j, JOYSTICK_BUTTON_BACK))
				return;
		}
	}
}

void CGame::SwapWorld(World* world)
{
	QueueEvent([this, world]()
	{
		if (_world)
			delete _world;
		_world = world;
	});
}

#ifdef INSPECTOR
void CGame::Inspect()
{
	if(_close_inspector)
		return;

	ImGui::GetIO().FontGlobalScale = _settings.InspectorFontSize;

	ImGuiWindowFlags window_flags = 0;
	//window_flags |= ImGuiWindowFlags_NoTitleBar;
	window_flags |= ImGuiWindowFlags_MenuBar;

	ImGui_ImplGlfwGL3_NewFrame();

	bool p_open = true;

	ImGui::BeginMainMenuBar();
	if (ImGui::BeginMenu("Tools"))
	{
		ImGui::MenuItem("Game Inspector", nullptr, &_show_engine_compoents);
		// Just a reminder that this might be useful
		// ImGui::MenuItem("Log", NULL, &show_app_log);
		ImGui::MenuItem("World Inspector", nullptr, &_show_world_inspector);
		ImGui::MenuItem("Settings Inspector", nullptr, &_show_settings);
		ImGui::MenuItem("Profiler", nullptr, &_show_profiler);
#if SHOW_IMGUI
		ImGui::MenuItem("ImGui Test", nullptr, &_show_imgui_test);
#endif
		ImGui::EndMenu();
	}

	if (ImGui::BeginMenu("About"))
	{
		string timestamp = __TIMESTAMP__;
		ImGui::MenuItem(("Built on: " + timestamp).c_str());
		ImGui::MenuItem("Copyright (C) Bojan Endrovski 2017");
		ImGui::EndMenu();
	}

	// Paused button
	if (!_paused)
		_paused = ImGui::Button("||");
	else
		_paused = !ImGui::Button("[>");
	ImGui::SameLine();
	_advanceFrame = ImGui::Button(">|");
	ImGui::SameLine();
	_close_inspector = ImGui::Button("X");
	ImGui::SameLine();
	ImGui::LabelText("Frame Time", "");
	ImGui::SameLine();
	ImGui::ProgressBar(_profiler->GetTimePerFrame() / (1.0 / 60.0));
	ImGui::EndMainMenuBar();

	if (_show_world_inspector)
	{
		ImGui::Begin("World Inspector");
		_world->Inspect();
		ImGui::End();
	}

	if(_show_profiler)
	{
		_profiler->Inspect();
	}

	if (_show_imgui_test)
	{
		ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
		ImGui::ShowTestWindow(&_show_imgui_test);
	}

	if(_show_engine_compoents)
	{
		ImGui::Begin("Game Inspector");
		for (auto& c : _components)
		{
			string name = typeid(*c).name();
			name = StringReplace(name, "class ", "");
			if (ImGui::CollapsingHeader(name.c_str()))
			{
				c->Inspect();
			}
		}
		ImGui::End();
	}

	if (_show_settings)
	{
		ImGui::Begin("Settings Inspector");
		_settings.Inspect();
		ImGui::End();
	}

	ImGui::Render();
}
#endif

/*
void CGame::Update()
{
	ASSERT(_initialized);
}

void CGame::Render()
{
	ASSERT(_initialized);
}
*/<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <policy/feerate.h>

#include <tinyformat.h>

CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_)
{
    assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
    int64_t nSize = int64_t(nBytes_);

    if (nSize > 0)
        nSatoshisPerK = nFeePaid * 1000 / nSize;
    else
        nSatoshisPerK = 0;
}

CAmount CFeeRate::GetFee(size_t nBytes_) const
{
    if((nBytes_*1000) > uint64_t(std::numeric_limits<int64_t>::max()))
        return 0;
    if((nSatoshisPerK*1000) > std::numeric_limits<int64_t>::max())
        return 0;
    assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
    int64_t nSize = int64_t(nBytes_);

    CAmount nFee = nSatoshisPerK * nSize / 1000;

    if (nFee == 0 && nSize != 0) {
        if (nSatoshisPerK > 0)
            nFee = CAmount(1);
        if (nSatoshisPerK < 0)
            nFee = CAmount(-1);
    }

    return nFee;
}

std::string CFeeRate::ToString(const FeeEstimateMode& fee_estimate_mode) const
{
    switch (fee_estimate_mode) {
    case FeeEstimateMode::SAT_B:  return strprintf("%d.%03d %s/B", nSatoshisPerK / 1000, nSatoshisPerK % 1000, CURRENCY_ATOM);
    default:                      return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT);
    }
}
<commit_msg>Update feerate.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <policy/feerate.h>

#include <tinyformat.h>

CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_)
{
    assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
    int64_t nSize = int64_t(nBytes_);

    if (nSize > 0)
        nSatoshisPerK = nFeePaid * 1000 / nSize;
    else
        nSatoshisPerK = 0;
}

CAmount CFeeRate::GetFee(size_t nBytes_) const
{
    if(nBytes_ > uint64_t(std::numeric_limits<int64_t>::max()/1000))
        return 0;
    if(nSatoshisPerK > std::numeric_limits<int64_t>::max()/1000)
        return 0;
    assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
    int64_t nSize = int64_t(nBytes_);

    CAmount nFee = nSatoshisPerK * nSize / 1000;

    if (nFee == 0 && nSize != 0) {
        if (nSatoshisPerK > 0)
            nFee = CAmount(1);
        if (nSatoshisPerK < 0)
            nFee = CAmount(-1);
    }

    return nFee;
}

std::string CFeeRate::ToString(const FeeEstimateMode& fee_estimate_mode) const
{
    switch (fee_estimate_mode) {
    case FeeEstimateMode::SAT_B:  return strprintf("%d.%03d %s/B", nSatoshisPerK / 1000, nSatoshisPerK % 1000, CURRENCY_ATOM);
    default:                      return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT);
    }
}
<|endoftext|>


<commit_before>#include "prog_translator.h"

#include <algorithm>

#include "CoinPackedVector.hpp"
#include "OsiSolverInterface.hpp"

#include "cyc_limits.h"
#include "exchange_graph.h"

namespace cyclus {

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,
                               bool exclusive)
    :  g_(g), iface_(iface), excl_(exclusive) {
  arc_offset_ = g_->arcs().size();
  int n_cols = arc_offset_ + g_->request_groups().size();
  ctx_.obj_coeffs.resize(n_cols);
  ctx_.col_ubs.resize(n_cols);
  ctx_.col_lbs.resize(n_cols);
  ctx_.m = CoinPackedMatrix(false, 0, 0);
  min_row_coeff_ = std::numeric_limits<double>::max();
  max_obj_coeff_ = 0;
  cost_add_ = 1;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Translate() {
  // number of variables = number of arcs + 1 faux arc per request group
  int n_cols = g_->arcs().size() + g_->request_groups().size();
  ctx_.m.setDimensions(0, n_cols);

  bool request;
  std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();
  for (int i = 0; i != sgs.size(); i++) {
    request = false;
    XlateGrp_(sgs[i].get(), request);
  }

  std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();
  for (int i = 0; i != rgs.size(); i++) {
    request = true;
    XlateGrp_(rgs[i].get(), request);
  }

  // add each false arc
  double inf = iface_->getInfinity();
  double max_cost = max_obj_coeff_ / min_row_coeff_ + cost_add_;
  for (int i = g_->arcs().size(); i != arc_offset_; i++) {
    ctx_.obj_coeffs[i] = max_cost;
    ctx_.col_lbs[i] = 0;
    ctx_.col_ubs[i] = inf;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Populate() {
  iface_->setObjSense(1.0); // minimize

  // load er up!
  iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],
                      &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);

  if (excl_) {
    std::vector<Arc>& arcs = g_->arcs();
    for (int i = 0; i != arcs.size(); i++) {
      Arc& a = arcs[i];
      if (a.exclusive()) {
        iface_->setInteger(g_->arc_ids()[a]);
      }
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::ToProg() {
  Translate();
  Populate();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {
  double inf = iface_->getInfinity();
  std::vector<double>& caps = grp->capacities();

  std::vector<CoinPackedVector> cap_rows;
  std::vector<CoinPackedVector> excl_rows;
  for (int i = 0; i != caps.size(); i++) {
    cap_rows.push_back(CoinPackedVector());
  }

  std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();
  for (int i = 0; i != nodes.size(); i++) {
    std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;
    std::map<Arc, std::vector<double> >::iterator cap_it;

    // add each arc
    for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {
      const Arc& a = cap_it->first;
      std::vector<double>& ucaps = cap_it->second;
      int arc_id = g_->arc_ids()[a];

      // add each unit capacity coefficient
      for (int j = 0; j != ucaps.size(); j++) {
        double coeff = ucaps[j];
        if (excl_ && a.exclusive()) {
          coeff *= a.excl_val();
        }

        cap_rows[j].insert(arc_id, coeff);

        double compare = coeff;// / caps[j];
        if (min_row_coeff_ > compare) {
          min_row_coeff_ = compare;
        }
      }

      if (request) {
        // add obj coeff for arc
        double pref = nodes[i]->prefs[a];
        double qty = std::min(nodes[i]->max_qty, inf);
        double obj_coeff = a.exclusive() ? a.excl_val() / pref  : 1 / pref;
        if (max_obj_coeff_ < obj_coeff) {
          max_obj_coeff_ = obj_coeff;
        }
        ctx_.obj_coeffs[arc_id] = obj_coeff;
        ctx_.col_lbs[arc_id] = 0;
        ctx_.col_ubs[arc_id] = a.exclusive() ? 1 : qty;
      }
    }
  }

  int faux_id;
  if (request) {
    faux_id = arc_offset_++;
  }

  // add all capacity rows
  for (int i = 0; i != cap_rows.size(); i++) {
    if (request) {
      cap_rows[i].insert(faux_id, 1.0); // faux arc
    }

    ctx_.row_lbs.push_back(request ? caps[i] : 0);
    ctx_.row_ubs.push_back(request ? inf : caps[i]);
    ctx_.m.appendRow(cap_rows[i]);
  }

  // add exclusive arcs
  std::vector< std::vector<ExchangeNode::Ptr> >& exngs =
      grp->excl_node_groups();
  for (int i = 0; i != exngs.size(); i++) {
    CoinPackedVector excl_row;
    std::vector<ExchangeNode::Ptr>& nodes = exngs[i];
    for (int j = 0; j != nodes.size(); j++) {
      std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];
      for (int k = 0; k != arcs.size(); k++) {
        excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);
      }
    }
    if (excl_row.getNumElements() > 0) {
      excl_rows.push_back(excl_row);
    }
  }

  // add all exclusive rows
  for (int i = 0; i != excl_rows.size(); i++) {
    ctx_.row_lbs.push_back(0.0);
    ctx_.row_ubs.push_back(1.0);
    ctx_.m.appendRow(excl_rows[i]);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::FromProg() {
  const double* sol = iface_->getColSolution();
  std::vector<Arc>& arcs = g_->arcs();
  double flow;
  for (int i = 0; i < arcs.size(); i++) {
    Arc& a = g_->arc_by_id().at(i);
    flow = sol[i];
    flow = (a.exclusive()) ? flow * a.excl_val() : flow;
    if (flow > cyclus::eps()) {
      g_->AddMatch(a, flow);
    }
  }
}

} // namespace cyclus
<commit_msg>qty->col_ub<commit_after>#include "prog_translator.h"

#include <algorithm>

#include "CoinPackedVector.hpp"
#include "OsiSolverInterface.hpp"

#include "cyc_limits.h"
#include "exchange_graph.h"

namespace cyclus {

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,
                               bool exclusive)
    :  g_(g), iface_(iface), excl_(exclusive) {
  arc_offset_ = g_->arcs().size();
  int n_cols = arc_offset_ + g_->request_groups().size();
  ctx_.obj_coeffs.resize(n_cols);
  ctx_.col_ubs.resize(n_cols);
  ctx_.col_lbs.resize(n_cols);
  ctx_.m = CoinPackedMatrix(false, 0, 0);
  min_row_coeff_ = std::numeric_limits<double>::max();
  max_obj_coeff_ = 0;
  cost_add_ = 1;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Translate() {
  // number of variables = number of arcs + 1 faux arc per request group
  int n_cols = g_->arcs().size() + g_->request_groups().size();
  ctx_.m.setDimensions(0, n_cols);

  bool request;
  std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();
  for (int i = 0; i != sgs.size(); i++) {
    request = false;
    XlateGrp_(sgs[i].get(), request);
  }

  std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();
  for (int i = 0; i != rgs.size(); i++) {
    request = true;
    XlateGrp_(rgs[i].get(), request);
  }

  // add each false arc
  double inf = iface_->getInfinity();
  double max_cost = max_obj_coeff_ / min_row_coeff_ + cost_add_;
  for (int i = g_->arcs().size(); i != arc_offset_; i++) {
    ctx_.obj_coeffs[i] = max_cost;
    ctx_.col_lbs[i] = 0;
    ctx_.col_ubs[i] = inf;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Populate() {
  iface_->setObjSense(1.0); // minimize

  // load er up!
  iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],
                      &ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);

  if (excl_) {
    std::vector<Arc>& arcs = g_->arcs();
    for (int i = 0; i != arcs.size(); i++) {
      Arc& a = arcs[i];
      if (a.exclusive()) {
        iface_->setInteger(g_->arc_ids()[a]);
      }
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::ToProg() {
  Translate();
  Populate();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {
  double inf = iface_->getInfinity();
  std::vector<double>& caps = grp->capacities();

  std::vector<CoinPackedVector> cap_rows;
  std::vector<CoinPackedVector> excl_rows;
  for (int i = 0; i != caps.size(); i++) {
    cap_rows.push_back(CoinPackedVector());
  }

  std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();
  for (int i = 0; i != nodes.size(); i++) {
    std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;
    std::map<Arc, std::vector<double> >::iterator cap_it;

    // add each arc
    for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {
      const Arc& a = cap_it->first;
      std::vector<double>& ucaps = cap_it->second;
      int arc_id = g_->arc_ids()[a];

      // add each unit capacity coefficient
      for (int j = 0; j != ucaps.size(); j++) {
        double coeff = ucaps[j];
        if (excl_ && a.exclusive()) {
          coeff *= a.excl_val();
        }

        cap_rows[j].insert(arc_id, coeff);

        double compare = coeff;// / caps[j];
        if (min_row_coeff_ > compare) {
          min_row_coeff_ = compare;
        }
      }

      if (request) {
        // add obj coeff for arc
        double pref = nodes[i]->prefs[a];
        double col_ub = std::min(nodes[i]->max_qty, inf);
        double obj_coeff = a.exclusive() ? a.excl_val() / pref  : 1 / pref;
        if (max_obj_coeff_ < obj_coeff) {
          max_obj_coeff_ = obj_coeff;
        }
        ctx_.obj_coeffs[arc_id] = obj_coeff;
        ctx_.col_lbs[arc_id] = 0;
        ctx_.col_ubs[arc_id] = a.exclusive() ? 1 : col_ub;
      }
    }
  }

  int faux_id;
  if (request) {
    faux_id = arc_offset_++;
  }

  // add all capacity rows
  for (int i = 0; i != cap_rows.size(); i++) {
    if (request) {
      cap_rows[i].insert(faux_id, 1.0); // faux arc
    }

    ctx_.row_lbs.push_back(request ? caps[i] : 0);
    ctx_.row_ubs.push_back(request ? inf : caps[i]);
    ctx_.m.appendRow(cap_rows[i]);
  }

  // add exclusive arcs
  std::vector< std::vector<ExchangeNode::Ptr> >& exngs =
      grp->excl_node_groups();
  for (int i = 0; i != exngs.size(); i++) {
    CoinPackedVector excl_row;
    std::vector<ExchangeNode::Ptr>& nodes = exngs[i];
    for (int j = 0; j != nodes.size(); j++) {
      std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];
      for (int k = 0; k != arcs.size(); k++) {
        excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);
      }
    }
    if (excl_row.getNumElements() > 0) {
      excl_rows.push_back(excl_row);
    }
  }

  // add all exclusive rows
  for (int i = 0; i != excl_rows.size(); i++) {
    ctx_.row_lbs.push_back(0.0);
    ctx_.row_ubs.push_back(1.0);
    ctx_.m.appendRow(excl_rows[i]);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::FromProg() {
  const double* sol = iface_->getColSolution();
  std::vector<Arc>& arcs = g_->arcs();
  double flow;
  for (int i = 0; i < arcs.size(); i++) {
    Arc& a = g_->arc_by_id().at(i);
    flow = sol[i];
    flow = (a.exclusive()) ? flow * a.excl_val() : flow;
    if (flow > cyclus::eps()) {
      g_->AddMatch(a, flow);
    }
  }
}

} // namespace cyclus
<|endoftext|>