<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
#include "Plant.h"

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    //construct
    Player *player = new Player;
    Zombie *zombie = new Zombie[ZOMBIES];
    Zombie::TotalNum = ZOMBIES;
    Map *map = new Map(LANDS);
    vector<Plant*> plant;
    fstream fin("plants.txt", fstream::in);
    string str;
    if(fin)
    {
        while(fin >> str)
        {
            Plant *tmp = nullptr;
            switch(str[0])
            {
            case 'C':
            {
                tmp = new CoinPlant(fin);
                break;
            }
            case 'S':
            {
                tmp = new HornPlant(fin);
                break;
            }
            case 'B':
            {
                tmp = new BombPlant(fin);
                break;
            }
            case 'H':
            {
                tmp = new HealPlant(fin);
                break;
            }
            default:
                continue;
            }
            if(tmp)
            {
                plant.push_back(tmp);
            }
        }
    }

    map->Display(*player, zombie);  //cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0; i<ZOMBIES; i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;

    for(size_t i=0; i<plant.size(); ++i)
    {
        cout << "[" << i << "] " ;
        switch(plant[i]->Type())
        {
            case 'C':
                dynamic_cast<CoinPlant *>(plant[i])->Print();
                break;
            case 'S':
                dynamic_cast<HornPlant *>(plant[i])->Print();
                break;
            case 'B':
                dynamic_cast<BombPlant *>(plant[i])->Print();
                break;
            case 'H':
                dynamic_cast<HealPlant *>(plant[i])->Print();
                break;
        }
        cout << endl;
    }
    int choice = plant.size();
    cout << endl << *player;
    cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";

    /*

        if(choice=plant.size()) break;
        int cost=0;
        string plantname;
        switch(plant[choice].type())
        {
        case 'C':
            CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="CoinPlant";
            cost=tmp->price();
        case 'S':
            HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="HornPlant";
            cost=tmp->price();
        case 'B':
            BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="BombPlant";
            cost=tmp->price();
        case 'H':
            HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="HealPlant";
            cost=tmp->price();
        }
        if(player->money() >= cost)
        {
            cout << "You have planted " << plantname << " at land 7 !";
            break;
        }
        else
        {
            cout << "Not enough money! Please input again.";
        }
    }*/
    // destruct
    while(!plant.empty())
    {
        delete plant.back();
        plant.pop_back();
    }
    delete player;
    delete map;
    delete [] zombie;

    return 0;
}
<commit_msg>modify plant print<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
#include "Plant.h"

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    //construct
    Player *player = new Player;
    Zombie *zombie = new Zombie[ZOMBIES];
    Zombie::TotalNum = ZOMBIES;
    Map *map = new Map(LANDS);
    vector<Plant*> plant;
    fstream fin("plants.txt", fstream::in);
    string str;
    if(fin)
    {
        while(fin >> str)
        {
            Plant *tmp = nullptr;
            switch(str[0])
            {
            case 'C':
            {
                tmp = new CoinPlant(fin);
                break;
            }
            case 'S':
            {
                tmp = new HornPlant(fin);
                break;
            }
            case 'B':
            {
                tmp = new BombPlant(fin);
                break;
            }
            case 'H':
            {
                tmp = new HealPlant(fin);
                break;
            }
            default:
                continue;
            }
            if(tmp)
            {
                plant.push_back(tmp);
            }
        }
    }

    map->Display(*player, zombie);  //cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0; i<ZOMBIES; i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;

    for(size_t i=0; i<plant.size(); ++i)
    {
        cout << "[" << i << "] " ;
        plant[i]->Print();
        cout << endl;
    }
    int choice = plant.size();
    // << endl << *player;
    cout << ":\tEnter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";

    /*

        if(choice=plant.size()) break;
        int cost=0;
        string plantname;
        switch(plant[choice].type())
        {
        case 'C':
            CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="CoinPlant";
            cost=tmp->price();
        case 'S':
            HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="HornPlant";
            cost=tmp->price();
        case 'B':
            BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="BombPlant";
            cost=tmp->price();
        case 'H':
            HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="HealPlant";
            cost=tmp->price();
        }
        if(player->money() >= cost)
        {
            cout << "You have planted " << plantname << " at land 7 !";
            break;
        }
        else
        {
            cout << "Not enough money! Please input again.";
        }
    }*/
    // destruct
    while(!plant.empty())
    {
        delete plant.back();
        plant.pop_back();
    }
    delete player;
    delete map;
    delete [] zombie;

    return 0;
}
<|endoftext|>


<commit_before>float   myState[12];            //status of the sphere
float   myPos[3];               //our position
float   theirPos[3];
float   itemState[12];          //state of the item
float   itemAtt[3];             //attitude of the item
float   pointAtt[3];            //point attitude
float   second[3];              //point to place SPS
float   third[3];
float   dropPos[3];
float   dropZone[3];
float   temp[3];

float   virtualTarget[3];       //we calculate and fly to this point
float   actualTarget[3];        //actual location of an item
float   distFromTarget;         //distance from our target
int     targetNumber;           //ID of the item
float   distMin;                //minimum distance of docking
float   distMax;                //maximum distance of docking

float   ranking[4];             //vector that is used to calculate which item is the worthiest

float   ourZone[3];             //our assembly zone
float   theirZone[3];           //they assembly zone

char    index;                  //switch index
bool    calculated;             //check if the virtualPoint is calculated
int     counter;                //counter used to fly around objects
int     packsInZone;

void init(){
    packsInZone = 0;
    getMyPos();
    getTheirPos();
    index = 's';                //index starts here
    game.dropSPS();             //we drop the first SPS at our starting point
    calculated = false;
    if(ourColor() == 'B'){
        assign(second, 0.0, 0.15, 0.60);
        assign(third, 0.60, 0.0, 0.60);
    }
    else{
        assign(second, 0.0, 0.0, -0.60);
        assign(third, -0.60, 0.0, -0.60);
    }
    setDist();
}

void loop(){
    getMyPos();                            //we get our position because we always need that information
    packsInZone = 0;
    for(int i = 0; i < 4; i++){
        game.getItemLoc(temp, i);
        if(compareVector(ourZone, temp, 0.05))
            packsInZone++;
        }
    if((game.getCurrentTime() >= 140 || packsInZone == 2) && index == 'p' )
        index = 'f';
    switch(index){
        /*we call worthyPack to see what is the worthiest pack to pick up. If we didn't place the SPS we will go to case F and place it,
        otherwise we will go for packs. we calculate here the virtual point or we would follow the pack if it starts moving*/
        case 's':
            if(!compareVector(myPos, second, 0.10))
                api.setPositionTarget(second);
            else{
                game.dropSPS();
                index = '3';
            }
            break;
        /*we calculate the position of the second SPS based on the position of the first worthyPack we find*/
        case '3':
            if(!compareVector(myPos, third, 0.10))
                api.setPositionTarget(third);
            else{
                game.dropSPS();
                zoneInfo();
                index = 'p';
            }
            break;
        /* */
        case 'p':
            worthyPack();
            if(!calculated)
                calcPoint();
            else{
                approachPack();
                api.setAttitudeTarget(pointAtt);
                DEBUG(("%f", dist(myPos, actualTarget)));
                if(dist(myPos, actualTarget)<=distMax && dist(myPos, actualTarget) >= distMin && game.isFacingCorrectItemSide(targetNumber)){
                    if(game.dockItem(targetNumber) && game.hasItem(targetNumber) == 1){
                        game.dropSPS();
                        assign(dropPos, myPos[0], myPos[1], myPos[2]);
                        index = 'z';
                    }
                }
            }
            break;
        /*we calculate the approach point. if the pack is moving we return to worthyPack, otherwise we go and dock the item. The first
        dock will place the last SPS and get the ZoneInfo*/
        case 'z':
            rotateToPoint(ourZone);
                api.setPositionTarget(ourZone);
            if((dist(dropPos, ourZone) < 0.2))
                assign(dropZone, ourZone[0], ourZone[1], ourZone[2] - 0.2);
            if(packInZone()){
                game.dropItem();
                index = 'p';
                calculated = false;
            }
            break;
        /*we drop the item in the zone. the first time we drop the item and calculate an universal dropping point*/
        case 'f':
            api.setPositionTarget(ourZone);
        break;
    }
}
<commit_msg>Added the most important DEBUG of all my life<commit_after>float   myState[12];            //status of the sphere
float   myPos[3];               //our position
float   theirPos[3];
float   itemState[12];          //state of the item
float   itemAtt[3];             //attitude of the item
float   pointAtt[3];            //point attitude
float   second[3];              //point to place SPS
float   third[3];
float   dropPos[3];
float   dropZone[3];
float   temp[3];

float   virtualTarget[3];       //we calculate and fly to this point
float   actualTarget[3];        //actual location of an item
float   distFromTarget;         //distance from our target
int     targetNumber;           //ID of the item
float   distMin;                //minimum distance of docking
float   distMax;                //maximum distance of docking

float   ranking[4];             //vector that is used to calculate which item is the worthiest

float   ourZone[3];             //our assembly zone
float   theirZone[3];           //they assembly zone

char    index;                  //switch index
bool    calculated;             //check if the virtualPoint is calculated
int     counter;                //counter used to fly around objects
int     packsInZone;

void init(){
    packsInZone = 0;
    getMyPos();
    getTheirPos();
    index = 's';                //index starts here
    game.dropSPS();             //we drop the first SPS at our starting point
    calculated = false;
    if(ourColor() == 'B'){
        assign(second, 0.0, 0.15, 0.60);
        assign(third, 0.60, 0.0, 0.60);
    }
    else{
        assign(second, 0.0, 0.0, -0.60);
        assign(third, -0.60, 0.0, -0.60);
    }
    setDist();
}

