<commit_before>#include <cassert>
#include <iostream>
#include <fstream>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>

// uncomment to enable debugging:
//#define CDEBUG 1
//#define EDEBUG 1

// util for debug
#ifdef CDEBUG
#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"")
#else
#define LOGnl(m,x,y,z,a)
#define LOG(m,x,y,z,a)
#endif
#ifdef EDEBUG
#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#else
#define LOGE(m,x,y,z,a)
#endif
inline void log_message(std::string m, double x, double y, double z, double a, std::string e) {
    std::cerr << m << "," << x << "," << y  << "," << z << "," << a << e;
}

struct trEntry {
    const uint64_t id;
    const uint64_t size;
    double pval;
    size_t nextSeen;
    bool inSchedule;
    bool hasNext;

    trEntry(uint64_t nid, uint64_t nsize)
        : id(nid),
          size(nsize)
    {
        pval = 1;
        nextSeen = 0;
        inSchedule = false;
        hasNext = false;
    };
};

int main(int argc, char* argv[]) {

    // parameters
    std::string path(argv[1]);
    uint64_t cacheSize(atoll(argv[2]));

    // each interval is represented by the index of the trace, where it started
    // store trace here
    std::vector<trEntry> trace;
    // store lastSeen entries here
    std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;
    // store which intervals are in the schedule
    std::unordered_set< size_t > scheduleSet;

    // open trace file
    std::ifstream traceFile(path);
    uint64_t time, id, size, reqc=0;
    // scan trace and initialize data structures
    while(traceFile >> time >> id >> size) {
        // only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)
        if(lastSeen.count(std::make_pair(id,size))>0) {
            // see object second time: add to schedule and initialize datastructures
            // find trace index where this interval started
            const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];
            // add to schedule the start index of this interval
            // TODO MIGHT NOT NEED THIS
            scheduleSet.insert(indexLastSeen);
            trEntry & lastSeenEntry = trace[indexLastSeen];
            // update trace so that we know this interval has finite length
            lastSeenEntry.hasNext = true;
            // update trace so that we know the end time of this interval
            lastSeenEntry.nextSeen = reqc;
            // update trace: this interval is in schedule
            lastSeenEntry.inSchedule = true;
        }
        // store: id, size, bool seen before, pvalue, start of this interval (if started)
        trace.emplace_back(id,size);
        lastSeen[std::make_pair(id,size)]=reqc++;
    }

    // free memory
    lastSeen.clear();
    std::cerr << "parsed trace\n";

    // DEBUG print trace
#ifdef CDEBUG
    reqc = 0;
    LOGnl("TRACE",0,0,0,0);
    for(auto & curEntry : trace) {
        LOGnl(" ",curEntry.id,curEntry.size,0,curEntry.nextSeen);
    }
#endif
    // END DEBUG

    // create feasible schedule by excluding worst feasibility violations
    // i.e., select largest delta in every iteration

    // store excluded intervals in a stack for later
    std::stack<size_t> excluded;

    // delta data structures
    int64_t curDelta;
    int64_t deltaStar;
    size_t timeStar;
    // map: intersecting interval set
    std::map<std::pair<uint64_t, uint64_t>, size_t> curI; //intersecting intervals at current time
    std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; // intersectin intervals at timeStar

    // iterate (every iteration removes one interval, so max iteration count = trace size)
    for(size_t i=0; i<trace.size(); i++) {

        // find highest delta
        reqc = 0;
        // iterate over all time instances (we can skip the last one)

        maxI.clear();
        curDelta = -cacheSize;
        deltaStar = -cacheSize;
        timeStar = 0;
        for(size_t j=0; j<trace.size(); j++) {
            trEntry & curEntry = trace[j];

            // if no next request and in intersecting intervals -> remove
            if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
                curI.erase(std::make_pair(curEntry.id,curEntry.size));
                curDelta -= curEntry.size;
                assert(!curEntry.inSchedule);
            }

            // if in schedule -> update curI
            if(curEntry.inSchedule) {

                // if not already in current intersecting set
                if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
                    curDelta += curEntry.size;
                } // else: don't need update the size/width

                // add to current intersecting set
                curI[std::make_pair(curEntry.id,curEntry.size)] = j;

                // check if we need to update deltaStar
                if(curDelta > deltaStar) {
                    deltaStar = curDelta;
                    timeStar = j;
                    // copy intersecting set
                    maxI = curI;
                }
            }

#ifdef CDEBUG
            for(auto it: curI) {
                trEntry & curEntry = trace[it.second];
                LOG("|",curEntry.id,curEntry.size,0,0);
            }
            LOGnl("|  TW ",curDelta,j,deltaStar,timeStar);
#endif
        }

        // check if we found a feasible solution
        if(deltaStar <= 0)
            break;

        curI.clear();
        assert(maxI.size()>0);
        assert(deltaStar > 0);
        assert(timeStar > 0); // first time interval can't be the unstable one

        LOGnl("\nd*,t*",deltaStar,timeStar,0,0);
        std::cout << "d*" << deltaStar << " t* " << timeStar << "\n";

        // find smallest rho so that p2 reaches zero
        double rho = 1;
        size_t toExclude = 0;
        for(auto & vit : maxI) {
            trEntry & curEntry = trace[vit.second];
            const double thisRho = curEntry.pval/static_cast<double>(curEntry.size);
            if(thisRho <= rho) {
                rho = thisRho;
                toExclude = vit.second;
                LOGE("mrho",rho,vit.second,curEntry.pval,curEntry.size);
            }
        }
        assert(rho < 1);
        LOGnl("min rho ",rho,0,0,0);
        //        std::cout << " mrho " << rho << "\n";

        // update p2, exclude intervals with p2=0 from schedule
        for(auto & vit : maxI) {
            trEntry & curEntry = trace[vit.second];

            // if (min-rho-entry or p2==0): we need the first check due to double rounding errors
            if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {
                LOGnl("exclude (t,id,size,p2)",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);
                curEntry.pval = 0;
                curEntry.inSchedule = false;
                // add current interval to excluded ones
                excluded.push(vit.second);
                // delete from current schedule
                scheduleSet.erase(vit.second);
            } else {
                // p2 >= 0
                curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; // pval = pval - p1
            }
        }
    }
    maxI.clear();
    std::cerr << "found feasible schedule\n";
    std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";

    // we now have a feasible schedule, which might not be maximal

    while (!excluded.empty())
    {
        const size_t firstSeen = excluded.top();
        trEntry & newEntry = trace[excluded.top()];
        curI.clear();
        curDelta = -cacheSize;
        deltaStar = -cacheSize;

        for(size_t j=0; j<trace.size(); j++) {
            trEntry & curEntry = trace[j];

            // if no next request and in intersecting intervals -> remove
            if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
                curI.erase(std::make_pair(curEntry.id,curEntry.size));
                curDelta -= curEntry.size;
                assert(!curEntry.inSchedule);
            }

            // if in schedule -> update curI
            if(j==excluded.top() || curEntry.inSchedule) {

                // if not already in current intersecting set
                if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
                    curDelta += curEntry.size;
                } // else: don't need update the size/width

                // add to current intersecting set
                curI[std::make_pair(curEntry.id,curEntry.size)] = j;

                // check if we need to update deltaStar
                if(curDelta > deltaStar) {
                    deltaStar = curDelta;
                }
            }
        }
        // if still feasible add excluded.top() to schedule
        if(deltaStar <=0) {
            newEntry.inSchedule = true;
            scheduleSet.insert(excluded.top());
        }

        // pop stack
        excluded.pop();
    }

    std::cerr << "found maximal schedule\n";

    std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";

    return 0;
}
<commit_msg>less cout output<commit_after>#include <cassert>
#include <iostream>
#include <fstream>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>

// uncomment to enable debugging:
//#define CDEBUG 1
//#define EDEBUG 1

// util for debug
#ifdef CDEBUG
#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,"")
#else
#define LOGnl(m,x,y,z,a)
#define LOG(m,x,y,z,a)
#endif
#ifdef EDEBUG
#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,"\n")
#else
#define LOGE(m,x,y,z,a)
#endif
inline void log_message(std::string m, double x, double y, double z, double a, std::string e) {
    std::cerr << m << "," << x << "," << y  << "," << z << "," << a << e;
}

struct trEntry {
    const uint64_t id;
    const uint64_t size;
    double pval;
    size_t nextSeen;
    bool inSchedule;
    bool hasNext;

    trEntry(uint64_t nid, uint64_t nsize)
        : id(nid),
          size(nsize)
    {
        pval = 1;
        nextSeen = 0;
        inSchedule = false;
        hasNext = false;
    };
};