void loop(){
    getMyPos();                            //we get our position because we always need that information
    packsInZone = 0;
    for(int i = 0; i < 4; i++){
        game.getItemLoc(temp, i);
        if(compareVector(ourZone, temp, 0.05))
            packsInZone++;
        }
    if((game.getCurrentTime() >= 140 || packsInZone == 2) && index == 'p' )
        index = 'f';
    switch(index){
        /*we call worthyPack to see what is the worthiest pack to pick up. If we didn't place the SPS we will go to case F and place it,
        otherwise we will go for packs. we calculate here the virtual point or we would follow the pack if it starts moving*/
        case 's':
            if(!compareVector(myPos, second, 0.10))
                api.setPositionTarget(second);
            else{
                game.dropSPS();
                index = '3';
            }
            break;
        /*we calculate the position of the second SPS based on the position of the first worthyPack we find*/
        case '3':
            if(!compareVector(myPos, third, 0.10))
                api.setPositionTarget(third);
            else{
                game.dropSPS();
                zoneInfo();
                index = 'p';
            }
            break;
        /* */
        case 'p':
            worthyPack();
            if(!calculated)
                calcPoint();
            else{
                approachPack();
                api.setAttitudeTarget(pointAtt);
                DEBUG(("%f", dist(myPos, actualTarget)));
                if(dist(myPos, actualTarget)<=distMax && dist(myPos, actualTarget) >= distMin && game.isFacingCorrectItemSide(targetNumber)){
                    if(game.dockItem(targetNumber) && game.hasItem(targetNumber) == 1){
                        game.dropSPS();
                        assign(dropPos, myPos[0], myPos[1], myPos[2]);
                        index = 'z';
                    }
                }
            }
            break;
        /*we calculate the approach point. if the pack is moving we return to worthyPack, otherwise we go and dock the item. The first
        dock will place the last SPS and get the ZoneInfo*/
        case 'z':
            rotateToPoint(ourZone);
                api.setPositionTarget(ourZone);
            if((dist(dropPos, ourZone) < 0.2))
                assign(dropZone, ourZone[0], ourZone[1], ourZone[2] - 0.2);
            if(packInZone()){
                game.dropItem();
                index = 'p';
                calculated = false;
            }
            break;
        /*we drop the item in the zone. the first time we drop the item and calculate an universal dropping point*/
        case 'f':
            api.setPositionTarget(ourZone);
            DEBUG(("VUÒ FA' CODICE E CODICE? PO PO PO PO PO PO"));
        break;
    }
}
<|endoftext|>


<commit_before>7b693e8f-2749-11e6-816f-e0f84713e7b8<commit_msg>Stuff changed<commit_after>7b7a21a3-2749-11e6-9ff6-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>  //头文件
#include <opencv2/xfeatures2d.hpp>

using namespace cv;  //包含cv命名空间
using namespace std;

vector<DMatch> ransac(vector<DMatch> matches, vector<KeyPoint> queryKeyPoint, vector<KeyPoint> trainKeyPoint);

int main() {
    //Create SIFT class pointer
    Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
    //读入图片
    Mat img_1 = imread("../3.png");
    Mat img_2 = imread("../4.png");
    imshow("img_1", img_1);
    imshow("img_2", img_2);

    //Detect the keypoints
    vector<KeyPoint> keypoints_1, keypoints_2;
    f2d->detect(img_1, keypoints_1);
    f2d->detect(img_2, keypoints_2);

    //Calculate descriptors (feature vectors)
    Mat descriptors_1, descriptors_2;
    f2d->compute(img_1, keypoints_1, descriptors_1);
    f2d->compute(img_2, keypoints_2, descriptors_2);

    //Matching descriptor vector using BFMatcher
    BFMatcher matcher;
    vector<DMatch> matches;
    matcher.match(descriptors_1, descriptors_2, matches);
    cout << "SIFT后一共：" << matches.size() << " 对匹配：" << endl;

    //绘制匹配出的关键点
    Mat img_matches;
    drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_matches);
    imshow("RANSC_before", img_matches);

    matches = ransac(matches, keypoints_1, keypoints_2);

    Mat img_matches1;
    drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_matches1);
    imshow("RANSC_after", img_matches1);

    //等待任意按键按下
    waitKey(0);
}

//RANSAC算法实现
vector<DMatch> ransac(vector<DMatch> matches, vector<KeyPoint> queryKeyPoint, vector<KeyPoint> trainKeyPoint) {
    //定义保存匹配点对坐标
    vector<Point2f> srcPoints(matches.size()), dstPoints(matches.size());
    //保存从关键点中提取到的匹配点对的坐标
    for (int i = 0; i < matches.size(); i++) {
        srcPoints[i] = queryKeyPoint[matches[i].queryIdx].pt;
        dstPoints[i] = trainKeyPoint[matches[i].trainIdx].pt;
    }
    //保存计算的单应性矩阵
    Mat homography;
    //保存点对是否保留的标志
    vector<unsigned char> inliersMask(srcPoints.size());
    //匹配点对进行RANSAC过滤
    homography = findHomography(srcPoints, dstPoints, CV_RANSAC, 5, inliersMask);
    //RANSAC过滤后的点对匹配信息
    vector<DMatch> matches_ransac;
    //手动的保留RANSAC过滤后的匹配点对
    for (int i = 0; i < inliersMask.size(); i++) {
        if (inliersMask[i]) {
            matches_ransac.push_back(matches[i]);
            //cout<<"第"<<i<<"对匹配："<<endl;
            //cout<<"queryIdx:"<<matches[i].queryIdx<<"\ttrainIdx:"<<matches[i].trainIdx<<endl;
            //cout<<"imgIdx:"<<matches[i].imgIdx<<"\tdistance:"<<matches[i].distance<<endl;
        }
    }
    cout << "经RANSAC消除误匹配后一共：" << matches_ransac.size() << " 对匹配：" << endl;
    //返回RANSAC过滤后的点对匹配信息
    return matches_ransac;
}<commit_msg>计算单应性矩阵，透视变化<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>  //头文件
#include <opencv2/xfeatures2d.hpp>

using namespace cv;  //包含cv命名空间
using namespace std;

vector<DMatch> ransac(vector<DMatch> matches, vector<KeyPoint> queryKeyPoint, vector<KeyPoint> trainKeyPoint);
Point2f getTransformPoint(const Point2f originalPoint,const Mat &transformMaxtri);

int main() {
    //Create SIFT class pointer
    Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
    //读入图片
    Mat img_1 = imread("../3.png");
    Mat img_2 = imread("../4.png");
    imshow("img_1", img_1);
    imshow("img_2", img_2);

    //Detect the keypoints
    vector<KeyPoint> keypoints_1, keypoints_2;
    f2d->detect(img_1, keypoints_1);
    f2d->detect(img_2, keypoints_2);

    //Calculate descriptors (feature vectors)
    Mat descriptors_1, descriptors_2;
    f2d->compute(img_1, keypoints_1, descriptors_1);
    f2d->compute(img_2, keypoints_2, descriptors_2);

    //Matching descriptor vector using BFMatcher
    BFMatcher matcher;
    vector<DMatch> matches;
    matcher.match(descriptors_1, descriptors_2, matches);
    cout << "SIFT后一共：" << matches.size() << " 对匹配：" << endl;

    //绘制匹配出的关键点
    Mat img_matches;
    drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_matches);
    imshow("RANSC_before", img_matches);

    matches = ransac(matches, keypoints_1, keypoints_2);

    Mat img_matches1;
    drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_matches1);
    imshow("RANSC_after", img_matches1);

    //获得匹配特征点，并提取最优配对
    sort(matches.begin(),matches.end()); //特征点排序
    //获取排在前N个的最优匹配特征点
    vector<Point2f> imagePoints1,imagePoints2;
    for(int i=0;i<10;i++)
    {
        imagePoints1.push_back(keypoints_1[matches[i].queryIdx].pt);
        imagePoints2.push_back(keypoints_2[matches[i].trainIdx].pt);
    }

    //获取图像1到图像2的投影映射矩阵，尺寸为3*3
    Mat homo=findHomography(imagePoints1,imagePoints2,CV_RANSAC);
    Mat adjustMat=(Mat_<double>(3,3)<<1.0,0,img_1.cols,0,1.0,0,0,0,1.0);
    Mat adjustHomo=adjustMat*homo;

    //获取最强配对点在原始图像和矩阵变换后图像上的对应位置，用于图像拼接点的定位
    Point2f originalLinkPoint,targetLinkPoint,basedImagePoint;
    originalLinkPoint=keypoints_1[matches[0].queryIdx].pt;
    targetLinkPoint=getTransformPoint(originalLinkPoint,adjustHomo);
    basedImagePoint=keypoints_2[matches[0].trainIdx].pt;

    //图像配准
    Mat imageTransform1;
    warpPerspective(img_1,imageTransform1,adjustMat*homo,Size(img_2.cols+img_1.cols+10,img_2.rows));

    //在最强匹配点的位置处衔接，最强匹配点左侧是图1，右侧是图2，这样直接替换图像衔接不好，光线有突变
    Mat ROIMat=img_2(Rect(Point(basedImagePoint.x,0),Point(img_2.cols,img_2.rows)));
    ROIMat.copyTo(Mat(imageTransform1,Rect(targetLinkPoint.x,0,img_2.cols-basedImagePoint.x+1,img_2.rows)));

    imshow("Complete!",imageTransform1);
    //等待任意按键按下
    waitKey(0);
}