int main(int argc, char* argv[]) {

    // parameters
    std::string path(argv[1]);
    uint64_t cacheSize(atoll(argv[2]));

    // each interval is represented by the index of the trace, where it started
    // store trace here
    std::vector<trEntry> trace;
    // store lastSeen entries here
    std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;
    // store which intervals are in the schedule
    std::unordered_set< size_t > scheduleSet;

    // open trace file
    std::ifstream traceFile(path);
    uint64_t time, id, size, reqc=0;
    // scan trace and initialize data structures
    while(traceFile >> time >> id >> size) {
        // only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)
        if(lastSeen.count(std::make_pair(id,size))>0) {
            // see object second time: add to schedule and initialize datastructures
            // find trace index where this interval started
            const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];
            // add to schedule the start index of this interval
            // TODO MIGHT NOT NEED THIS
            scheduleSet.insert(indexLastSeen);
            trEntry & lastSeenEntry = trace[indexLastSeen];
            // update trace so that we know this interval has finite length
            lastSeenEntry.hasNext = true;
            // update trace so that we know the end time of this interval
            lastSeenEntry.nextSeen = reqc;
            // update trace: this interval is in schedule
            lastSeenEntry.inSchedule = true;
        }
        // store: id, size, bool seen before, pvalue, start of this interval (if started)
        trace.emplace_back(id,size);
        lastSeen[std::make_pair(id,size)]=reqc++;
    }

    // free memory
    lastSeen.clear();
    std::cerr << "parsed trace\n";

    // DEBUG print trace
#ifdef CDEBUG
    reqc = 0;
    LOGnl("TRACE",0,0,0,0);
    for(auto & curEntry : trace) {
        LOGnl(" ",curEntry.id,curEntry.size,0,curEntry.nextSeen);
    }
#endif
    // END DEBUG

    // create feasible schedule by excluding worst feasibility violations
    // i.e., select largest delta in every iteration

    // store excluded intervals in a stack for later
    std::stack<size_t> excluded;

    // delta data structures
    int64_t curDelta;
    int64_t deltaStar;
    size_t timeStar;
    // map: intersecting interval set
    std::map<std::pair<uint64_t, uint64_t>, size_t> curI; //intersecting intervals at current time
    std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; // intersectin intervals at timeStar

    // iterate (every iteration removes one interval, so max iteration count = trace size)
    for(size_t i=0; i<trace.size(); i++) {

        // find highest delta
        reqc = 0;
        // iterate over all time instances (we can skip the last one)

        maxI.clear();
        curDelta = -cacheSize;
        deltaStar = -cacheSize;
        timeStar = 0;
        for(size_t j=0; j<trace.size(); j++) {
            trEntry & curEntry = trace[j];

            // if no next request and in intersecting intervals -> remove
            if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
                curI.erase(std::make_pair(curEntry.id,curEntry.size));
                curDelta -= curEntry.size;
                assert(!curEntry.inSchedule);
            }

            // if in schedule -> update curI
            if(curEntry.inSchedule) {

                // if not already in current intersecting set
                if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
                    curDelta += curEntry.size;
                } // else: don't need update the size/width

                // add to current intersecting set
                curI[std::make_pair(curEntry.id,curEntry.size)] = j;

                // check if we need to update deltaStar
                if(curDelta > deltaStar) {
                    deltaStar = curDelta;
                    timeStar = j;
                    // copy intersecting set
                    maxI = curI;
                }
            }

#ifdef CDEBUG
            for(auto it: curI) {
                trEntry & curEntry = trace[it.second];
                LOG("|",curEntry.id,curEntry.size,0,0);
            }
            LOGnl("|  TW ",curDelta,j,deltaStar,timeStar);
#endif
        }

        // check if we found a feasible solution
        if(deltaStar <= 0)
            break;

        curI.clear();
        assert(maxI.size()>0);
        assert(deltaStar > 0);
        assert(timeStar > 0); // first time interval can't be the unstable one

        LOGnl("\nd*,t*",deltaStar,timeStar,0,0);

        // find smallest rho so that p2 reaches zero
        double rho = 1;
        size_t toExclude = 0;
        for(auto & vit : maxI) {
            trEntry & curEntry = trace[vit.second];
            const double thisRho = curEntry.pval/static_cast<double>(curEntry.size);
            if(thisRho <= rho) {
                rho = thisRho;
                toExclude = vit.second;
                LOGE("mrho",rho,vit.second,curEntry.pval,curEntry.size);
            }
        }
        assert(rho < 1);
        LOGnl("min rho ",rho,0,0,0);

        // update p2, exclude intervals with p2=0 from schedule
        for(auto & vit : maxI) {
            trEntry & curEntry = trace[vit.second];

            // if (min-rho-entry or p2==0): we need the first check due to double rounding errors
            if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {
                LOGnl("exclude (t,id,size,p2)",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);
                curEntry.pval = 0;
                curEntry.inSchedule = false;
                // add current interval to excluded ones
                excluded.push(vit.second);
                // delete from current schedule
                scheduleSet.erase(vit.second);
            } else {
                // p2 >= 0
                curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; // pval = pval - p1
            }
        }
    }
    maxI.clear();
    std::cerr << "found feasible schedule\n";
    std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";

    // we now have a feasible schedule, which might not be maximal

    while (!excluded.empty())
    {
        const size_t firstSeen = excluded.top();
        trEntry & newEntry = trace[excluded.top()];
        curI.clear();
        curDelta = -cacheSize;
        deltaStar = -cacheSize;

        for(size_t j=0; j<trace.size(); j++) {
            trEntry & curEntry = trace[j];

            // if no next request and in intersecting intervals -> remove
            if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {
                curI.erase(std::make_pair(curEntry.id,curEntry.size));
                curDelta -= curEntry.size;
                assert(!curEntry.inSchedule);
            }

            // if in schedule -> update curI
            if(j==excluded.top() || curEntry.inSchedule) {

                // if not already in current intersecting set
                if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {
                    curDelta += curEntry.size;
                } // else: don't need update the size/width

                // add to current intersecting set
                curI[std::make_pair(curEntry.id,curEntry.size)] = j;

                // check if we need to update deltaStar
                if(curDelta > deltaStar) {
                    deltaStar = curDelta;
                }
            }
        }
        // if still feasible add excluded.top() to schedule
        if(deltaStar <=0) {
            newEntry.inSchedule = true;
            scheduleSet.insert(excluded.top());
        }

        // pop stack
        excluded.pop();
    }

    std::cerr << "found maximal schedule\n";
    std::cout << "hitc " << scheduleSet.size() << " reqc " << trace.size() << " OHR " << static_cast<double>(scheduleSet.size())/trace.size() << "\n";

    return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "schedule.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    marks_select();
    schedule_show();
    QString name_day[] = {"понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресение"};
    QString h1_text = "Сегодня";

    h1_text.append(", ");
    h1_text.append(current_date.toString("d MMM yyyy"));
    h1_text.append(", ");
    h1_text.append(name_day[day_week-1]);
    h1_text.append(", идет ");
    h1_text.append(QString::number(cur_week));
    h1_text.append("-ая неделя учебы");
    ui->h1_main->setText(h1_text);

    ui->form_save_lable->hide();
    ui->dateEdit->setDate(current_date);

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));

    for (int i = 1; i <= 6; i++) //назначаем одинаковые сигналы всем кнопкам
    {
        QPushButton *butt = findChild<QPushButton *>("sch_" + QString::number(i));
        if (butt == nullptr) continue;  //если объект не найден
        connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));
    }

    QPixmap myPixmap("C:/qtprojects/curs/course_2016.git/tem2.jpg"); //фотография
    ui->photo->setPixmap(myPixmap);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::db_connect()
{
    QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
    dbase.setDatabaseName("C:/qtprojects/curs/course_2016.git/mydatabase.sqlite");
    if (!dbase.open())
    {
             qDebug() << "Ошибка открытия базы данных!";

    }
    else
    {
        _db_connect = 1; //если база данных успешно подключена, то меняем параметр на 1
    }
}

void MainWindow::marks_select()
{
     if(!_db_connect)db_connect(); //проверка подключения к базе
     marks_text = ""; // обнуляем переменную

     QSqlQuery a_query; // переменная для запроса

     if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
     {
             qDebug() << "Ошибка выполнения запроса SELECT";
     }

     QSqlRecord res = a_query.record(); //результат запроса

     while (a_query.next())
     {
         marks_text.append("\n\n"); //отступ от заметок
         marks_text.append(a_query.value(res.indexOf("text")).toString());
     }

     //if(marks_text == "") marks_text = "Заметок на сегодня нет!";

     ui->marks_conteiner->setText(marks_text);
}

void MainWindow::sch_select(int day_week, int week)
{
     if(day_week == 7)
     {
         sch_text = "Ура! Cегодня пар нет!";
         return;
     }
     int type_week = 1;
     if(week % 2 == 0) type_week = 2;
     if(!_db_connect)db_connect(); //проверка подключения к базе
     sch_text = ""; // обнуляем переменную

     QSqlQuery a_query; // переменная для запроса
     QString str_select; //текст запроса

     if(type_week == 2) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5";
     if(type_week == 1) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5,5";
     QString str = str_select.arg(day_week);

     if (!a_query.exec(str))
     {
             qDebug() << "Ошибка выполнения запроса SELECT";
     }

     QSqlRecord res = a_query.record(); //результат запроса
    int i = 1; //счетчик пар
     while (a_query.next())
     {
         sch_text.append(QString::number(i));
         sch_text.append(". ");
         QString para = a_query.value(res.indexOf("name")).toString();
         if(para == "") sch_text.append("-"); else sch_text.append(para);
         sch_text.append("\n\n");
         i++;
     }
     if(sch_text == "") sch_text = "Ура! Cегодня пар нет!";
}

void MainWindow::send_form()
{
    mark = ui->textEdit->toPlainText();
    mark = mark.simplified(); //убираем лишние пробелы из строки

    form_date = ui->dateEdit->text();

    if(mark == "")
    {
        ui->form_save_lable->setText("Введите текст заметки");
        ui->form_save_lable->show();
        return;
    }

    if(!_db_connect)db_connect(); //проверка подключения к базе

    QSqlQuery a_query;

    QString str_insert = "INSERT INTO marks(text,time) "
                "VALUES ('%1', '%2');";
    QString str = str_insert.arg(mark)
            .arg(form_date);

    bool b = a_query.exec(str);

    if (!b)
    {
        qDebug() << "Ошибка выполнения запроса INSERT";
    }

    ui->textEdit->clear();
    ui->dateEdit->setDate(current_date);
    ui->form_save_lable->setText("Заметка сохранена!");
    ui->form_save_lable->show();
    marks_select();
}
void MainWindow::open_sch()
{
    QObject* obj = QObject::sender(); //объект, который запустил слот

    QString obj_name = obj->objectName(); // имя объекта

    int day;

    if(obj_name == "sch_1") day = 1;
    else if(obj_name == "sch_2") day = 2;
    else if(obj_name == "sch_3") day = 3;
    else if(obj_name == "sch_4") day = 4;
    else if(obj_name == "sch_5") day = 5;
    else if(obj_name == "sch_6") day = 6;

    schedule sch(this,day);
    connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); //коннектор обновления расписания в главном окне
    sch.exec();
}
void MainWindow::schedule_show()
{
    sch_select(day_week,cur_week); //выборка расписания на текущий день из таблицы
    ui->sch_output->setText(sch_text); //вывод в lable в главное окно
}

void MainWindow::date()
{
    QDate start_date1;
    start_date1.setDate(year, 9, 1);
    QDate start_date2;
    start_date2.setDate(year, 9, 1); //здесь я задумался, как же определить день начала занятий или дать возможность выбора пользователю?

}
<commit_msg>изменение функции date<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "schedule.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    db_connect();
    bool res_date = date();
    marks_select();
    if (!res_date) schedule_show(); //если каникулы или сессия не выводим расписание
    QString name_day[] = {"понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресение"};
    QString h1_text = "Сегодня";

    h1_text.append(", ");
    h1_text.append(current_date.toString("d MMM yyyy"));
    h1_text.append(", ");
    h1_text.append(name_day[day_week-1]);

    if(!res_date)
    {
        h1_text.append(", идет ");
        h1_text.append(QString::number(cur_week));
        h1_text.append("-ая неделя учебы");
    }

    ui->h1_main->setText(h1_text);

    ui->form_save_lable->hide();
    ui->dateEdit->setDate(current_date);

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));

    for (int i = 1; i <= 6; i++) //назначаем одинаковые сигналы всем кнопкам
    {
        QPushButton *butt = findChild<QPushButton *>("sch_" + QString::number(i));
        if (butt == nullptr) continue;  //если объект не найден
        connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));
    }

    QPixmap myPixmap("C:/qtprojects/curs/course_2016.git/tem2.jpg"); //фотография
    ui->photo->setPixmap(myPixmap);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::db_connect()
{
    QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE");
    dbase.setDatabaseName("C:/qtprojects/curs/course_2016.git/mydatabase.sqlite");
    if (!dbase.open())
    {
             qDebug() << "Ошибка открытия базы данных!";

    }
}

void MainWindow::marks_select()
{
     marks_text = ""; // обнуляем переменную

     QSqlQuery a_query; // переменная для запроса

     if (!a_query.exec("SELECT * FROM marks WHERE time = date('now')"))
     {
             qDebug() << "Ошибка выполнения запроса SELECT marks";
     }

     QSqlRecord res = a_query.record(); //результат запроса

     while (a_query.next())
     {
         marks_text.append("\n\n"); //отступ от заметок
         marks_text.append(a_query.value(res.indexOf("text")).toString());
     }

     //if(marks_text == "") marks_text = "Заметок на сегодня нет!";

     ui->marks_conteiner->setText(marks_text);
}

void MainWindow::sch_select(int day_week, int week)
{
     if(day_week == 7)
     {
         sch_text = "Ура! Cегодня пар нет!";
         return;
     }
     int type_week = 1;
     if(week % 2 == 0) type_week = 2;
     sch_text = ""; // обнуляем переменную

     QSqlQuery a_query; // переменная для запроса
     QString str_select; //текст запроса

     if(type_week == 2) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5";
     if(type_week == 1) str_select = "SELECT * FROM schedule WHERE day = %1 LIMIT 5,5";
     QString str = str_select.arg(day_week);

     if (!a_query.exec(str))
     {
             qDebug() << "Ошибка выполнения запроса SELECT schedule";
     }

     QSqlRecord res = a_query.record(); //результат запроса
    int i = 1; //счетчик пар
     while (a_query.next())
     {
         sch_text.append(QString::number(i));
         sch_text.append(". ");
         QString para = a_query.value(res.indexOf("name")).toString();
         if(para == "") sch_text.append("-"); else sch_text.append(para);
         sch_text.append("\n\n");
         i++;
     }
     if(sch_text == "") sch_text = "Ура! Cегодня пар нет!";
}

void MainWindow::send_form()
{
    mark = ui->textEdit->toPlainText();
    mark = mark.simplified(); //убираем лишние пробелы из строки

    form_date = ui->dateEdit->text();

    if(mark == "")
    {
        ui->form_save_lable->setText("Введите текст заметки");
        ui->form_save_lable->show();
        return;
    }

    QSqlQuery a_query;

    QString str_insert = "INSERT INTO marks(text,time) "
                "VALUES ('%1', '%2');";
    QString str = str_insert.arg(mark)
            .arg(form_date);

    bool b = a_query.exec(str);

    if (!b)
    {
        qDebug() << "Ошибка выполнения запроса INSERT marks";
    }

    ui->textEdit->clear();
    ui->dateEdit->setDate(current_date);
    ui->form_save_lable->setText("Заметка сохранена!");
    ui->form_save_lable->show();
    marks_select();
}
void MainWindow::open_sch()
{
    QObject* obj = QObject::sender(); //объект, который запустил слот

    QString obj_name = obj->objectName(); // имя объекта

    int day;

    if(obj_name == "sch_1") day = 1;
    else if(obj_name == "sch_2") day = 2;
    else if(obj_name == "sch_3") day = 3;
    else if(obj_name == "sch_4") day = 4;
    else if(obj_name == "sch_5") day = 5;
    else if(obj_name == "sch_6") day = 6;

    schedule sch(this,day);
    connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); //коннектор обновления расписания в главном окне
    sch.exec();
}
void MainWindow::schedule_show()
{
    sch_select(day_week,cur_week); //выборка расписания на текущий день из таблицы
    ui->sch_output->setText(sch_text); //вывод в lable в главное окно
}

bool MainWindow::date()
{
    QSqlQuery a_query; // переменная для запроса

    if (!a_query.exec("SELECT week FROM study_day LIMIT 4"))
    {
            qDebug() << "Ошибка выполнения запроса SELECT week";
    }

    QSqlRecord res = a_query.record(); //результат запроса

    int i=0;
    while (a_query.next())
    {
       study_day[i] = a_query.value(res.indexOf("week")).toInt();
       i++;
    }
    if(week >= study_day[0] && week <= study_day[1]) cur_week = week-study_day[0] + 1; //входит ли текущая неделя в диапазон семестра
    else if(week >= study_day[2] && week <= study_day[3]) cur_week = week-study_day[2] + 1;
    else return 1; //значит каникулы или сессия

    return 0;
}
<|endoftext|>


<commit_before>/*++

Module Name:

    ComputeROC.cpp

Abstract:

   Take a SAM file with simulated reads and compute a ROC curve from it.

Authors:

    Bill Bolosky, December, 2012

Environment:
`
    User mode service.

Revision History:

--*/

#include "stdafx.h"
#include "SAM.h"
#include "Genome.h"
#include "Compat.h"
#include "Read.h"
#include "RangeSplitter.h"
#include "BigAlloc.h"