//RANSAC算法实现
vector<DMatch> ransac(vector<DMatch> matches, vector<KeyPoint> queryKeyPoint, vector<KeyPoint> trainKeyPoint) {
    //定义保存匹配点对坐标
    vector<Point2f> srcPoints(matches.size()), dstPoints(matches.size());
    //保存从关键点中提取到的匹配点对的坐标
    for (int i = 0; i < matches.size(); i++) {
        srcPoints[i] = queryKeyPoint[matches[i].queryIdx].pt;
        dstPoints[i] = trainKeyPoint[matches[i].trainIdx].pt;
    }
    //保存计算的单应性矩阵
    Mat homography;
    //保存点对是否保留的标志
    vector<unsigned char> inliersMask(srcPoints.size());
    //匹配点对进行RANSAC过滤
    homography = findHomography(srcPoints, dstPoints, CV_RANSAC, 5, inliersMask);
    //RANSAC过滤后的点对匹配信息
    vector<DMatch> matches_ransac;
    //手动的保留RANSAC过滤后的匹配点对
    for (int i = 0; i < inliersMask.size(); i++) {
        if (inliersMask[i]) {
            matches_ransac.push_back(matches[i]);
            //cout<<"第"<<i<<"对匹配："<<endl;
            //cout<<"queryIdx:"<<matches[i].queryIdx<<"\ttrainIdx:"<<matches[i].trainIdx<<endl;
            //cout<<"imgIdx:"<<matches[i].imgIdx<<"\tdistance:"<<matches[i].distance<<endl;
        }
    }
    cout << "经RANSAC消除误匹配后一共：" << matches_ransac.size() << " 对匹配：" << endl;
    //返回RANSAC过滤后的点对匹配信息
    return matches_ransac;
}

//计算原始图像点位在经过矩阵变换后在目标图像上对应位置
Point2f getTransformPoint(const Point2f originalPoint,const Mat &transformMaxtri)
{
    Mat originelP,targetP;
    originelP=(Mat_<double>(3,1)<<originalPoint.x,originalPoint.y,1.0);
    targetP=transformMaxtri*originelP;
    float x=targetP.at<double>(0,0)/targetP.at<double>(2,0);
    float y=targetP.at<double>(1,0)/targetP.at<double>(2,0);
    return Point2f(x,y);
}<|endoftext|>


<commit_before>d0d79200-2747-11e6-b44e-e0f84713e7b8<commit_msg>new flies<commit_after>d0eff599-2747-11e6-acec-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>

#include "DboProject.h"
#include "util.h"

char* const CMD_INSTALL = "install";
char* const CMD_REMOVE = "remove";
char* const CMD_UPGRADE = "upgrade";
char* const CMD_HELP = "help";
char* const cmds[] = {"install", "remove", "upgrade", "help"};

int main(int argc, char* argv[]) {
    if (argc < 2) {
        err("Too few args!");
        print("    Usage: dbo_get <command> <projects>...");
        return 1;
    }

    char* cmd = argv[1];
    if (std::strcmp(cmd, CMD_INSTALL) == 0) {
        return install(argc, argv);
    } else if (std::strcmp(cmd, CMD_REMOVE) == 0) {
        if (argc < 3) {
            tooFewArgs(cmd);
            return 1;
        }
        err("Command not yet implemented");
        return 1;
    } else if (std::strcmp(cmd, CMD_UPGRADE) == 0) {
        err("Command not yet implemented");
        return 1;
    } else if (std::strcmp(cmd, CMD_HELP) == 0) {
        err("Command not yet implemented");
        return 1;
    } else {
        err("Invalid command, try `dbo-get help`.");
        return 1;
    }

    for (int i = 0; i < argc; i++) {
        std::string project = argv[2 + i];
        DboProject dbo = DboProject(project);

        bool fail = false;
        if (!dbo.resolve()) {
            err("Failed to resolve project " + project);
            std::string alt = dbo.getAlternatives();
            if (alt.length() > 0) {
                print("    Possible alternatives: " + *alt.c_str());
            }
            fail = true;
        }

        if (fail) {
            return 1;
        }
    }
}

bool install(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(std::strcat(CMD_INSTALL, " <projects>..."));
        return 1;
    }
    err("Command not yet implemented");
    return 1;

}
<commit_msg>Add basic infrastructure for installing projects<commit_after>#include <iostream>
#include <vector>

#include "DboProject.h"
#include "util.h"

char* const CMD_INSTALL = "install";
char* const CMD_REMOVE = "remove";
char* const CMD_UPGRADE = "upgrade";
char* const CMD_HELP = "help";
char* const cmds[] = {"install", "remove", "upgrade", "help"};

int main(int argc, char* argv[]) {
    if (argc < 2) {
        err("Too few args!");
        print("    Usage: dbo_get <command> <projects>...");
        return 1;
    }

    char* cmd = argv[1];
    if (std::strcmp(cmd, CMD_INSTALL) == 0) {
        return install(argc, argv);
    } else if (std::strcmp(cmd, CMD_REMOVE) == 0) {
        if (argc < 3) {
            tooFewArgs(cmd);
            return 1;
        }
        err("Command not yet implemented");
        return 1;
    } else if (std::strcmp(cmd, CMD_UPGRADE) == 0) {
        err("Command not yet implemented");
        return 1;
    } else if (std::strcmp(cmd, CMD_HELP) == 0) {
        err("Command not yet implemented");
        return 1;
    } else {
        err("Invalid command, try `dbo-get help`.");
        return 1;
    }
}

std::vector<DboProject>* resolve(int argc, char* argv[]) {
    std::vector<DboProject> vec = std::vector<DboProject>(argc - 2);
    for (int i = 0; i < argc; i++) {
        std::string project = argv[2 + i];
        DboProject dbo = DboProject(project);
        vec[i] = dbo;

        bool fail = false;
        if (!dbo.resolve()) {
            err("Failed to resolve project " + project);
            std::string alt = dbo.getAlternatives();
            if (alt.length() > 0) {
                print("    Possible alternatives: " + *alt.c_str());
            }
            fail = true;
        }

        if (fail) {
            return NULL;
        }
    }
    return &vec;
}

int install(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(std::strcat(CMD_INSTALL, " <projects>..."));
        return 1;
    }

    std::vector<DboProject>* projects = resolve(argc, argv);
    if (projects == NULL) {
        return 1;
    }

    for (int i = 0; i < projects->size(); i++) {
        install((*projects)[i]);
    }
}

int install(DboProject project) {
    //TODO
}
<|endoftext|>


<commit_before>#include "main.h"

#include <climits>
#include <cstring>
#include <iomanip>
#include <iostream>

#ifndef _WIN32
#include <ftw.h>
#endif

#include "leanify.h"
#include "fileio.h"
#include "version.h"

void PrintSize(size_t size)
{
    if (size < 1024)
    {
        std::cout << size << " B";
    }
    else if (size < 1024 * 1024)
    {
        std::cout << size / 1024.0 << " KB";
    }
    else
    {
        std::cout << size / 1024.0 / 1024.0 << " MB";
    }
}