void usage()
{
    fprintf(stderr,"usage: ComputeROC genomeDirectory inputFile {-b}\n");
    fprintf(stderr,"       -b means to accept reads that match either end of the range regardless of RC\n");
    fprintf(stderr,"       -c means to just count the number of reads that are aligned, not to worry about correctness\n");
    fprintf(stderr,"You can specify only one of -b or -c\n");
  	exit(1);
}

RangeSplitter *rangeSplitter;
volatile _int64 nRunningThreads;
SingleWaiterObject allThreadsDone;
const char *inputFileName;
const Genome *genome;
bool matchBothWays = false;
bool justCount = false;

static const int MaxMAPQ = 70;
const unsigned MaxEditDistance = 100;
struct ThreadContext {
    unsigned    whichThread;

    _int64 countOfReads[MaxMAPQ+1];
    _int64 countOfMisalignments[MaxMAPQ+1];
    _int64 nUnaligned;
    _int64 totalReads;

    _int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
    _int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];

    ThreadContext() {
        nUnaligned = 0;
        totalReads = 0;
        for (int i = 0; i <= MaxMAPQ; i++) {
            countOfReads[i] = countOfMisalignments[i] = 0;
            for (int j = 0; j <= MaxEditDistance; j++) {
                countOfReadsByEditDistance[i][j] = 0;
                countOfMisalignmentsByEditDistance[i][j] = 0;
            }
        }
    }

};

bool inline isADigit(char x) {
    return x >= '0' && x <= '9';
}

void
WorkerThreadMain(void *param)
{
    ThreadContext *context = (ThreadContext *)param;

    _int64 rangeStart, rangeLength;

    SAMReader *samReader = NULL;
    ReaderContext rcontext;
    rcontext.clipping = NoClipping;
    rcontext.genome = genome;
    rcontext.paired = false;
    rcontext.defaultReadGroup = "";
    rcontext.header = NULL;
    while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {
        if (NULL == samReader) {
            SAMReader::readHeader(inputFileName, rcontext);
            samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);
        } else {
            ((ReadReader *)samReader)->reinit(rangeStart, rangeLength);
        }

        AlignmentResult alignmentResult;
        unsigned genomeLocation;
        Direction isRC;
        unsigned mapQ;
        unsigned flag;
        const char *cigar;
        unsigned nextFileToWrite = 0;
        Read read;
        LandauVishkinWithCigar lv;
        while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {

            if (mapQ < 0 || mapQ > MaxMAPQ) {
                fprintf(stderr,"Invalid MAPQ: %d\n",mapQ);
                exit(1);
            }

            context->totalReads++;

            if (0xffffffff == genomeLocation) {
                context->nUnaligned++;
            } else if (!justCount) {
                if (flag & SAM_REVERSE_COMPLEMENT) {
                    read.becomeRC();
                }

                const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);
                if (NULL == piece) {
                    fprintf(stderr,"couldn't find genome piece for offset %u\n",genomeLocation);
                    exit(1);
                }
                unsigned offsetA, offsetB;
                bool matched;

                const unsigned cigarBufLen = 1000;
                char cigarForAligned[cigarBufLen];
                const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1);
                int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);

                if (editDistance == -1 || editDistance > MaxEditDistance) {
                    editDistance = MaxEditDistance;
                }

                //
                // Parse the read ID.  The format is ChrName_OffsetA_OffsetB_?:<more stuff>.  This would be simple to parse, except that
                // ChrName can include "_".  So, we parse it by looking for the first : and then working backward.
                //
                char idBuffer[10000];   // Hopefully big enough.  I'm not worried about malicious input data here.

                memcpy(idBuffer,read.getId(),read.getIdLength());
                idBuffer[read.getIdLength()] = 0;

                const char *firstColon = strchr(idBuffer,':');
                bool badParse = true;
                size_t chrNameLen;
                const char *beginningOfSecondNumber;
                const char *beginningOfFirstNumber; int stage = 0;
                unsigned offsetOfCorrectChromosome;

                if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {
                    //
                    // We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal.  If it's
                    // a digit, then scan backwards through that number.
                    //
                    const char *underscoreBeforeFirstColon = firstColon - 2;
                    while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {
                        underscoreBeforeFirstColon--;
                    }

                    if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {
                        stage = 1;
                        if (isADigit(*(underscoreBeforeFirstColon - 1))) {
                            beginningOfSecondNumber = firstColon - 3;
                            while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {
                                beginningOfSecondNumber--;
                            }
                            beginningOfSecondNumber++; // That loop actually moved us back one char before the beginning;
                        } else {
                            //
                            // There's only one number,  we have two consecutive underscores.
                            //
                            beginningOfSecondNumber = underscoreBeforeFirstColon;
                        }
                        if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {
                            stage = 2;
                            beginningOfFirstNumber = beginningOfSecondNumber - 2;
                            while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {
                                beginningOfFirstNumber--;
                            }
                            beginningOfFirstNumber++; // Again, we went one too far.

                           offsetA = -1;
                           offsetB = -1;

                            if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,"%u",&offsetA) &&
                                ('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,"%u", &offsetB))) {
                                    stage = 3;

                                chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;
                                char correctChromosomeName[1000];
                                memcpy(correctChromosomeName, idBuffer, chrNameLen);
                                correctChromosomeName[chrNameLen] = '\0';

                                if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {
                                    fprintf(stderr, "Couldn't parse chromosome name '%s' from read id\n", correctChromosomeName);
                                } else {
                                    badParse = false;
                                }
                            }
                        }
                    }

                    if (badParse) {
                        fprintf(stderr,"Unable to parse read ID '%s', perhaps this isn't simulated data.  piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\n", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);
                        exit(1);
                    }

                    bool match0 = false;
                    bool match1 = false;
                    if (-1 == offsetA || -1 == offsetB) {
                        matched = false;
                    }  else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {
                        matched = false;
                    } else {
                        if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {
                            matched = true;
                            match0 = true;
                        } else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {
                            matched = true;
                            match1 = true;
                        } else {
                            matched = false;
                            if (flag & SAM_FIRST_SEGMENT) {
                                match0 = true;
                            } else {
                                match1 = true;
                            }
                        }
                    }

                    context->countOfReads[mapQ]++;
                    context->countOfReadsByEditDistance[mapQ][editDistance]++;

                    if (!matched) {
                        context->countOfMisalignments[mapQ]++;
                        context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;

                        if (70 == mapQ || 69 == mapQ) {

                            //
                            // We don't know which offset is correct, because neither one matched.  Just take the one with the lower edit distance.
                            //
                            unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;
                            unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;

                            unsigned correctLocation = 0;
                            const char *correctData = NULL;

                            const char *dataA = genome->getSubstring(correctLocationA, 1);
                            const char *dataB = genome->getSubstring(correctLocationB, 1);
                            int distanceA, distanceB;
                            char cigarA[cigarBufLen];
                            char cigarB[cigarBufLen];

                            cigarA[0] = '*'; cigarA[1] = '\0';
                            cigarB[0] = '*'; cigarB[1] = '\0';

                            if (dataA == NULL) {
                                distanceA = -1;
                            } else {
                                distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);
                            }

                            if (dataB == NULL) {
                                distanceB = -1;
                            } else {
                                distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);
                            }

                            const char *correctGenomeData;
                            char *cigarForCorrect;

                            if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {
                                correctGenomeData = dataA;
                                correctLocation = correctLocationA;
                                cigarForCorrect = cigarA;
                            } else {
                                correctGenomeData = dataB;
                                correctLocation = correctLocationB;
                                cigarForCorrect = cigarB;
                            }

                            printf("%s\t%d\t%s\t%u\t%d\t%s\t*\t*\t100\t%.*s\t%.*s\tAlignedGenomeLocation:%u\tCorrectGenomeLocation: %u\tCigarForCorrect: %s\tCorrectData: %.*s\tAlignedData: %.*s\n",
                                idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(),
                                read.getDataLength(), read.getQuality(),  genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),
                                correctGenomeData, read.getDataLength(), alignedGenomeData);
                        }
                    }
                }
            } // if it was mapped
        } // for each read from the sam reader
    }

     if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {
        SignalSingleWaiterObject(&allThreadsDone);
    }
}

int main(int argc, char * argv[])
{
    BigAllocUseHugePages = false;

    if (3 != argc && 4 != argc) {
		usage();
	}

    if (4 == argc) {
        if (!strcmp(argv[3],"-b")) {
            matchBothWays = true;
        } else if (!strcmp(argv[3], "-c")) {
            justCount = true;
        } else {
            usage();
        }
    }

    static const char *genomeSuffix = "Genome";
	size_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;
	char *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];
	snprintf(fileName,filenameLen,"%s%c%s",argv[1],PATH_SEP,genomeSuffix);
	genome = Genome::loadFromFile(fileName, 0);
	if (NULL == genome) {
		fprintf(stderr,"Unable to load genome from file '%s'\n",fileName);
		return -1;
	}
	delete [] fileName;
	fileName = NULL;

    inputFileName = argv[2];

    unsigned nThreads;
#ifdef _DEBUG
    nThreads = 1;
#else   // _DEBUG
    nThreads = GetNumberOfProcessors();
#endif // _DEBUG

    nRunningThreads = nThreads;

    _int64 fileSize = QueryFileSize(argv[2]);
    rangeSplitter = new RangeSplitter(fileSize, nThreads);

    CreateSingleWaiterObject(&allThreadsDone);
    ThreadContext *contexts = new ThreadContext[nThreads];

    for (unsigned i = 0; i < nThreads; i++) {
        contexts[i].whichThread = i;

        StartNewThread(WorkerThreadMain, &contexts[i]);
    }

    WaitForSingleWaiterObject(&allThreadsDone);

    _int64 nUnaligned = 0;
    _int64 totalReads = 0;
    for (unsigned i = 0; i < nThreads; i++) {
        nUnaligned += contexts[i].nUnaligned;
        totalReads += contexts[i].totalReads;
    }
    printf("%lld reads, %lld unaligned (%0.2f%%)\n", totalReads, nUnaligned, 100. * (double)nUnaligned / (double)totalReads);

    if (justCount) return 0;

    printf("%lld total unaligned\nMAPQ\tnReads\tnMisaligned\n",nUnaligned);

    for (int i = 0; i <= MaxMAPQ; i++) {
        _int64 nReads = 0;
        _int64 nMisaligned = 0;
        for (unsigned j = 0; j < nThreads; j++) {
            nReads += contexts[j].countOfReads[i];
            nMisaligned += contexts[j].countOfMisalignments[i];
        }
        printf("%d\t%lld\t%lld\n", i, nReads, nMisaligned);
    }

    int maxEditDistanceSeen = 0;
    for (unsigned i = 0; i < nThreads; i++) {
    }

	return 0;
}

<commit_msg>update roc to count mapq even on reads even if alignment position is not present<commit_after>/*++

Module Name:

    ComputeROC.cpp

Abstract:

   Take a SAM file with simulated reads and compute a ROC curve from it.

Authors:

    Bill Bolosky, December, 2012

Environment:
`
    User mode service.

Revision History:

--*/

#include "stdafx.h"
#include "SAM.h"
#include "Genome.h"
#include "Compat.h"
#include "Read.h"
#include "RangeSplitter.h"
#include "BigAlloc.h"

void usage()
{
    fprintf(stderr,"usage: ComputeROC genomeDirectory inputFile {-b}\n");
    fprintf(stderr,"       -b means to accept reads that match either end of the range regardless of RC\n");
    fprintf(stderr,"       -c means to just count the number of reads that are aligned, not to worry about correctness\n");
    fprintf(stderr,"You can specify only one of -b or -c\n");
  	exit(1);
}

RangeSplitter *rangeSplitter;
volatile _int64 nRunningThreads;
SingleWaiterObject allThreadsDone;
const char *inputFileName;
const Genome *genome;
bool matchBothWays = false;
bool justCount = false;

static const int MaxMAPQ = 70;
const unsigned MaxEditDistance = 100;
struct ThreadContext {
    unsigned    whichThread;

    _int64 countOfReads[MaxMAPQ+1];
    _int64 countOfMisalignments[MaxMAPQ+1];
    _int64 nUnaligned;
    _int64 totalReads;

    _int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];
    _int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];

    ThreadContext() {
        nUnaligned = 0;
        totalReads = 0;
        for (int i = 0; i <= MaxMAPQ; i++) {
            countOfReads[i] = countOfMisalignments[i] = 0;
            for (int j = 0; j <= MaxEditDistance; j++) {
                countOfReadsByEditDistance[i][j] = 0;
                countOfMisalignmentsByEditDistance[i][j] = 0;
            }
        }
    }

};

bool inline isADigit(char x) {
    return x >= '0' && x <= '9';
}

void
WorkerThreadMain(void *param)
{
    ThreadContext *context = (ThreadContext *)param;

    _int64 rangeStart, rangeLength;

    SAMReader *samReader = NULL;
    ReaderContext rcontext;
    rcontext.clipping = NoClipping;
    rcontext.genome = genome;
    rcontext.paired = false;
    rcontext.defaultReadGroup = "";
    rcontext.header = NULL;
    while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {
        if (NULL == samReader) {
            SAMReader::readHeader(inputFileName, rcontext);
            samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);
        } else {
            ((ReadReader *)samReader)->reinit(rangeStart, rangeLength);
        }

        AlignmentResult alignmentResult;
        unsigned genomeLocation;
        Direction isRC;
        unsigned mapQ;
        unsigned flag;
        const char *cigar;
        unsigned nextFileToWrite = 0;
        Read read;
        LandauVishkinWithCigar lv;
        while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {
  	    if (justCount) {
              context->countOfReads[mapQ]++;
	    }
            if (mapQ < 0 || mapQ > MaxMAPQ) {
                fprintf(stderr,"Invalid MAPQ: %d\n",mapQ);
                exit(1);
            }

            context->totalReads++;

            if (0xffffffff == genomeLocation) {
                context->nUnaligned++;
            } else if (!justCount) {
                if (flag & SAM_REVERSE_COMPLEMENT) {
                    read.becomeRC();
                }

                const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);
                if (NULL == piece) {
                    fprintf(stderr,"couldn't find genome piece for offset %u\n",genomeLocation);
                    exit(1);
                }
                unsigned offsetA, offsetB;
                bool matched;

                const unsigned cigarBufLen = 1000;
                char cigarForAligned[cigarBufLen];
                const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1);
                int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);

                if (editDistance == -1 || editDistance > MaxEditDistance) {
                    editDistance = MaxEditDistance;
                }

                //
                // Parse the read ID.  The format is ChrName_OffsetA_OffsetB_?:<more stuff>.  This would be simple to parse, except that
                // ChrName can include "_".  So, we parse it by looking for the first : and then working backward.
                //
                char idBuffer[10000];   // Hopefully big enough.  I'm not worried about malicious input data here.

                memcpy(idBuffer,read.getId(),read.getIdLength());
                idBuffer[read.getIdLength()] = 0;

                const char *firstColon = strchr(idBuffer,':');
                bool badParse = true;
                size_t chrNameLen;
                const char *beginningOfSecondNumber;
                const char *beginningOfFirstNumber; int stage = 0;
                unsigned offsetOfCorrectChromosome;

                if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {
                    //
                    // We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal.  If it's
                    // a digit, then scan backwards through that number.
                    //
                    const char *underscoreBeforeFirstColon = firstColon - 2;
                    while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {
                        underscoreBeforeFirstColon--;
                    }

                    if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {
                        stage = 1;
                        if (isADigit(*(underscoreBeforeFirstColon - 1))) {
                            beginningOfSecondNumber = firstColon - 3;
                            while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {
                                beginningOfSecondNumber--;
                            }
                            beginningOfSecondNumber++; // That loop actually moved us back one char before the beginning;
                        } else {
                            //
                            // There's only one number,  we have two consecutive underscores.
                            //
                            beginningOfSecondNumber = underscoreBeforeFirstColon;
                        }
                        if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {
                            stage = 2;
                            beginningOfFirstNumber = beginningOfSecondNumber - 2;
                            while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {
                                beginningOfFirstNumber--;
                            }
                            beginningOfFirstNumber++; // Again, we went one too far.

                           offsetA = -1;
                           offsetB = -1;

                            if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,"%u",&offsetA) &&
                                ('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,"%u", &offsetB))) {
                                    stage = 3;

                                chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;
                                char correctChromosomeName[1000];
                                memcpy(correctChromosomeName, idBuffer, chrNameLen);
                                correctChromosomeName[chrNameLen] = '\0';

                                if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {
                                    fprintf(stderr, "Couldn't parse chromosome name '%s' from read id\n", correctChromosomeName);
                                } else {
                                    badParse = false;
                                }
                            }
                        }
                    }

                    if (badParse) {
                        fprintf(stderr,"Unable to parse read ID '%s', perhaps this isn't simulated data.  piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\n", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);
                        exit(1);
                    }

                    bool match0 = false;
                    bool match1 = false;
                    if (-1 == offsetA || -1 == offsetB) {
                        matched = false;
                    }  else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {
                        matched = false;
                    } else {
                        if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {
                            matched = true;
                            match0 = true;
                        } else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {
                            matched = true;
                            match1 = true;
                        } else {
                            matched = false;
                            if (flag & SAM_FIRST_SEGMENT) {
                                match0 = true;
                            } else {
                                match1 = true;
                            }
                        }
                    }

                    context->countOfReads[mapQ]++;
                    context->countOfReadsByEditDistance[mapQ][editDistance]++;

                    if (!matched) {
                        context->countOfMisalignments[mapQ]++;
                        context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;

                        if (70 == mapQ || 69 == mapQ) {

                            //
                            // We don't know which offset is correct, because neither one matched.  Just take the one with the lower edit distance.
                            //
                            unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;
                            unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;

                            unsigned correctLocation = 0;
                            const char *correctData = NULL;

                            const char *dataA = genome->getSubstring(correctLocationA, 1);
                            const char *dataB = genome->getSubstring(correctLocationB, 1);
                            int distanceA, distanceB;
                            char cigarA[cigarBufLen];
                            char cigarB[cigarBufLen];

                            cigarA[0] = '*'; cigarA[1] = '\0';
                            cigarB[0] = '*'; cigarB[1] = '\0';

                            if (dataA == NULL) {
                                distanceA = -1;
                            } else {
                                distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);
                            }

                            if (dataB == NULL) {
                                distanceB = -1;
                            } else {
                                distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);
                            }

                            const char *correctGenomeData;
                            char *cigarForCorrect;

                            if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {
                                correctGenomeData = dataA;
                                correctLocation = correctLocationA;
                                cigarForCorrect = cigarA;
                            } else {
                                correctGenomeData = dataB;
                                correctLocation = correctLocationB;
                                cigarForCorrect = cigarB;
                            }

                            printf("%s\t%d\t%s\t%u\t%d\t%s\t*\t*\t100\t%.*s\t%.*s\tAlignedGenomeLocation:%u\tCorrectGenomeLocation: %u\tCigarForCorrect: %s\tCorrectData: %.*s\tAlignedData: %.*s\n",
                                idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(),
                                read.getDataLength(), read.getQuality(),  genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),
                                correctGenomeData, read.getDataLength(), alignedGenomeData);
                        }
                    }
                }
            } // if it was mapped
        } // for each read from the sam reader
    }

     if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {
        SignalSingleWaiterObject(&allThreadsDone);
    }
}