#ifdef _WIN32
int ProcessFile(const wchar_t *file_path)
{
    char mbs[MAX_PATH] = { 0 };
    WideCharToMultiByte(CP_ACP, 0, file_path, -1, mbs, sizeof(mbs) - 1, nullptr, nullptr);
    std::cout << "Processing: " << mbs << std::endl;
#else
// written like this in order to be callback funtion of ftw()
int ProcessFile(const char file_path[], const struct stat *sb = nullptr, int typeflag = FTW_F)
{
    if (typeflag != FTW_F)
    {
        return 0;
    }
    std::cout << "Processing: " << file_path << std::endl;
#endif // _WIN32

    File input_file(file_path);

    if (input_file.IsOK())
    {
        size_t original_size = input_file.GetSize();

        size_t new_size = LeanifyFile(input_file.GetFilePionter(), original_size);

        PrintSize(original_size);
        std::cout << " -> ";
        PrintSize(new_size);
        std::cout << "\tLeanified: ";
        PrintSize(original_size - new_size);

        std::cout << " (" << 100 - 100.0 * new_size / original_size << "%)" << std::endl;

        input_file.UnMapFile(new_size);
    }

    return 0;
}

void PauseIfNotTerminal()
{
    // pause if Leanify is not started in terminal
    // so that user can see the output instead of just a flash of a black box
#ifdef _WIN32
    if (is_pause)
    {
        system("pause");
    }
#endif // _WIN32
}

void PrintInfo()
{
    std::cerr << "Leanify\t" << VERSION_STR << std::endl << std::endl;
    std::cerr << "Usage: Leanify [options] paths" << std::endl;
    std::cerr << "  -i <iteration>  More iterations means slower but better result. Default: 15." << std::endl;
    std::cerr << "  -d <max depth>  Maximum recursive depth." << std::endl;
    std::cerr << "  -f              Fast mode, no recompression." << std::endl;
    std::cerr << "  -q              Quiet mode, no output." << std::endl;
    std::cerr << "  -v              Verbose output." << std::endl;
    PauseIfNotTerminal();
}

#ifdef _WIN32
int main()
{
    int argc;
    wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
#else
int main(int argc, char *argv[])
{
#endif // _WIN32

    is_fast = false;
    is_verbose = false;
    iterations = 15;
    depth = 1;
    max_depth = INT_MAX;

#ifdef _WIN32
    is_pause = !getenv("PROMPT");
#endif // _WIN32

    int i;
    for (i = 1; i < argc && argv[i][0] == L'-'; i++)
    {
#ifdef _WIN32
        // do not pause if any options are given
        is_pause = false;
#endif // _WIN32
        int num_optargs = 0;
        for (int j = 1; argv[i][j]; j++)
        {
            switch (argv[i][j])
            {
            case 'f':
                is_fast = true;
                break;
            case 'i':
                if (i < argc - 1)
                {
                    iterations = STRTOL(argv[i + ++num_optargs], nullptr, 10);
                    // strtol will return 0 on fail
                    if (iterations == 0)
                    {
                        std::cerr << "There should be a positive number after -i option." << std::endl;
                        PrintInfo();
                        return 1;
                    }
                }
                break;
            case 'd':
                if (i < argc - 1)
                {
                    max_depth = STRTOL(argv[i + ++num_optargs], nullptr, 10);
                    // strtol will return 0 on fail
                    if (max_depth == 0)
                    {
                        std::cerr << "There should be a positive number after -d option." << std::endl;
                        PrintInfo();
                        return 1;
                    }
                }
                break;
            case 'q':
                std::cout.setstate(std::ios::failbit);
                is_verbose = false;
                break;
            case 'v':
                std::cout.clear();
                is_verbose = true;
                break;
            case '-':
                if (STRCMP(argv[i] + j + 1, "fastmode") == 0)
                {
                    j += 7;
                    argv[i][j + 1] = 'f';
                }
                else if (STRCMP(argv[i] + j + 1, "iteration") == 0)
                {
                    j += 8;
                    argv[i][j + 1] = 'i';
                }
                else if (STRCMP(argv[i] + j + 1, "max_depth") == 0)
                {
                    j += 8;
                    argv[i][j + 1] = 'd';
                }
                else if (STRCMP(argv[i] + j + 1, "quiet") == 0)
                {
                    j += 4;
                    argv[i][j + 1] = 'q';
                }
                else if (STRCMP(argv[i] + j + 1, "verbose") == 0)
                {
                    j += 6;
                    argv[i][j + 1] = 'v';
                }
                else
                {
#ifdef _WIN32
                    char mbs[64] = { 0 };
                    WideCharToMultiByte(CP_ACP, 0, argv[i] + j + 1, -1, mbs, sizeof(mbs) - 1, nullptr, nullptr);
                    std::cerr << "Unknown option: " << mbs << std::endl;
#else
                    std::cerr << "Unknown option: " << argv[i] + j + 1 << std::endl;
#endif // _WIN32
                    PrintInfo();
                    return 1;
                }
                break;
            default:
                std::cerr << "Unknown option: " << (char)argv[i][j] << std::endl;
                PrintInfo();
                return 1;
            }
        }
        i += num_optargs;
    }

    if (i == argc)
    {
        std::cerr << "No file path provided." << std::endl;
        PrintInfo();
        return 1;
    }

    std::cout << std::fixed;
    std::cout.precision(2);

    // support multiple input file
    do
    {
        if (IsDirectory(argv[i]))
        {
            // directory
            TraverseDirectory(argv[i], ProcessFile);
        }
        else
        {
            // file
            ProcessFile(argv[i]);
        }

    }
    while (++i < argc);

    PauseIfNotTerminal();

    return 0;
}<commit_msg>Update usage<commit_after>#include "main.h"

#include <climits>
#include <cstring>
#include <iomanip>
#include <iostream>

#ifndef _WIN32
#include <ftw.h>
#endif

#include "leanify.h"
#include "fileio.h"
#include "version.h"

void PrintSize(size_t size)
{
    if (size < 1024)
    {
        std::cout << size << " B";
    }
    else if (size < 1024 * 1024)
    {
        std::cout << size / 1024.0 << " KB";
    }
    else
    {
        std::cout << size / 1024.0 / 1024.0 << " MB";
    }
}

#ifdef _WIN32
int ProcessFile(const wchar_t *file_path)
{
    char mbs[MAX_PATH] = { 0 };
    WideCharToMultiByte(CP_ACP, 0, file_path, -1, mbs, sizeof(mbs) - 1, nullptr, nullptr);
    std::cout << "Processing: " << mbs << std::endl;
#else
// written like this in order to be callback funtion of ftw()
int ProcessFile(const char file_path[], const struct stat *sb = nullptr, int typeflag = FTW_F)
{
    if (typeflag != FTW_F)
    {
        return 0;
    }
    std::cout << "Processing: " << file_path << std::endl;
#endif // _WIN32

    File input_file(file_path);

    if (input_file.IsOK())
    {
        size_t original_size = input_file.GetSize();

        size_t new_size = LeanifyFile(input_file.GetFilePionter(), original_size);

        PrintSize(original_size);
        std::cout << " -> ";
        PrintSize(new_size);
        std::cout << "\tLeanified: ";
        PrintSize(original_size - new_size);

        std::cout << " (" << 100 - 100.0 * new_size / original_size << "%)" << std::endl;

        input_file.UnMapFile(new_size);
    }

    return 0;
}

void PauseIfNotTerminal()
{
    // pause if Leanify is not started in terminal
    // so that user can see the output instead of just a flash of a black box
#ifdef _WIN32
    if (is_pause)
    {
        system("pause");
    }
#endif // _WIN32
}

void PrintInfo()
{
    std::cerr << "Leanify\t" << VERSION_STR << std::endl << std::endl;
    std::cerr <<
        "Usage: Leanify [options] paths\n"
        "  -i, --iteration <iteration>   More iterations produce better result, but\n"
        "                                  use more time, default is 15.\n"
        "  -d, --max_depth <max depth>   Maximum recursive depth, unlimited by default.\n"
        "                                  Set to 1 will disable recursive minifying.\n"
        "  -f, --fastmode                Fast mode, no recompression.\n"
        "  -q, --quiet                   No output to stdout.\n"
        "  -v, --verbose                 Verbose output." << std::endl;
    PauseIfNotTerminal();
}

#ifdef _WIN32
int main()
{
    int argc;
    wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
#else
int main(int argc, char *argv[])
{
#endif // _WIN32

    is_fast = false;
    is_verbose = false;
    iterations = 15;
    depth = 1;
    max_depth = INT_MAX;

#ifdef _WIN32
    is_pause = !getenv("PROMPT");
#endif // _WIN32

    int i;
    for (i = 1; i < argc && argv[i][0] == L'-'; i++)
    {
#ifdef _WIN32
        // do not pause if any options are given
        is_pause = false;
#endif // _WIN32
        int num_optargs = 0;
        for (int j = 1; argv[i][j]; j++)
        {
            switch (argv[i][j])
            {
            case 'f':
                is_fast = true;
                break;
            case 'i':
                if (i < argc - 1)
                {
                    iterations = STRTOL(argv[i + ++num_optargs], nullptr, 10);
                    // strtol will return 0 on fail
                    if (iterations == 0)
                    {
                        std::cerr << "There should be a positive number after -i option." << std::endl;
                        PrintInfo();
                        return 1;
                    }
                }
                break;
            case 'd':
                if (i < argc - 1)
                {
                    max_depth = STRTOL(argv[i + ++num_optargs], nullptr, 10);
                    // strtol will return 0 on fail
                    if (max_depth == 0)
                    {
                        std::cerr << "There should be a positive number after -d option." << std::endl;
                        PrintInfo();
                        return 1;
                    }
                }
                break;
            case 'q':
                std::cout.setstate(std::ios::failbit);
                is_verbose = false;
                break;
            case 'v':
                std::cout.clear();
                is_verbose = true;
                break;
            case '-':
                if (STRCMP(argv[i] + j + 1, "fastmode") == 0)
                {
                    j += 7;
                    argv[i][j + 1] = 'f';
                }
                else if (STRCMP(argv[i] + j + 1, "iteration") == 0)
                {
                    j += 8;
                    argv[i][j + 1] = 'i';
                }
                else if (STRCMP(argv[i] + j + 1, "max_depth") == 0)
                {
                    j += 8;
                    argv[i][j + 1] = 'd';
                }
                else if (STRCMP(argv[i] + j + 1, "quiet") == 0)
                {
                    j += 4;
                    argv[i][j + 1] = 'q';
                }
                else if (STRCMP(argv[i] + j + 1, "verbose") == 0)
                {
                    j += 6;
                    argv[i][j + 1] = 'v';
                }
                else
                {
#ifdef _WIN32
                    char mbs[64] = { 0 };
                    WideCharToMultiByte(CP_ACP, 0, argv[i] + j + 1, -1, mbs, sizeof(mbs) - 1, nullptr, nullptr);
                    std::cerr << "Unknown option: " << mbs << std::endl;
#else
                    std::cerr << "Unknown option: " << argv[i] + j + 1 << std::endl;
#endif // _WIN32
                    PrintInfo();
                    return 1;
                }
                break;
            default:
                std::cerr << "Unknown option: " << (char)argv[i][j] << std::endl;
                PrintInfo();
                return 1;
            }
        }
        i += num_optargs;
    }

    if (i == argc)
    {
        std::cerr << "No file path provided." << std::endl;
        PrintInfo();
        return 1;
    }

    std::cout << std::fixed;
    std::cout.precision(2);

    // support multiple input file
    do
    {
        if (IsDirectory(argv[i]))
        {
            // directory
            TraverseDirectory(argv[i], ProcessFile);
        }
        else
        {
            // file
            ProcessFile(argv[i]);
        }

    }
    while (++i < argc);

    PauseIfNotTerminal();

    return 0;
}<|endoftext|>


<commit_before>#include <llvm/Transforms/Utils/Cloning.h>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include <llvm/Linker/Linker.h>
#include <llvm/Demangle/Demangle.h>

#include "util.h"
#include "taichi_llvm_context.h"
#include "backends/llvm_jit.h"

TLANG_NAMESPACE_BEGIN

static llvm::ExitOnError exit_on_err;

TaichiLLVMContext::TaichiLLVMContext() {
  llvm::InitializeNativeTarget();
  llvm::InitializeNativeTargetAsmPrinter();
  llvm::InitializeNativeTargetAsmParser();
  ctx = std::make_unique<llvm::LLVMContext>();
  jit = exit_on_err(TaichiLLVMJIT::Create());
}

TaichiLLVMContext::~TaichiLLVMContext() {
}

llvm::Type *TaichiLLVMContext::get_data_type(DataType dt) {
  if (dt == DataType::i32) {
    return llvm::Type::getInt32Ty(*ctx);
  } else if (dt == DataType::f32) {
    return llvm::Type::getFloatTy(*ctx);
  } else if (dt == DataType::f64) {
    return llvm::Type::getDoubleTy(*ctx);
  } else {
    TC_INFO(data_type_name(dt));
    TC_NOT_IMPLEMENTED
  }
  return nullptr;
}

std::string find_existing_command(const std::vector<std::string> &commands) {
  for (auto &cmd : commands) {
    if (command_exist(cmd)) {
      return cmd;
    }
  }
  TC_P(commands);
  TC_ERROR("No command found.");
  return "";
}

void compile_runtime() {
  auto clang = find_existing_command({"clang-7", "clang"});
  TC_ASSERT(command_exist("llvm-as"));
  TC_TRACE("Compiling runtime module bitcode...");
  auto runtime_folder = get_project_fn() + "/runtime/";
  int ret = std::system(
      fmt::format("{} -S {}runtime.cpp -o {}runtime.ll -emit-llvm -std=c++17",
                  clang, runtime_folder, runtime_folder)
          .c_str());
  if (ret) {
    TC_ERROR("Runtime compilation failed.");
  }
  std::system(fmt::format("llvm-as {}runtime.ll -o {}runtime.bc",
                          runtime_folder, runtime_folder)
                  .c_str());
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::get_init_module() {
  return clone_runtime_module();
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_runtime_module() {
  if (!runtime_module) {
    compile_runtime();
    std::ifstream ifs(get_project_fn() + "/runtime/runtime.bc");
    std::string bitcode(std::istreambuf_iterator<char>(ifs),
                        (std::istreambuf_iterator<char>()));
    auto runtime =
        parseBitcodeFile(MemoryBufferRef(bitcode, "runtime_bitcode"), *ctx);
    if (!runtime) {
      TC_ERROR("Runtime bitcode load failure.");
    }
    runtime_module = std::move(runtime.get());
    for (auto &f : *runtime_module) {
      TC_INFO("Loaded runtime function: {}", std::string(f.getName()));
    }
  }
  return llvm::CloneModule(*runtime_module);
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_struct_module() {
  TC_ASSERT(struct_module);
  /*
  auto runtime = clone_runtime_module();
  bool failed =
      llvm::Linker::linkModules(*runtime, llvm::CloneModule(*struct_module));
  if (failed) {
    TC_ERROR("Runtime linking failure.");
  }
  */
  // return llvm::CloneModule(*struct_module);
  // runtime_module->print(llvm::errs(), nullptr);
  return llvm::CloneModule(*struct_module);
}

void TaichiLLVMContext::set_struct_module(
    const std::unique_ptr<llvm::Module> &module) {
  TC_ASSERT(module);
  struct_module = llvm::CloneModule(*module);
}

template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(T t) {
  if constexpr (std::is_same_v<T, float32> || std::is_same_v<T, float64>) {
    return llvm::ConstantFP::get(*ctx, llvm::APFloat(t));
  } else if (std::is_same_v<T, int32> || std::is_same_v<T, uint32>) {
    return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
  } else if (std::is_same_v<T, int64> || std::is_same_v<T, uint64>) {
    return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
  } else {
    TC_NOT_IMPLEMENTED
    return nullptr;
  }
}

std::string TaichiLLVMContext::type_name(llvm::Type *type) {
  std::string type_name;
  llvm::raw_string_ostream rso(type_name);
  type->print(rso);
  return rso.str();
}

std::size_t TaichiLLVMContext::get_type_size(llvm::Type *type) {
  return jit->get_type_size(type);
}

template llvm::Value *TaichiLLVMContext::get_constant(float32 t);
template llvm::Value *TaichiLLVMContext::get_constant(float64 t);

template llvm::Value *TaichiLLVMContext::get_constant(int32 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint32 t);

template llvm::Value *TaichiLLVMContext::get_constant(int64 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint64 t);

TLANG_NAMESPACE_END
<commit_msg>verify struct module<commit_after>#include <llvm/Transforms/Utils/Cloning.h>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include <llvm/Linker/Linker.h>
#include <llvm/Demangle/Demangle.h>

#include "util.h"
#include "taichi_llvm_context.h"
#include "backends/llvm_jit.h"

TLANG_NAMESPACE_BEGIN

static llvm::ExitOnError exit_on_err;

TaichiLLVMContext::TaichiLLVMContext() {
  llvm::InitializeNativeTarget();
  llvm::InitializeNativeTargetAsmPrinter();
  llvm::InitializeNativeTargetAsmParser();
  ctx = std::make_unique<llvm::LLVMContext>();
  jit = exit_on_err(TaichiLLVMJIT::Create());
}

TaichiLLVMContext::~TaichiLLVMContext() {
}

llvm::Type *TaichiLLVMContext::get_data_type(DataType dt) {
  if (dt == DataType::i32) {
    return llvm::Type::getInt32Ty(*ctx);
  } else if (dt == DataType::f32) {
    return llvm::Type::getFloatTy(*ctx);
  } else if (dt == DataType::f64) {
    return llvm::Type::getDoubleTy(*ctx);
  } else {
    TC_INFO(data_type_name(dt));
    TC_NOT_IMPLEMENTED
  }
  return nullptr;
}

std::string find_existing_command(const std::vector<std::string> &commands) {
  for (auto &cmd : commands) {
    if (command_exist(cmd)) {
      return cmd;
    }
  }
  TC_P(commands);
  TC_ERROR("No command found.");
  return "";
}

void compile_runtime() {
  auto clang = find_existing_command({"clang-7", "clang"});
  TC_ASSERT(command_exist("llvm-as"));
  TC_TRACE("Compiling runtime module bitcode...");
  auto runtime_folder = get_project_fn() + "/runtime/";
  int ret = std::system(
      fmt::format("{} -S {}runtime.cpp -o {}runtime.ll -emit-llvm -std=c++17",
                  clang, runtime_folder, runtime_folder)
          .c_str());
  if (ret) {
    TC_ERROR("Runtime compilation failed.");
  }
  std::system(fmt::format("llvm-as {}runtime.ll -o {}runtime.bc",
                          runtime_folder, runtime_folder)
                  .c_str());
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::get_init_module() {
  return clone_runtime_module();
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_runtime_module() {
  if (!runtime_module) {
    compile_runtime();
    std::ifstream ifs(get_project_fn() + "/runtime/runtime.bc");
    std::string bitcode(std::istreambuf_iterator<char>(ifs),
                        (std::istreambuf_iterator<char>()));
    auto runtime =
        parseBitcodeFile(MemoryBufferRef(bitcode, "runtime_bitcode"), *ctx);
    if (!runtime) {
      TC_ERROR("Runtime bitcode load failure.");
    }
    runtime_module = std::move(runtime.get());
    for (auto &f : *runtime_module) {
      TC_INFO("Loaded runtime function: {}", std::string(f.getName()));
    }
  }
  return llvm::CloneModule(*runtime_module);
}

std::unique_ptr<llvm::Module> TaichiLLVMContext::clone_struct_module() {
  TC_ASSERT(struct_module);
  /*
  auto runtime = clone_runtime_module();
  bool failed =
      llvm::Linker::linkModules(*runtime, llvm::CloneModule(*struct_module));
  if (failed) {
    TC_ERROR("Runtime linking failure.");
  }
  */
  // return llvm::CloneModule(*struct_module);
  // runtime_module->print(llvm::errs(), nullptr);
  return llvm::CloneModule(*struct_module);
}

void TaichiLLVMContext::set_struct_module(
    const std::unique_ptr<llvm::Module> &module) {
  TC_ASSERT(module);
  if (llvm::verifyModule(*module, &llvm::errs())) {
    TC_ERROR("module broken");
  }
  struct_module = llvm::CloneModule(*module);
}

template <typename T>
llvm::Value *TaichiLLVMContext::get_constant(T t) {
  if constexpr (std::is_same_v<T, float32> || std::is_same_v<T, float64>) {
    return llvm::ConstantFP::get(*ctx, llvm::APFloat(t));
  } else if (std::is_same_v<T, int32> || std::is_same_v<T, uint32>) {
    return llvm::ConstantInt::get(*ctx, llvm::APInt(32, t, true));
  } else if (std::is_same_v<T, int64> || std::is_same_v<T, uint64>) {
    return llvm::ConstantInt::get(*ctx, llvm::APInt(64, t, true));
  } else {
    TC_NOT_IMPLEMENTED
    return nullptr;
  }
}

std::string TaichiLLVMContext::type_name(llvm::Type *type) {
  std::string type_name;
  llvm::raw_string_ostream rso(type_name);
  type->print(rso);
  return rso.str();
}

std::size_t TaichiLLVMContext::get_type_size(llvm::Type *type) {
  return jit->get_type_size(type);
}

template llvm::Value *TaichiLLVMContext::get_constant(float32 t);
template llvm::Value *TaichiLLVMContext::get_constant(float64 t);

template llvm::Value *TaichiLLVMContext::get_constant(int32 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint32 t);

template llvm::Value *TaichiLLVMContext::get_constant(int64 t);
template llvm::Value *TaichiLLVMContext::get_constant(uint64 t);

TLANG_NAMESPACE_END
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "DArray.h"

#include "Algorithms.h"
#include "BHeap.h"
#include "Defs.h"
#include "FHeap.h"
#include "Graph.h"
#include "GraphReader.h"
#include "MovingMean.h"
#include "RandomGraphGenerator.h"
#include "StopWatch.h"

using namespace ADS;

enum Mode {
    SIMPLE = 0x00,
    FIBONACCI_HEAP = 0x01,
    BINOMIAL_HEAP = 0x02,
    RANDOM = 0x03,

    UNSUPPORTED = 0x04
};

const char * PERFORMANCE_MATRIX_COLUMNS [] = {"Number of vertices", "Density",
                                              "Simple scheme(msec)",
                                              "F-heap scheme (msec)", "B-heap scheme(msec)"};

void displayPerformanceMatrixColumnNames (void)
{
    for (unsigned int i = 0; i < 5; i++)
        printf ("%s\t", PERFORMANCE_MATRIX_COLUMNS[i]);
    printf ("\n");
}

void displayPerformanceMatrix (unsigned int uiNVerteces, unsigned int uiDensity,
                               double *pMeanTimeInMSec)
{
    /* print one row of the performance matrix */
    printf ("%u\t\t\t%u%%\t\t\t%f\t\t\t%f\t\t\t%f\n",
            uiNVerteces, uiDensity, pMeanTimeInMSec[SIMPLE],
            pMeanTimeInMSec[FIBONACCI_HEAP], pMeanTimeInMSec[BINOMIAL_HEAP]);
}

void displayDistanceMatrix (cost_type **pDistances, unsigned int uiNNodes)
{
    /* printf distance matrix columns names */
    printf ("Node");
    for (unsigned int i = 0; i < uiNNodes; i++)
        printf ("\t\t%u", i);
    printf ("\n");

    for (unsigned int i = 0; i < uiNNodes; i++) {
        /* print distance matrix row name */
        printf ("%u", i);
        for (unsigned int j = 0; j < uiNNodes; j++)
            if ((i == j) || (pDistances[i][j] == INFINITY))
                 printf ("\t\t?");
            else
                printf ("\t\t%u", pDistances[i][j]);

        printf ("\n");
    }
}

Graph<unsigned int> * getGraph (Mode mode, const char *pszFile)
{
    Graph<unsigned int> *pGraph =
        new Graph<unsigned int> (GRAPH_DIRECTED, GRAPH_ALLOWS_DUPLICATE_EDGES);

    switch (mode) {
        case SIMPLE:
        case BINOMIAL_HEAP:
        case FIBONACCI_HEAP:
        {
            GraphReader *pReader = new GraphReader (pszFile);
            pReader->read (pGraph);
            break;
        }

        default:
            return NULL;
    }

    return pGraph;
}

Graph<unsigned int> * getRandomGraph (Mode mode, unsigned int uiNVerteces, unsigned int uiDensity)
{
    Graph<unsigned int> *pGraph =
        new Graph<unsigned int> (GRAPH_DIRECTED, GRAPH_ALLOWS_DUPLICATE_EDGES);

    switch (mode) {
        case RANDOM:
        {
            RandomGraphGenerator *pGenerator = new RandomGraphGenerator();
            pGenerator->generate (pGraph, uiNVerteces, uiDensity, true);
            break;
        }

        default:
            return NULL;
    }

    return pGraph;
}

Mode parseMode (const char *pszMode)
{
    if (NULL == pszMode || 0 == strlen (pszMode))
        return UNSUPPORTED;

    if (0 == strcmp ("-r", pszMode))
        return RANDOM;
    else if (0 == strcmp ("-is", pszMode))
        return SIMPLE;
    else if (0 == strcmp ("-if", pszMode))
        return FIBONACCI_HEAP;
    else if (0 == strcmp ("-ib", pszMode))
        return BINOMIAL_HEAP;

    return UNSUPPORTED;
}

void printUsageAndExit (const char *pszProgram)
{
    printf ("Usage:\n%s -r\n%s -is <file>\n%s -ib <file>\n%s -if <file>\n",
            pszProgram, pszProgram, pszProgram, pszProgram);
    exit (1);
}

int main (int argc, char *argv[])
{
    if (argc > 3)
        printUsageAndExit (argv[0]);

    Mode mode = UNSUPPORTED;
    const char *pszFile = NULL;
    for (int i = 1; i < argc; i++) {
        switch (i) {
            case 1:
                mode = parseMode (argv[1]);
                break;

            case 2:
                pszFile = argv[2];
                break;
        }
    }

    if ((mode == UNSUPPORTED) ||
        ((mode == RANDOM) && (pszFile != NULL)))
        printUsageAndExit (argv[0]);

    Graph<unsigned int> *pGraph = NULL;
    switch (mode) {
        case SIMPLE:
        {
            pGraph = getGraph (mode, pszFile);
            SimplePQ *pQueue = new SimplePQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }

        case BINOMIAL_HEAP:
        {
            pGraph = getGraph (mode, pszFile);
            BHeapPQ *pQueue = new BHeapPQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }
        case FIBONACCI_HEAP:
        {
            pGraph = getGraph (mode, pszFile);
            FHeapPQ *pQueue = new FHeapPQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }

        case RANDOM:
        {
            displayPerformanceMatrixColumnNames();

            unsigned int verticesLen = sizeof (N_VERTECES)/ sizeof (unsigned int);
            unsigned int densitiesLen = sizeof (GRAPH_DENSITIES)/ sizeof (unsigned int);

            MovingMean<long long int> mean;
            StopWatch sw;
            double performances[3];
            for (unsigned int i = 0; i < 3; i++)
                performances[i] = -1.0f;

            for (unsigned int v = 0; v < verticesLen; v++) {
                for (unsigned int d = 0; d < densitiesLen; d++) {
                    /* Generate a graph with N_VERTECES[v] vertices and density
                       GRAPH_DENSITIES[d] */
                    log ("Generating graph of %u vertices with edge density %u...",
                         N_VERTECES[v], GRAPH_DENSITIES[d]);
                    pGraph = getRandomGraph (mode, N_VERTECES[v], GRAPH_DENSITIES[d]);
                    log ("Graph generated\n");
                    /* For each of the data structures to use*/
                    for (unsigned int queue = 0; queue < 3; queue++) {
                        mean.reset();
                        /* Run Dijskstra's algorithm NUMBER_OF_RUNS times */
                        for (unsigned int r = 0; r < NUMBER_OF_RUNS; r++) {
                            PQueue *pQueue = NULL;
                            switch (queue) {
                                case SIMPLE:
                                {
                                    pQueue = new SimplePQ();
                                    break;
                                }

                                case FIBONACCI_HEAP:
                                {
                                    pQueue = new FHeapPQ();
                                    break;
                                }

                                case BINOMIAL_HEAP:
                                {
                                    pQueue = new BHeapPQ();
                                    break;
                                }
                            }
                            if (pQueue == NULL)
                                printf ("Weirdness happend\n");

                            /* start timer and execute Dijskstra's algorithm */
                            sw.startWatch();
                            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
                            mean.add (sw.stopWatch());

                            /* deallocate data structures */
                            for (unsigned int i = 0; i < pGraph->getVertexCount(); i++)
                                free (pDistances[i]);
                            free (pDistances);

                            /* just in case there were nodes that were not connected,
                               it should not be the case, but better safe then sorry... */
                            emptyQueue (pQueue);
                            delete pQueue;
                        }
                        /* Record the average of the performance for the scheme*/
                        performances[queue] = mean.getMean();
                    }
                    /* Output the performances of the 3 schemes for the given number
                       of vertices and density */
                    displayPerformanceMatrix (pGraph->getVertexCount(),
                                              pGraph->getDensityAsInt(),
                                              performances);

                    for (unsigned int i = 0; i < 3; i++)
                        performances[i] = -1.0f;
                    delete pGraph;
                }
            }
            break;
        }

        case UNSUPPORTED:
        default:
            printUsageAndExit (argv[0]);
    }
}

<commit_msg>Functions declared into the ADS namespace to reduce visibility.<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "DArray.h"

#include "Algorithms.h"
#include "Defs.h"
#include "Graph.h"
#include "GraphReader.h"
#include "MovingMean.h"
#include "RandomGraphGenerator.h"
#include "StopWatch.h"

using namespace ADS;

namespace ADS
{
    enum Mode {
        SIMPLE = 0x00,
        FIBONACCI_HEAP = 0x01,
        BINOMIAL_HEAP = 0x02,
        RANDOM = 0x03,

        UNSUPPORTED = 0x04
    };

    const char * PERFORMANCE_MATRIX_COLUMNS[] = { "Number of vertices", "Density",
        "Simple scheme(msec)",
        "F-heap scheme (msec)", "B-heap scheme(msec)" };

    void displayPerformanceMatrixColumnNames (void)
    {
        for (unsigned int i = 0; i < 5; i++)
            printf ("%s\t", PERFORMANCE_MATRIX_COLUMNS[i]);
        printf ("\n");
    }

    void displayPerformanceMatrix (unsigned int uiNVerteces, unsigned int uiDensity,
        double *pMeanTimeInMSec)
    {
        /* print one row of the performance matrix */
        printf ("%u\t\t\t%u%%\t\t\t%f\t\t\t%f\t\t\t%f\n",
            uiNVerteces, uiDensity, pMeanTimeInMSec[SIMPLE],
            pMeanTimeInMSec[FIBONACCI_HEAP], pMeanTimeInMSec[BINOMIAL_HEAP]);
    }

    void displayDistanceMatrix (cost_type **pDistances, unsigned int uiNNodes)
    {
        /* printf distance matrix columns names */
        printf ("Node");
        for (unsigned int i = 0; i < uiNNodes; i++)
            printf ("\t\t%u", i);
        printf ("\n");

        for (unsigned int i = 0; i < uiNNodes; i++) {
            /* print distance matrix row name */
            printf ("%u", i);
            for (unsigned int j = 0; j < uiNNodes; j++)
                if ((i == j) || (pDistances[i][j] == ADS_INFINITY))
                    printf ("\t\t?");
                else
                    printf ("\t\t%u", pDistances[i][j]);

            printf ("\n");
        }
    }

    Graph<unsigned int> * getGraph (Mode mode, const char *pszFile)
    {
        Graph<unsigned int> *pGraph =
            new Graph<unsigned int> (GRAPH_DIRECTED, GRAPH_ALLOWS_DUPLICATE_EDGES);

        switch (mode) {
            case SIMPLE:
            case BINOMIAL_HEAP:
            case FIBONACCI_HEAP:
            {
                GraphReader reader (pszFile);
                if (reader.read (pGraph))
                    break;
            }

            default:
                return NULL;
        }

        return pGraph;
    }

    Graph<unsigned int> * getRandomGraph (Mode mode, unsigned int uiNVerteces, unsigned int uiDensity)
    {
        Graph<unsigned int> *pGraph =
            new Graph<unsigned int> (GRAPH_DIRECTED, GRAPH_ALLOWS_DUPLICATE_EDGES);

        switch (mode) {
            case RANDOM:
            {
                RandomGraphGenerator graphGen;
                graphGen.generate (pGraph, uiNVerteces, uiDensity, true);
                break;
            }
            default:
                return NULL;
        }

        return pGraph;
    }

    Mode parseMode (const char *pszMode)
    {
        if (NULL == pszMode || 0 == strlen (pszMode))
            return UNSUPPORTED;

        if (0 == strcmp ("-r", pszMode))
            return RANDOM;
        if (0 == strcmp ("-is", pszMode))
            return SIMPLE;
        if (0 == strcmp ("-if", pszMode))
            return FIBONACCI_HEAP;
        if (0 == strcmp ("-ib", pszMode))
            return BINOMIAL_HEAP;

        return UNSUPPORTED;
    }

    void printUsageAndExit (const char *pszProgram)
    {
        printf ("Usage:\n%s -r\n%s -is <file>\n%s -ib <file>\n%s -if <file>\n",
            pszProgram, pszProgram, pszProgram, pszProgram);
        exit (1);
    }
}
int main (int argc, char *argv[])
{
    if (argc > 3)
        printUsageAndExit (argv[0]);

    Mode mode = UNSUPPORTED;
    const char *pszFile = NULL;
    for (int i = 1; i < argc; i++) {
        switch (i) {
            case 1:
                mode = parseMode (argv[1]);
                break;

            case 2:
                pszFile = argv[2];
                break;
        }
    }

    if ((mode == UNSUPPORTED) ||
        ((mode == RANDOM) && (pszFile != NULL)))
        printUsageAndExit (argv[0]);

    Graph<unsigned int> *pGraph = NULL;
    switch (mode) {
        case SIMPLE:
        {
            pGraph = getGraph (mode, pszFile);
            SimplePQ *pQueue = new SimplePQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }

        case BINOMIAL_HEAP:
        {
            pGraph = getGraph (mode, pszFile);
            BHeapPQ *pQueue = new BHeapPQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }
        case FIBONACCI_HEAP:
        {
            pGraph = getGraph (mode, pszFile);
            FHeapPQ *pQueue = new FHeapPQ();
            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
            displayDistanceMatrix (pDistances, pGraph->getVertexCount());
            delete pGraph;
            break;
        }

        case RANDOM:
        {
            displayPerformanceMatrixColumnNames();

            const unsigned int verticesLen = sizeof (N_VERTECES)/ sizeof (unsigned int);
            const unsigned int densitiesLen = sizeof (GRAPH_DENSITIES)/ sizeof (unsigned int);

            MovingMean<long long int> mean;
            StopWatch sw;
            double performances[3];
            for (unsigned int i = 0; i < 3; i++)
                performances[i] = -1.0f;

            for (unsigned int v = 0; v < verticesLen; v++) {
                for (unsigned int d = 0; d < densitiesLen; d++) {
                    /* Generate a graph with N_VERTECES[v] vertices and density
                       GRAPH_DENSITIES[d] */
                    log ("Generating graph of %u vertices with edge density %u...",
                         N_VERTECES[v], GRAPH_DENSITIES[d]);
                    pGraph = getRandomGraph (mode, N_VERTECES[v], GRAPH_DENSITIES[d]);
                    log ("Graph generated\n");
                    /* For each of the data structures to use*/
                    for (unsigned int queue = 0; queue < 3; queue++) {
                        mean.reset();
                        /* Run Dijskstra's algorithm NUMBER_OF_RUNS times */
                        for (unsigned int r = 0; r < NUMBER_OF_RUNS; r++) {
                            PQueue *pQueue = NULL;
                            switch (queue) {
                                case SIMPLE:
                                {
                                    pQueue = new SimplePQ();
                                    break;
                                }

                                case FIBONACCI_HEAP:
                                {
                                    pQueue = new FHeapPQ();
                                    break;
                                }

                                case BINOMIAL_HEAP:
                                {
                                    pQueue = new BHeapPQ();
                                    break;
                                }
                            }
                            if (pQueue == NULL)
                                printf ("Weirdness happend\n");

                            /* start timer and execute Dijskstra's algorithm */
                            sw.startWatch();
                            cost_type **pDistances = Algorithms<cost_type>::dijskstra (pGraph, pQueue);
                            mean.add (sw.stopWatch());

                            /* deallocate data structures */
                            for (unsigned int i = 0; i < pGraph->getVertexCount(); i++)
                                free (pDistances[i]);
                            free (pDistances);

                            /* just in case there were nodes that were not connected,
                               it should not be the case, but better safe then sorry... */
                            emptyQueue (pQueue);
                            delete pQueue;
                        }
                        /* Record the average of the performance for the scheme*/
                        performances[queue] = mean.getMean();
                    }
                    /* Output the performances of the 3 schemes for the given number
                       of vertices and density */
                    displayPerformanceMatrix (pGraph->getVertexCount(),
                                              pGraph->getDensityAsInt(),
                                              performances);

                    for (unsigned int i = 0; i < 3; i++)
                        performances[i] = -1.0f;
                    delete pGraph;
                }
            }
            break;
        }

        case UNSUPPORTED:
        default:
            printUsageAndExit (argv[0]);
    }
}

<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////////
//                                                                             //
// AliFemtoPairCutRadialDistance - a pair cut which checks                     //
// for some pair qualities that attempt to identify slit/doubly                //
// reconstructed tracks and also selects pairs based on their separation       //
// at the entrance to the TPC                                                  //
//                                                                             //
/////////////////////////////////////////////////////////////////////////////////
/********************************************************************************
 *
 * Author: Johanna Gramling, University of Heidelberg, jgramlin@cern.ch
 *         Malgorzata Janik, Warsaw University of Technology, majanik@cern.ch
 *         Lukasz Graczykowski, Warsaw University of Technology, lgraczyk@cern.ch
 *
 ********************************************************************************/

#include "AliFemtoPairCutRadialDistance.h"
#include <string>
#include <cstdio>

#ifdef __ROOT__
ClassImp(AliFemtoPairCutRadialDistance)
#endif

//__________________
AliFemtoPairCutRadialDistance::AliFemtoPairCutRadialDistance():
  AliFemtoPairCutAntiGamma(),
  fDPhiStarMin(0),
  fEtaMin(0),
  fMinRad(0.8),
  fMagSign(1)
{
}
//__________________
AliFemtoPairCutRadialDistance::AliFemtoPairCutRadialDistance(const AliFemtoPairCutRadialDistance& c) :
  AliFemtoPairCutAntiGamma(c),
  fDPhiStarMin(0),
  fEtaMin(0),
  fMinRad(0.8),
  fMagSign(1)
{
  fDPhiStarMin = c.fDPhiStarMin;
  fEtaMin = c.fEtaMin;
  fMinRad = c.fMinRad;
  fMagSign = c.fMagSign;
}

//__________________
AliFemtoPairCutRadialDistance::~AliFemtoPairCutRadialDistance(){
  /* no-op */
}
//__________________
bool AliFemtoPairCutRadialDistance::Pass(const AliFemtoPair* pair){
  // Accept pairs based on their TPC entrance separation and
  // quality and sharity
  bool temp = true;

//    double pih = 3.14159265358979312;
//    double pit = 6.28318530717958623;

  double phi1 = pair->Track1()->Track()->P().Phi();
  double phi2 = pair->Track2()->Track()->P().Phi();
  double chg1 = pair->Track1()->Track()->Charge();
  double chg2 = pair->Track2()->Track()->Charge();
  double ptv1 = pair->Track1()->Track()->Pt();
  double ptv2 = pair->Track2()->Track()->Pt();
  double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
  double eta2 = pair->Track2()->Track()->P().PseudoRapidity();

  Double_t rad;
  Bool_t pass5 = kTRUE;

    rad = fMinRad;
    for (Double_t iter=fMinRad*10; iter<251; iter+=1.0) {
      Double_t dps = (phi1-phi2+(TMath::ASin(-0.075*chg1*fMagSign*rad/ptv1))-(TMath::ASin(-0.075*chg2*fMagSign*rad/ptv2)));
      double etad = eta2 - eta1;
      if (fabs(etad)<fEtaMin && fabs(dps)<fDPhiStarMin) {
	//       cout << "5% cut is not passed - returning" << endl;
	pass5 = kFALSE;
	break;
      }
      rad+=0.01;
    }

  if (temp) {
    temp = AliFemtoPairCutAntiGamma::Pass(pair);
  }
  else
    fNPairsFailed++;

  return temp;
}
//__________________
AliFemtoString AliFemtoPairCutRadialDistance::Report(){
  // Prepare a report from the execution
  string stemp = "AliFemtoRadialDistance Pair Cut - remove shared and split pairs and pairs with small separation at the specified radius\n";  char ctemp[100];
  snprintf(ctemp , 100, "Accept pair with separation more that %f",fDPhiStarMin);
  stemp += ctemp;
  snprintf(ctemp , 100, "Number of pairs which passed:\t%ld  Number which failed:\t%ld\n",fNPairsPassed,fNPairsFailed);
  stemp += ctemp;
  AliFemtoString returnThis = stemp;
  return returnThis;}
//__________________

TList *AliFemtoPairCutRadialDistance::ListSettings()
{
  // return a list of settings in a writable form
  TList *tListSetttings =  AliFemtoPairCutAntiGamma::ListSettings();
  char buf[200];
  snprintf(buf, 200, "AliFemtoPairCutRadialDistance.phistarsepmin=%f", fDPhiStarMin);
  tListSetttings->AddLast(new TObjString(buf));

  return tListSetttings;
}

void AliFemtoPairCutRadialDistance::SetPhiStarDifferenceMinimum(double dtpc)
{
  fDPhiStarMin = dtpc;
}

void AliFemtoPairCutRadialDistance::SetEtaDifferenceMinimum(double etpc)
{
  fEtaMin = etpc;
}

void AliFemtoPairCutRadialDistance::SetMinimumRadius(double minrad)
{
  fMinRad = minrad;
}

void AliFemtoPairCutRadialDistance::SetMagneticFieldSign(int magsign)
{
  if(magsign>1) fMagSign = 1;
  else if(magsign<1) fMagSign = -1;
  else fMagSign = magsign;
}
<commit_msg>Fix Coverity report<commit_after>/////////////////////////////////////////////////////////////////////////////////
//                                                                             //
// AliFemtoPairCutRadialDistance - a pair cut which checks                     //
// for some pair qualities that attempt to identify slit/doubly                //
// reconstructed tracks and also selects pairs based on their separation       //
// at the entrance to the TPC                                                  //
//                                                                             //
/////////////////////////////////////////////////////////////////////////////////
/********************************************************************************
 *
 * Author: Johanna Gramling, University of Heidelberg, jgramlin@cern.ch
 *         Malgorzata Janik, Warsaw University of Technology, majanik@cern.ch
 *         Lukasz Graczykowski, Warsaw University of Technology, lgraczyk@cern.ch
 *
 ********************************************************************************/

#include "AliFemtoPairCutRadialDistance.h"
#include <string>
#include <cstdio>

#ifdef __ROOT__
ClassImp(AliFemtoPairCutRadialDistance)
#endif

//__________________
AliFemtoPairCutRadialDistance::AliFemtoPairCutRadialDistance():
  AliFemtoPairCutAntiGamma(),
  fDPhiStarMin(0),
  fEtaMin(0),
  fMinRad(0.8),
  fMagSign(1)
{
}
//__________________
AliFemtoPairCutRadialDistance::AliFemtoPairCutRadialDistance(const AliFemtoPairCutRadialDistance& c) :
  AliFemtoPairCutAntiGamma(c),
  fDPhiStarMin(0),
  fEtaMin(0),
  fMinRad(0.8),
  fMagSign(1)
{
  fDPhiStarMin = c.fDPhiStarMin;
  fEtaMin = c.fEtaMin;
  fMinRad = c.fMinRad;
  fMagSign = c.fMagSign;
}

//__________________
AliFemtoPairCutRadialDistance::~AliFemtoPairCutRadialDistance(){
  /* no-op */
}
//__________________
bool AliFemtoPairCutRadialDistance::Pass(const AliFemtoPair* pair){
  // Accept pairs based on their TPC entrance separation and
  // quality and sharity
  //  bool temp = true;

//    double pih = 3.14159265358979312;
//    double pit = 6.28318530717958623;

  double phi1 = pair->Track1()->Track()->P().Phi();
  double phi2 = pair->Track2()->Track()->P().Phi();
  double chg1 = pair->Track1()->Track()->Charge();
  double chg2 = pair->Track2()->Track()->Charge();
  double ptv1 = pair->Track1()->Track()->Pt();
  double ptv2 = pair->Track2()->Track()->Pt();
  double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
  double eta2 = pair->Track2()->Track()->P().PseudoRapidity();

  Double_t rad;
  Bool_t pass5 = kTRUE;

    rad = fMinRad;
    for (Double_t iter=fMinRad*10; iter<251; iter+=1.0) {
      Double_t dps = (phi1-phi2+(TMath::ASin(-0.075*chg1*fMagSign*rad/ptv1))-(TMath::ASin(-0.075*chg2*fMagSign*rad/ptv2)));
      double etad = eta2 - eta1;
      if (fabs(etad)<fEtaMin && fabs(dps)<fDPhiStarMin) {
	//       cout << "5% cut is not passed - returning" << endl;
	pass5 = kFALSE;
	break;
      }
      rad+=0.01;
    }

  if (pass5) {
    pass5 = AliFemtoPairCutAntiGamma::Pass(pair);
  }
  else
    fNPairsFailed++;

  return pass5;
}
//__________________
AliFemtoString AliFemtoPairCutRadialDistance::Report(){
  // Prepare a report from the execution
  string stemp = "AliFemtoRadialDistance Pair Cut - remove shared and split pairs and pairs with small separation at the specified radius\n";  char ctemp[100];
  snprintf(ctemp , 100, "Accept pair with separation more that %f",fDPhiStarMin);
  stemp += ctemp;
  snprintf(ctemp , 100, "Number of pairs which passed:\t%ld  Number which failed:\t%ld\n",fNPairsPassed,fNPairsFailed);
  stemp += ctemp;
  AliFemtoString returnThis = stemp;
  return returnThis;}
//__________________

TList *AliFemtoPairCutRadialDistance::ListSettings()
{
  // return a list of settings in a writable form
  TList *tListSetttings =  AliFemtoPairCutAntiGamma::ListSettings();
  char buf[200];
  snprintf(buf, 200, "AliFemtoPairCutRadialDistance.phistarsepmin=%f", fDPhiStarMin);
  tListSetttings->AddLast(new TObjString(buf));

  return tListSetttings;
}

void AliFemtoPairCutRadialDistance::SetPhiStarDifferenceMinimum(double dtpc)
{
  fDPhiStarMin = dtpc;
}

void AliFemtoPairCutRadialDistance::SetEtaDifferenceMinimum(double etpc)
{
  fEtaMin = etpc;
}

void AliFemtoPairCutRadialDistance::SetMinimumRadius(double minrad)
{
  fMinRad = minrad;
}

void AliFemtoPairCutRadialDistance::SetMagneticFieldSign(int magsign)
{
  if(magsign>1) fMagSign = 1;
  else if(magsign<1) fMagSign = -1;
  else fMagSign = magsign;
}
<|endoftext|>


<commit_before> #include "MultiLevelProblem.hpp"
// #include "TransientSystem.hpp"
// #include "NumericVector.hpp"
// #include "Fluid.hpp"
// #include "Parameter.hpp"

// #include "SparseMatrix.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
// #include "NonLinearImplicitSystem.hpp"
// #include "FElemTypeEnum.hpp"
// #include "Files.hpp"

// using std::cout;
// using std::endl;

#include "FemusInit.hpp"
using namespace femus;

double InitalValueU(const double &x, const double &y, const double &z){
  return x+y;
}

double InitalValueP(const double &x, const double &y, const double &z){
  return x;
}

double InitalValueT(const double &x, const double &y, const double &z){
  return y;
}

int main(int argc, char **args) {

  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  // read coarse level mesh and generate finers level meshes
  MultiLevelMesh mlMsh;
  double scalingFactor=1.;
  mlMsh.ReadCoarseMesh("./input/square.neu","seventh",scalingFactor);
  /* "seventh" is the order of accuracy that is used in the gauss integration scheme
      probably in the furure it is not going to be an argument of this function   */
  unsigned numberOfLevels=2;
  unsigned numberOfSelectiveLevels=0;
  mlMsh.RefineMesh(numberOfLevels , numberOfLevels + numberOfSelectiveLevels, NULL);
  mlMsh.PrintInfo();

  // define and initialize variables
  MultiLevelSolution mlSol(&mlMsh);

  mlSol.AddSolution("U",LAGRANGE, FIRST);
  mlSol.AddSolution("V",LAGRANGE, SERENDIPITY);
  mlSol.AddSolution("W",LAGRANGE, SECOND);
  mlSol.AddSolution("P",DISCONTINOUS_POLYNOMIAL, ZERO);
  mlSol.AddSolution("T",DISCONTINOUS_POLYNOMIAL, FIRST);

  mlSol.Initialize("All");
  mlSol.Initialize("U", InitalValueU);
  mlSol.Initialize("P", InitalValueP);
  mlSol.Initialize("T", InitalValueT); //note that this initialization is the same as piecewise constant element

  // print solutions
  std::vector < std::string > variablesToBePrinted;
  variablesToBePrinted.push_back("U");
  variablesToBePrinted.push_back("P");
  variablesToBePrinted.push_back("T");

  VTKWriter vtkIO(mlSol);
  vtkIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  GMVWriter gmvIO(mlSol);
  variablesToBePrinted.push_back("all");
  gmvIO.SetDebugOutput(true);
  gmvIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  return 1;
}

<commit_msg>class changes<commit_after> #include "MultiLevelProblem.hpp"
// #include "TransientSystem.hpp"
// #include "NumericVector.hpp"
// #include "Fluid.hpp"
// #include "Parameter.hpp"

// #include "SparseMatrix.hpp"
#include "VTKWriter.hpp"
#include "GMVWriter.hpp"
// #include "NonLinearImplicitSystem.hpp"
// #include "FElemTypeEnum.hpp"
// #include "Files.hpp"

// using std::cout;
// using std::endl;

#include "FemusInit.hpp"
using namespace femus;

double InitalValueU(const double &x, const double &y, const double &z){
  return x+y;
}

double InitalValueP(const double &x, const double &y, const double &z){
  return x;
}

double InitalValueT(const double &x, const double &y, const double &z){
  return y;
}

int main(int argc, char **args) {

  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  // read coarse level mesh and generate finers level meshes
  MultiLevelMesh mlMsh;
  double scalingFactor=1.;
  mlMsh.ReadCoarseMesh("./input/square.neu","seventh",scalingFactor);
  /* "seventh" is the order of accuracy that is used in the gauss integration scheme
      probably in the furure it is not going to be an argument of this function   */
  unsigned numberOfLevels=4;
  unsigned numberOfSelectiveLevels=0;
  mlMsh.RefineMesh(numberOfLevels , numberOfLevels + numberOfSelectiveLevels, NULL);
  mlMsh.PrintInfo();

  // define and initialize variables
  MultiLevelSolution mlSol(&mlMsh);

  mlSol.AddSolution("U",LAGRANGE, FIRST);
  mlSol.AddSolution("V",LAGRANGE, SERENDIPITY);
  mlSol.AddSolution("W",LAGRANGE, SECOND);
  mlSol.AddSolution("P",DISCONTINOUS_POLYNOMIAL, ZERO);
  mlSol.AddSolution("T",DISCONTINOUS_POLYNOMIAL, FIRST);

  mlSol.Initialize("All");

  mlSol.Initialize("U", InitalValueU);
  mlSol.Initialize("P", InitalValueP);
  mlSol.Initialize("T", InitalValueT);
  //note that this initialization is the same as piecewise constant element

  // print solutions
  std::vector < std::string > variablesToBePrinted;
  variablesToBePrinted.push_back("U");
  variablesToBePrinted.push_back("P");
  variablesToBePrinted.push_back("T");

  VTKWriter vtkIO(mlSol);
  vtkIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  GMVWriter gmvIO(mlSol);
  variablesToBePrinted.push_back("all");
  gmvIO.SetDebugOutput(false);
  gmvIO.write_system_solutions(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  return 1;
}

<|endoftext|>