int main(int argc, char * argv[])
{
    BigAllocUseHugePages = false;

    if (3 != argc && 4 != argc) {
		usage();
	}

    if (4 == argc) {
        if (!strcmp(argv[3],"-b")) {
            matchBothWays = true;
        } else if (!strcmp(argv[3], "-c")) {
            justCount = true;
        } else {
            usage();
        }
    }

    static const char *genomeSuffix = "Genome";
	size_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;
	char *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];
	snprintf(fileName,filenameLen,"%s%c%s",argv[1],PATH_SEP,genomeSuffix);
	genome = Genome::loadFromFile(fileName, 0);
	if (NULL == genome) {
		fprintf(stderr,"Unable to load genome from file '%s'\n",fileName);
		return -1;
	}
	delete [] fileName;
	fileName = NULL;

    inputFileName = argv[2];

    unsigned nThreads;
#ifdef _DEBUG
    nThreads = 1;
#else   // _DEBUG
    nThreads = GetNumberOfProcessors();
#endif // _DEBUG

    nRunningThreads = nThreads;

    _int64 fileSize = QueryFileSize(argv[2]);
    rangeSplitter = new RangeSplitter(fileSize, nThreads);

    CreateSingleWaiterObject(&allThreadsDone);
    ThreadContext *contexts = new ThreadContext[nThreads];

    for (unsigned i = 0; i < nThreads; i++) {
        contexts[i].whichThread = i;

        StartNewThread(WorkerThreadMain, &contexts[i]);
    }

    WaitForSingleWaiterObject(&allThreadsDone);

    _int64 nUnaligned = 0;
    _int64 totalReads = 0;
    for (unsigned i = 0; i < nThreads; i++) {
        nUnaligned += contexts[i].nUnaligned;
        totalReads += contexts[i].totalReads;
    }
    printf("%lld reads, %lld unaligned (%0.2f%%)\n", totalReads, nUnaligned, 100. * (double)nUnaligned / (double)totalReads);

    printf("MAPQ\tnReads\tnMisaligned\n");
    for (int i = 0; i <= MaxMAPQ; i++) {
        _int64 nReads = 0;
        _int64 nMisaligned = 0;
        for (unsigned j = 0; j < nThreads; j++) {
            nReads += contexts[j].countOfReads[i];
            nMisaligned += contexts[j].countOfMisalignments[i];
        }
        printf("%d\t%lld\t%lld\n", i, nReads, nMisaligned);
    }

    int maxEditDistanceSeen = 0;
    for (unsigned i = 0; i < nThreads; i++) {
    }

	return 0;
}

<|endoftext|>


<commit_before>
#undef NDEBUG

#include "ospray/common/OspCommon.h"
#include "apps/common/xml/xml.h"
#include "model.h"

#include "common/sys/filename.h"

namespace ospray {
  namespace particle {
    bool big_endian = false;

    /*! a dump-file we can use for debugging; we'll simply dump each
        parsed particle into this file during parsing */
    FILE *particleDumpFile = NULL;

    struct Particle {
      double x,y,z;
    };
    // struct MPM {
    //   std::vector<vec3f> pos;
    // };
    // MPM mpm;

    double htonlf(double f)
    {
      double ret;
      char *in = (char*)&f;
      char *out = (char*)&ret;
      for (int i=0;i<8;i++)
        out[i] = in[7-i];
      return ret;
    }
    void readParticles(Model *model,
                       size_t numParticles, const std::string &fn, size_t begin, size_t end)
    {
      // std::cout << "#mpm: reading " << numParticles << " particles... " << std::flush;
      // printf("#mpm: reading%7ld particles...",numParticles); fflush(0);
      FILE *file = fopen(fn.c_str(),"rb");
      if (!file) {
        throw std::runtime_error("could not open data file "+fn);
      }
      assert(file);

      fseek(file,begin,SEEK_SET);
      size_t len = end-begin;

      if (len != numParticles*sizeof(Particle)) {
        PING;
        PRINT(len);
        PRINT(numParticles);
        PRINT(len/numParticles);
      }
      // PRINT(len);

      for (int i=0;i<numParticles;i++) {
        Particle p;
        int rc = fread(&p,sizeof(p),1,file);
        if (rc != 1) {
          fclose(file);
          throw std::runtime_error("read partial data "+fn);
        }
#if 1
        if (big_endian) {
          p.x = htonlf(p.x);
          p.y = htonlf(p.y);
          p.z = htonlf(p.z);
        }
#endif
        Model::Atom a;
        a.position = vec3f(p.x,p.y,p.z);
        a.type = model->getAtomType("<unnamed>");

        if (particleDumpFile)
          fwrite(&a,sizeof(a),1,particleDumpFile);

        model->atom.push_back(a);
      }

      std::cout << "\r#osp:uintah: read " << numParticles << " particles (total " << float(model->atom.size()/1e6) << "M)";

      // Particle *particle = new Particle[numParticles];
      // fread(particle,numParticles,sizeof(Particle),file);
      // for (int i=0;i
      // for (int i=0;i<100;i++)
      //   printf("particle %5i: %lf %lf %lf\n",particle[i].x,particle[i].y,particle[i].z);
      fclose(file);
    }

    void parse__Variable(Model *model,
                       const std::string &basePath, xml::Node *var)
    {
      size_t index = -1;
      size_t start = -1;
      size_t end = -1;
      size_t patch = -1;
      size_t numParticles = 0;
      std::string variable;
      std::string filename;
      for (int i=0;i<var->child.size();i++) {
        xml::Node *n = var->child[i];
        if (n->name == "index") {
          index = atoi(n->content.c_str());
        } else if (n->name == "variable") {
          variable = n->content;
        } else if (n->name == "numParticles") {
          numParticles = atol(n->content.c_str());
        } else if (n->name == "patch") {
          patch = atol(n->content.c_str());
        } else if (n->name == "filename") {
          filename = n->content;
        } else if (n->name == "start") {
          start = atol(n->content.c_str());
        } else if (n->name == "end") {
          end = atol(n->content.c_str());
        }
      }

      if (numParticles > 0
          && variable == "p.x"
          /* && index == .... */
          ) {
        readParticles(model,numParticles,basePath+"/"+filename,start,end);
      }
      // PRINT(patch);
      // PRINT(numParticles);
      // PRINT(start);
      // PRINT(filename);
    }

    // pase a "Uintah_Output" node
    // void parse__Uintah_Output(const std::string &basePath, xml::Node *node)
    // {
    //   assert(node->name == "Uintah_Output");
    //   for (int i=0;i<node->child.size();i++) {
    //     xml::Node *c = node->child[i];
    //     assert(c->name == "Variable");
    //     parse__Variable(basePath,c);
    //   }
    // }
    void parse__Uintah_Datafile(Model *model,
                       const std::string &fileName)
    {
      std::string basePath = embree::FileName(fileName).path();

      xml::XMLDoc *doc = NULL;
      try {
        doc = xml::readXML(fileName);
      } catch (std::runtime_error e) {
        static bool warned = false;
        if (!warned) {
          std::cerr << "#osp:uintah: error in opening xml data file: " << e.what() << std::endl;
           std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
           std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
           warned = true;
        }
        return;
      }
      assert(doc);
      assert(doc->child.size() == 1);
      xml::Node *node = doc->child[0];
      assert(node->name == "Uintah_Output");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        assert(c->name == "Variable");
        parse__Variable(model,basePath,c);
      }
      delete doc;
    }
    void parse__Uintah_TimeStep_Data(Model *model,
                                     const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Data");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        assert(c->name == "Datafile");
        for (int j=0;j<c->prop.size();j++) {
          xml::Prop *p = c->prop[j];
          if (p->name == "href") {
            try {
              parse__Uintah_Datafile(model,basePath+"/"+p->value);
            } catch (std::runtime_error e) {
              static bool warned = false;
              if (!warned) {
                std::cerr << "#osp:uintah: error in parsing timestep data: " << e.what() << std::endl;
                std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
                std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
                warned = true;
              }
            }
          }
        }
      }
    }
    void parse__Uintah_TimeStep_Meta(Model *model,
                                     const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Meta");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        if (c->name == "endianness") {
          if (c->content == "big_endian") {
            std::cout << "#osp:uintah: SWITCHING TO BIG_ENDIANNESS" << std::endl;
            big_endian = true;
          }
        }
      }
    }
    void parse__Uintah_timestep(Model *model,
                                const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Uintah_timestep");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        if (c->name == "Meta") {
          parse__Uintah_TimeStep_Meta(model,basePath,c);
        }
        if (c->name == "Data") {
          parse__Uintah_TimeStep_Data(model,basePath,c);
        }
      }
    }
    Model *parse__Uintah_timestep_xml(const std::string &s)
    {
      Model *model = new Model;
      Ref<xml::XMLDoc> doc = xml::readXML(s);

      char *dumpFileName = getenv("OSPRAY_PARTICLE_DUMP_FILE");
      if (dumpFileName)
        particleDumpFile = fopen(dumpFileName,"wb");
      assert(doc);
      assert(doc->child.size() == 1);
      assert(doc->child[0]->name == "Uintah_timestep");
      std::string basePath = embree::FileName(s).path();
      parse__Uintah_timestep(model, basePath, doc->child[0]);
      std::cout << "#osp:mpm: read " << s << " : "
                << model->atom.size() << " particles" << std::endl;

      box3f bounds = embree::empty;
      for (int i=0;i<model->atom.size();i++) {
        bounds.extend(model->atom[i].position);
      }
      std::cout << "#osp:mpm: bounds of particle centers: " << bounds << std::endl;
      model->radius = .002f;
      return model;
    }
  }
}

<commit_msg>can now specify particle dump file for particle viewer<commit_after>
#undef NDEBUG

#include "ospray/common/OspCommon.h"
#include "apps/common/xml/xml.h"
#include "model.h"

#include "common/sys/filename.h"

namespace ospray {
  namespace particle {
    bool big_endian = false;

    /*! a dump-file we can use for debugging; we'll simply dump each
        parsed particle into this file during parsing */
    FILE *particleDumpFile = NULL;
    size_t numDumpedParticles = 0;

    struct Particle {
      double x,y,z;
    };
    // struct MPM {
    //   std::vector<vec3f> pos;
    // };
    // MPM mpm;

    double htonlf(double f)
    {
      double ret;
      char *in = (char*)&f;
      char *out = (char*)&ret;
      for (int i=0;i<8;i++)
        out[i] = in[7-i];
      return ret;
    }
    void readParticles(Model *model,
                       size_t numParticles, const std::string &fn, size_t begin, size_t end)
    {
      // std::cout << "#mpm: reading " << numParticles << " particles... " << std::flush;
      // printf("#mpm: reading%7ld particles...",numParticles); fflush(0);
      FILE *file = fopen(fn.c_str(),"rb");
      if (!file) {
        throw std::runtime_error("could not open data file "+fn);
      }
      assert(file);

      fseek(file,begin,SEEK_SET);
      size_t len = end-begin;

      if (len != numParticles*sizeof(Particle)) {
        PING;
        PRINT(len);
        PRINT(numParticles);
        PRINT(len/numParticles);
      }
      // PRINT(len);

      for (int i=0;i<numParticles;i++) {
        Particle p;
        int rc = fread(&p,sizeof(p),1,file);
        if (rc != 1) {
          fclose(file);
          throw std::runtime_error("read partial data "+fn);
        }
#if 1
        if (big_endian) {
          p.x = htonlf(p.x);
          p.y = htonlf(p.y);
          p.z = htonlf(p.z);
        }
#endif
        Model::Atom a;
        a.position = vec3f(p.x,p.y,p.z);
        a.type = model->getAtomType("<unnamed>");

        if (particleDumpFile) {
          numDumpedParticles++;
          fwrite(&a,sizeof(a),1,particleDumpFile);
        } else
          model->atom.push_back(a);
      }

      std::cout << "\r#osp:uintah: read " << numParticles << " particles (total " << float((numDumpedParticles+model->atom.size())/1e6) << "M)";

      // Particle *particle = new Particle[numParticles];
      // fread(particle,numParticles,sizeof(Particle),file);
      // for (int i=0;i
      // for (int i=0;i<100;i++)
      //   printf("particle %5i: %lf %lf %lf\n",particle[i].x,particle[i].y,particle[i].z);
      fclose(file);
    }

    void parse__Variable(Model *model,
                       const std::string &basePath, xml::Node *var)
    {
      size_t index = -1;
      size_t start = -1;
      size_t end = -1;
      size_t patch = -1;
      size_t numParticles = 0;
      std::string variable;
      std::string filename;
      for (int i=0;i<var->child.size();i++) {
        xml::Node *n = var->child[i];
        if (n->name == "index") {
          index = atoi(n->content.c_str());
        } else if (n->name == "variable") {
          variable = n->content;
        } else if (n->name == "numParticles") {
          numParticles = atol(n->content.c_str());
        } else if (n->name == "patch") {
          patch = atol(n->content.c_str());
        } else if (n->name == "filename") {
          filename = n->content;
        } else if (n->name == "start") {
          start = atol(n->content.c_str());
        } else if (n->name == "end") {
          end = atol(n->content.c_str());
        }
      }

      if (numParticles > 0
          && variable == "p.x"
          /* && index == .... */
          ) {
        readParticles(model,numParticles,basePath+"/"+filename,start,end);
      }
      // PRINT(patch);
      // PRINT(numParticles);
      // PRINT(start);
      // PRINT(filename);
    }

    // pase a "Uintah_Output" node
    // void parse__Uintah_Output(const std::string &basePath, xml::Node *node)
    // {
    //   assert(node->name == "Uintah_Output");
    //   for (int i=0;i<node->child.size();i++) {
    //     xml::Node *c = node->child[i];
    //     assert(c->name == "Variable");
    //     parse__Variable(basePath,c);
    //   }
    // }
    void parse__Uintah_Datafile(Model *model,
                       const std::string &fileName)
    {
      std::string basePath = embree::FileName(fileName).path();

      xml::XMLDoc *doc = NULL;
      try {
        doc = xml::readXML(fileName);
      } catch (std::runtime_error e) {
        static bool warned = false;
        if (!warned) {
          std::cerr << "#osp:uintah: error in opening xml data file: " << e.what() << std::endl;
           std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
           std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
           warned = true;
        }
        return;
      }
      assert(doc);
      assert(doc->child.size() == 1);
      xml::Node *node = doc->child[0];
      assert(node->name == "Uintah_Output");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        assert(c->name == "Variable");
        parse__Variable(model,basePath,c);
      }
      delete doc;
    }
    void parse__Uintah_TimeStep_Data(Model *model,
                                     const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Data");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        assert(c->name == "Datafile");
        for (int j=0;j<c->prop.size();j++) {
          xml::Prop *p = c->prop[j];
          if (p->name == "href") {
            try {
              parse__Uintah_Datafile(model,basePath+"/"+p->value);
            } catch (std::runtime_error e) {
              static bool warned = false;
              if (!warned) {
                std::cerr << "#osp:uintah: error in parsing timestep data: " << e.what() << std::endl;
                std::cerr << "#osp:uintah: continuing parsing, but parts of the data will be missing" << std::endl;
                std::cerr << "#osp:uintah: (only printing first instance of this error; there may be more)" << std::endl;
                warned = true;
              }
            }
          }
        }
      }
    }
    void parse__Uintah_TimeStep_Meta(Model *model,
                                     const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Meta");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        if (c->name == "endianness") {
          if (c->content == "big_endian") {
            std::cout << "#osp:uintah: SWITCHING TO BIG_ENDIANNESS" << std::endl;
            big_endian = true;
          }
        }
      }
    }
    void parse__Uintah_timestep(Model *model,
                                const std::string &basePath, xml::Node *node)
    {
      assert(node->name == "Uintah_timestep");
      for (int i=0;i<node->child.size();i++) {
        xml::Node *c = node->child[i];
        if (c->name == "Meta") {
          parse__Uintah_TimeStep_Meta(model,basePath,c);
        }
        if (c->name == "Data") {
          parse__Uintah_TimeStep_Data(model,basePath,c);
        }
      }
    }
    Model *parse__Uintah_timestep_xml(const std::string &s)
    {
      Model *model = new Model;
      Ref<xml::XMLDoc> doc = xml::readXML(s);

      char *dumpFileName = getenv("OSPRAY_PARTICLE_DUMP_FILE");
      if (dumpFileName)
        particleDumpFile = fopen(dumpFileName,"wb");
      assert(doc);
      assert(doc->child.size() == 1);
      assert(doc->child[0]->name == "Uintah_timestep");
      std::string basePath = embree::FileName(s).path();
      parse__Uintah_timestep(model, basePath, doc->child[0]);
      std::cout << "#osp:mpm: read " << s << " : "
                << model->atom.size() << " particles" << std::endl;

      box3f bounds = embree::empty;
      for (int i=0;i<model->atom.size();i++) {
        bounds.extend(model->atom[i].position);
      }
      std::cout << "#osp:mpm: bounds of particle centers: " << bounds << std::endl;
      model->radius = .002f;
      return model;
    }
  }
}

<|endoftext|>


<commit_before>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#include <cmath>

namespace mjolnir
{

/* Implicit membrane potential & derivative           *
 * potential field dependent on z coordinate.         *
 * tanh is used to represent membrane potential.      *
 *  V(z) = ma * tanh(be * (|z| - th/2))               *
 * dV/dr = (z/|z|) * ma * (cosh^2(be * (|z| - th/2))) *
 * Cutoff ratio ensure 1/1000 accuracy.               */
template<typename traitT>
class ImplicitMembranePotential
{
  public:
    typedef traitT traits_type;
    typedef typename traits_type::real_type real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef real_type parameter_type;

    constexpr static real_type cutoff_ratio = 4.0;

  public:
    ImplicitMembranePotential() = default;
    ImplicitMembranePotential(const real_type th, const real_type ma,
        const real_type be, const std::vector<parameter_type>& hydrophobicities)
        : half_thick_(th * 0.5), interaction_magnitude_(ma),
          bend_(be), hydrophobicities_(hydrophobicities)
    {}

    ImplicitMembranePotential(real_type th, real_type ma,
        real_type be, std::vector<parameter_type>&& hydrophobicities)
        : half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),
          hydrophobicities_(std::move(hydrophobicities))
    {}
    ~ImplicitMembranePotential() = default;

    real_type  half_thick() const noexcept {return half_thick_;}
    real_type& half_thick()       noexcept {return half_thick_;}

    real_type  interaction_magnitude() const noexcept
    {return interaction_magnitude_;}
    real_type& interaction_magnitude() noexcept
    {return interaction_magnitude_;}

    real_type  bend() const noexcept {return bend_;}
    real_type& bend()       noexcept {return bend_;}

    void hydrophobicities_emplace(const parameter_type);

    void set_hydrophobicities(const std::vector<parameter_type>&);
    void set_hydrophobicities(std::vector<parameter_type>&&);

    std::size_t size() const noexcept {return hydrophobicities_.size();}
    void resize (const std::size_t i){hydrophobicities_.resize();}
    void reserve(const std::size_t i){hydrophobicities_.reserve();}
    void clear() {hydrophobicities_.clear();}

    parameter_type&       operator[](const std::size_t i) noexcept
    {return hydrophobicities_[i];}
    parameter_type const& operator[](const std::size_t i) const noexcept
    {return hydrophobicities_[i];}
    parameter_type&       at(const std::size_t i)
    {return hydrophobicities_.at(i);}
    parameter_type const& at(const std::size_t i) const
    {return hydrophobicities_.at(i);}

    real_type potential (const std::size_t i, const real_type z) const;
    real_type derivative(const std::size_t i, const real_type z) const;
    real_type max_cutoff_length() const noexcept;

  private:

    real_type half_thick_;//membrane half of thickness.
    real_type interaction_magnitude_;
    real_type bend_;//bend_ decide the slope of tanh carve.
    std::vector<parameter_type> hydrophobicities_;
};

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::hydrophobicities_emplace(
    const parameter_type hydrophobicity)
{
    hydrophobicities_.emplace_back(hydrophobicity);
    return;
}

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
    const std::vector<parameter_type>& hydrophobicities)
{
    hydrophobicities_ = hydrophobicities;
    return;
}

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
    std::vector<parameter_type>&& hydrophobicities)
{
    hydrophobicities_ = std::move(hydrophobicities);
    return;
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::potential(
    const std::size_t i, const real_type z) const
{
    return hydrophobicities_[i] * interaction_magnitude_ *
        std::tanh(bend_ * (std::abs(z) - half_thick_));
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::derivative(
    const std::size_t i, const real_type z) const
{
    return hydrophobicities_[i] * std::copysign(1.0, z) *
        interaction_magnitude_ * bend_ /
        std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept
{
    return cutoff_ratio / bend_ + half_thick_;
}

}
#endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */
<commit_msg>fix: pass argument to member<commit_after>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL
#include <cmath>

namespace mjolnir
{

/* Implicit membrane potential & derivative           *
 * potential field dependent on z coordinate.         *
 * tanh is used to represent membrane potential.      *
 *  V(z) = ma * tanh(be * (|z| - th/2))               *
 * dV/dr = (z/|z|) * ma * (cosh^2(be * (|z| - th/2))) *
 * Cutoff ratio ensure 1/1000 accuracy.               */
template<typename traitT>
class ImplicitMembranePotential
{
  public:
    typedef traitT traits_type;
    typedef typename traits_type::real_type real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef real_type parameter_type;

    constexpr static real_type cutoff_ratio = 4.0;

  public:
    ImplicitMembranePotential() = default;
    ImplicitMembranePotential(const real_type th, const real_type ma,
        const real_type be, const std::vector<parameter_type>& hydrophobicities)
        : half_thick_(th * 0.5), interaction_magnitude_(ma),
          bend_(be), hydrophobicities_(hydrophobicities)
    {}

    ImplicitMembranePotential(real_type th, real_type ma,
        real_type be, std::vector<parameter_type>&& hydrophobicities)
        : half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),
          hydrophobicities_(std::move(hydrophobicities))
    {}
    ~ImplicitMembranePotential() = default;

    real_type  half_thick() const noexcept {return half_thick_;}
    real_type& half_thick()       noexcept {return half_thick_;}

    real_type  interaction_magnitude() const noexcept
    {return interaction_magnitude_;}
    real_type& interaction_magnitude() noexcept
    {return interaction_magnitude_;}

    real_type  bend() const noexcept {return bend_;}
    real_type& bend()       noexcept {return bend_;}

    void hydrophobicities_emplace(const parameter_type);

    void set_hydrophobicities(const std::vector<parameter_type>&);
    void set_hydrophobicities(std::vector<parameter_type>&&);

    std::size_t size() const noexcept {return hydrophobicities_.size();}
    void resize (const std::size_t i){hydrophobicities_.resize(i);}
    void reserve(const std::size_t i){hydrophobicities_.reserve(i);}
    void clear() {hydrophobicities_.clear();}

    parameter_type&       operator[](const std::size_t i) noexcept
    {return hydrophobicities_[i];}
    parameter_type const& operator[](const std::size_t i) const noexcept
    {return hydrophobicities_[i];}
    parameter_type&       at(const std::size_t i)
    {return hydrophobicities_.at(i);}
    parameter_type const& at(const std::size_t i) const
    {return hydrophobicities_.at(i);}

    real_type potential (const std::size_t i, const real_type z) const;
    real_type derivative(const std::size_t i, const real_type z) const;
    real_type max_cutoff_length() const noexcept;

  private:

    real_type half_thick_;//membrane half of thickness.
    real_type interaction_magnitude_;
    real_type bend_;//bend_ decide the slope of tanh carve.
    std::vector<parameter_type> hydrophobicities_;
};

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::hydrophobicities_emplace(
    const parameter_type hydrophobicity)
{
    hydrophobicities_.emplace_back(hydrophobicity);
    return;
}

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
    const std::vector<parameter_type>& hydrophobicities)
{
    hydrophobicities_ = hydrophobicities;
    return;
}

template<typename traitsT>
inline void
ImplicitMembranePotential<traitsT>::set_hydrophobicities(
    std::vector<parameter_type>&& hydrophobicities)
{
    hydrophobicities_ = std::move(hydrophobicities);
    return;
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::potential(
    const std::size_t i, const real_type z) const
{
    return hydrophobicities_[i] * interaction_magnitude_ *
        std::tanh(bend_ * (std::abs(z) - half_thick_));
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::derivative(
    const std::size_t i, const real_type z) const
{
    return hydrophobicities_[i] * std::copysign(1.0, z) *
        interaction_magnitude_ * bend_ /
        std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);
}

template<typename traitsT>
inline typename ImplicitMembranePotential<traitsT>::real_type
ImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept
{
    return cutoff_ratio / bend_ + half_thick_;
}

}
#endif /* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL */
<|endoftext|>