EICTrack.cc 16.4 KB
Newer Older
1 2
#undef NDEBUG

David Blyth's avatar
David Blyth committed
3 4 5 6 7 8 9 10
#include <fstream>
#include <vector>

#include <ConstField.h>
#include <EventDisplay.h>
#include <FieldManager.h>
#include <KalmanFitStatus.h>
#include <KalmanFitter.h>
11
#include <KalmanFitterInfo.h>
David Blyth's avatar
David Blyth committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <MaterialEffects.h>
#include <ProlateSpacepointMeasurement.h>
#include <TGeoManager.h>
#include <TGeoMaterialInterface.h>
#include <TVector3.h>
#include <Track.h>
#include <TrackPoint.h>
#include <proio/event.h>
#include <proio/model/eic/eic.pb.h>
#include <proio/reader.h>
#include <proio/writer.h>

#include "EICTrack.h"

using namespace eictrack;
using namespace proio::model;

std::map<std::string, BFieldFactory *> BField::factories;

void printBFields() {
    std::cout << "Available magnetic field types:\n";
    for (auto type : BField::AvailableTypes()) {
        std::cout << "\t" << type << "\n";
    }
}

David Blyth's avatar
fixme  
David Blyth committed
38
genfit::AbsMeasurement *makeMeasurement(eic::EnergyDep *entry) {
David Blyth's avatar
David Blyth committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    if (entry->mean() / entry->noise() < 2) return NULL;

    TVectorD hitCoords(3);
    hitCoords = 0;
    TMatrixDSym hitCov(3);
    hitCov = 0;
    double wTot = 0;

    for (auto obsPos : entry->pos()) {
        TMatrixDSym hitCovTemp(3);
        hitCovTemp = 0;

        for (auto randVar : obsPos.noise()) {
            hitCovTemp[0][0] += randVar.sigma().x() * randVar.sigma().x();
            hitCovTemp[0][1] += randVar.sigma().x() * randVar.sigma().y();
            hitCovTemp[0][2] += randVar.sigma().x() * randVar.sigma().z();
            hitCovTemp[1][1] += randVar.sigma().y() * randVar.sigma().y();
            hitCovTemp[1][2] += randVar.sigma().y() * randVar.sigma().z();
            hitCovTemp[2][2] += randVar.sigma().z() * randVar.sigma().z();
        }

        if (entry->pos().size() == 1) {
            hitCov += 0.01 * hitCovTemp;
            hitCoords[0] += 0.1 * obsPos.mean().x();
            hitCoords[1] += 0.1 * obsPos.mean().y();
            hitCoords[2] += 0.1 * obsPos.mean().z();

            auto measurement = new genfit::SpacepointMeasurement(hitCoords, hitCov, 0, 0, nullptr);
            return measurement;
        } else {
            hitCovTemp[0][0] += obsPos.mean().x() * obsPos.mean().x();
            hitCovTemp[0][1] += obsPos.mean().x() * obsPos.mean().y();
            hitCovTemp[0][2] += obsPos.mean().x() * obsPos.mean().z();
            hitCovTemp[1][1] += obsPos.mean().y() * obsPos.mean().y();
            hitCovTemp[1][2] += obsPos.mean().y() * obsPos.mean().z();
            hitCovTemp[2][2] += obsPos.mean().z() * obsPos.mean().z();

            double w = obsPos.weightmod() + 1;
            hitCov += 0.01 * w * hitCovTemp;
            hitCoords[0] += 0.1 * w * obsPos.mean().x();
            hitCoords[1] += 0.1 * w * obsPos.mean().y();
            hitCoords[2] += 0.1 * w * obsPos.mean().z();
            wTot += w;
        }
    }

    hitCov *= 1. / wTot;
    hitCoords *= 1. / wTot;
    hitCov[0][0] -= hitCoords[0] * hitCoords[0];
    hitCov[0][1] -= hitCoords[0] * hitCoords[1];
    hitCov[0][2] -= hitCoords[0] * hitCoords[2];
    hitCov[1][1] -= hitCoords[1] * hitCoords[1];
    hitCov[1][2] -= hitCoords[1] * hitCoords[2];
    hitCov[2][2] -= hitCoords[2] * hitCoords[2];

    auto measurement = new genfit::SpacepointMeasurement(hitCoords, hitCov, 0, 0, nullptr);
    return measurement;
}

void checkMetadata(proio::Event *event) {
    static std::shared_ptr<const std::string> lastGeomString(NULL);
    if (event->Metadata().count("geometry")) {
        auto geomString = event->Metadata().at("geometry");
        if (geomString != lastGeomString) {
            char dirTemplate[] = "eictrack_XXXXXX";
            std::string tempDir = mkdtemp(dirTemplate);
            std::string geomFilePath = tempDir + "/geometry.gdml";
            std::ofstream geomFile(geomFilePath);
            geomFile << *geomString;
            geomFile.close();

            TGeoManager::Import(geomFilePath.c_str());
            genfit::MaterialEffects::getInstance()->setNoEffects(false);
            genfit::MaterialEffects::getInstance()->init(new genfit::TGeoMaterialInterface());

            unlink(geomFilePath.c_str());
            rmdir(tempDir.c_str());
            lastGeomString = geomString;
        }
    }

    static std::shared_ptr<const std::string> lastFieldString(NULL);
    if (event->Metadata().count("field")) {
        auto fieldString = event->Metadata().at("field");
        if (fieldString != lastFieldString) {
            auto colonLoc = fieldString->find_first_of(':');
            auto fieldName = fieldString->substr(0, colonLoc);
            std::vector<double> params;
            for (int i = colonLoc; i != std::string::npos && i < fieldString->size();
                 i = fieldString->find_first_of(',', i + 1)) {
                double value = atof(fieldString->substr(i + 1).c_str());
                params.push_back(value);
            }
            genfit::AbsBField *field = BField::Create(fieldName, &params[0]);
            if (field)
                genfit::FieldManager::getInstance()->init(field);
            else {
                std::cerr << "Invalid magnetic field type: " << fieldName << "\n";
                printBFields();
                exit(EXIT_FAILURE);
            }

            lastFieldString = fieldString;
        }
    }
}

146 147 148 149 150 151 152 153 154 155 156 157
void trackEvent(proio::Event *event, const int n_validate, genfit::KalmanFitter *fitter) {
    // build available observations list and a map of observations to
    // GenFit measurements
    std::vector<uint64_t> available_obs;
    std::map<uint64_t, genfit::AbsMeasurement *> measurements;
    std::map<uint64_t, double> seed_sort_param;
    for (auto id : event->TaggedEntries("Tracker")) {
        auto obs = dynamic_cast<eic::EnergyDep *>(event->GetEntry(id));
        if (obs) {
            available_obs.push_back(id);
            auto measurement = makeMeasurement(obs);
            measurements[id] = measurement;
158 159 160 161 162 163 164 165 166
            double t_sum = 0;
            double weight_sum = 0;
            for (auto pos : obs->pos()) {
                double weight = pos.weightmod() + 1;
                t_sum += pos.mean().t() * weight;
                weight_sum += weight;
            }
            seed_sort_param[id] = t_sum / weight_sum;
            // seed_sort_param[id] = measurement->getRawHitCoords().Norm2Sqr();
167 168 169 170 171 172 173
        }
    }

    auto seed_sort_fn = [&](const uint64_t a_id, const uint64_t b_id) {
        return seed_sort_param[a_id] > seed_sort_param[b_id];
    };

174 175
    while (available_obs.size() >= n_validate) {
        std::sort(available_obs.begin(), available_obs.end(), seed_sort_fn);
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        auto track = new genfit::Track;

        // build genfit::Track object and process with Kalman
        std::vector<uint64_t> track_obs;
        auto measurement = measurements[available_obs.back()];
        track->insertMeasurement(measurement->clone());
        TVector3 ip_pos(0, 0, 0);
        auto meas_coords = measurement->getRawHitCoords();
        TVector3 meas_pos(meas_coords[0], meas_coords[1], meas_coords[2]);
        track->setStateSeed(ip_pos, meas_pos);
        track->addTrackRep(new genfit::RKTrackRep(11));
        track->addTrackRep(new genfit::RKTrackRep(-11));
        track->addTrackRep(new genfit::RKTrackRep(13));
        track->addTrackRep(new genfit::RKTrackRep(-13));
        for (auto rep : track->getTrackReps()) fitter->processTrackPartially(track, rep, 0, 0);
        track_obs.push_back(available_obs.back());
        available_obs.pop_back();

        // extend Track
195
        std::vector<uint64_t> tmp_unavailable;
196 197 198 199
        while (available_obs.size() > 0) {
            // kernel sort available observations
            meas_coords = measurement->getRawHitCoords();
            meas_pos = TVector3(meas_coords[0], meas_coords[1], meas_coords[2]);
200 201 202 203 204 205 206 207
            // auto kernel_sort_fn = [&](const uint64_t a_id, const uint64_t b_id) {
            //    auto a_coords = measurements[a_id]->getRawHitCoords();
            //    TVector3 a_pos(a_coords[0], a_coords[1], a_coords[2]);
            //    auto b_coords = measurements[b_id]->getRawHitCoords();
            //    TVector3 b_pos(b_coords[0], b_coords[1], b_coords[2]);
            //    return meas_pos.Dot(a_pos) / seed_sort_param[a_id] <
            //           meas_pos.Dot(b_pos) / seed_sort_param[b_id];
            //};
208
            auto kernel_sort_fn = [&](const uint64_t a_id, const uint64_t b_id) {
209 210
                return pow(seed_sort_param[a_id] - seed_sort_param[track_obs.back()], 2) >
                       pow(seed_sort_param[b_id] - seed_sort_param[track_obs.back()], 2);
211 212 213 214 215 216 217 218 219 220 221
            };
            std::sort(available_obs.begin(), available_obs.end(), kernel_sort_fn);

            auto tmp_meas = measurements[available_obs.back()];
            track->insertMeasurement(tmp_meas->clone(), -1);
            auto track_point = track->getPoint(-1);

            // process and check for goodness
            std::vector<genfit::AbsTrackRep *> all_reps(track->getTrackReps());
            std::vector<genfit::AbsTrackRep *> bad_reps;
            for (auto rep : all_reps) {
222
                fitter->processTrackPartially(track, rep, 0, -1);
223 224 225 226 227 228
                auto fi = static_cast<genfit::KalmanFitterInfo *>(track_point->getKalmanFitterInfo(rep));
                if (!fi) {
                    bad_reps.push_back(rep);
                    continue;
                }
                auto chi2_inc = fi->getUpdate(1)->getChiSquareIncrement();
229 230
                // std::cout << "chi2_inc: " << chi2_inc << std::endl;
                if (chi2_inc > 5) bad_reps.push_back(rep);
231 232 233
            }
            if (bad_reps.size() == all_reps.size()) {
                track->deletePoint(-1);
234 235 236
                tmp_unavailable.push_back(available_obs.back());
                available_obs.pop_back();
                continue;
237 238
            }

239
            // clear bad track reps and pop hit from available list
240 241 242 243 244
            for (auto rep : bad_reps) track->deleteTrackRep(track->getIdForRep(rep));
            track_obs.push_back(available_obs.back());
            available_obs.pop_back();
            measurement = tmp_meas;
        }
245
        for (auto id : tmp_unavailable) available_obs.push_back(id);
246

247 248 249 250
        // fit and prune track
        std::cout << "track_obs.size(): " << track_obs.size() << std::endl;
        while (track_obs.size() >= n_validate) {
            track->determineCardinalRep();
251
            auto rep = track->getCardinalRep();
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            track->udpateSeed(0, rep);
            fitter->processTrackWithRep(track, rep);

            if (track->getFitStatus(rep)->isFitConverged()) {
                auto eic_track = new eic::Track;
                try {
                    auto fieldMgr = genfit::FieldManager::getInstance();
                    for (unsigned int id = 0; id < track->getNumPoints() - 1; id++) {
                        auto point = track->getPointWithMeasurement(id);
                        auto info = point->getFitterInfo(rep);
                        auto state = info->getFittedState();
                        TVector3 pos = rep->getPos(state);
                        TVector3 mom = rep->getMom(state);
                        TVector3 field = fieldMgr->getFieldVal(pos);
                        double charge = rep->getCharge(state);
                        double chargeMag = abs(charge);
                        double time = rep->getTime(state);
                        double length = track->getTrackLen(rep, id, id + 1);

                        auto segment = eic_track->add_segment();
                        auto vertex = segment->mutable_vertex();
                        vertex->set_x(pos.x() * 10);
                        vertex->set_y(pos.y() * 10);
                        vertex->set_z(pos.z() * 10);
                        vertex->set_t(time);
                        auto poq = segment->mutable_poq();
                        poq->set_x(mom.x() / chargeMag);
                        poq->set_y(mom.y() / chargeMag);
                        poq->set_z(mom.z() / chargeMag);
                        auto magfield = segment->mutable_magfield();
                        magfield->set_x(field.x() / 10);
                        magfield->set_y(field.y() / 10);
                        magfield->set_z(field.z() / 10);
                        segment->set_chargesign(charge);
                        segment->set_length(length * 10);
                    }
                    auto entryID = event->AddEntry(eic_track, "Tracker");
                    event->TagEntry(entryID, "Reconstructed");
                    event->TagEntry(entryID, "Vis");
                    std::cout << "successful fit" << std::endl;
                } catch (const genfit::Exception e) {
                    std::cout << e.what() << std::endl;
                }

                track_obs.clear();
                break;
            } else {
                std::cout << "failed to converge" << std::endl;

                double max_chi2_inc = 0;
                int max_chi2_inc_i = 0;
                for (int i = 0; i < track_obs.size(); i++) {
                    auto fi =
                        static_cast<genfit::KalmanFitterInfo *>(track->getPoint(i)->getKalmanFitterInfo(rep));
                    if (!fi) {
                        max_chi2_inc_i = i;
                        break;
                    }
                    auto update = fi->getUpdate(1);
                    if (!update) {
                        max_chi2_inc_i = i;
                        break;
                    }
                    auto chi2_inc = update->getChiSquareIncrement();
                    if (chi2_inc > max_chi2_inc) {
                        max_chi2_inc = chi2_inc;
                        max_chi2_inc_i = i;
                    }
320
                }
321 322 323 324 325 326

                if (max_chi2_inc_i == 0) break;

                available_obs.push_back(track_obs[max_chi2_inc_i]);
                track_obs.erase(track_obs.begin() + max_chi2_inc_i);
                track->deletePoint(max_chi2_inc_i);
327 328 329
            }
        }

330 331 332 333 334 335
        // return unconsumed hits to available list
        // std::sort(available_obs.begin(), available_obs.end(), seed_sort_fn);
        // seed_sort_param[track_obs[0]] += seed_sort_param[available_obs.back()];
        // std::sort(available_obs.begin(), available_obs.end(), seed_sort_fn);
        // for (int i = 0; i < track_obs.size(); i++) available_obs.push_back(track_obs[i]);

336 337 338 339 340 341
        delete track;
    }

    for (auto idMeasPair : measurements) delete idMeasPair.second;
}

David Blyth's avatar
David Blyth committed
342 343 344 345 346 347 348 349 350
void printUsage() {
    std::cerr << "Usage: eictrack [options] <input proio file> <output proio file>\n";
    std::cerr << "options:\n";
    std::cerr << "  -c  output compression level: 0 for uncompressed, 1 for LZ4 compression, 2 for GZIP\n"
                 "      compression (default 1))\n";
    std::cerr << std::endl;
}

int main(int argc, char **argv) {
351 352 353 354 355 356 357 358 359 360
    class NullBuffer : public std::streambuf {
       public:
        int overflow(int c) { return c; }
    };
    NullBuffer nullBuffer;
    genfit::errorOut.rdbuf(&nullBuffer);

    genfit::MaterialEffects::getInstance()->setNoEffects();
    genfit::MaterialEffects::getInstance()->setEnergyLossBrems(false);
    genfit::KalmanFitter fitter;
361
    // fitter.setMaxIterations(10);
David Blyth's avatar
David Blyth committed
362
    int comp = 0;
363 364
    int n_validate = 5;

David Blyth's avatar
David Blyth committed
365
    int opt;
366
    while ((opt = getopt(argc, argv, "c:n:h")) != -1) {
David Blyth's avatar
David Blyth committed
367 368 369 370
        switch (opt) {
            case 'c':
                comp = atoi(optarg);
                break;
371 372 373 374 375 376 377
            case 'n':
                n_validate = atoi(optarg);
                if (n_validate < 2) {
                    std::cerr << "n must be >= 2" << std::endl;
                    exit(EXIT_FAILURE);
                }
                break;
David Blyth's avatar
David Blyth committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            default:
                printUsage();
                exit(EXIT_FAILURE);
        }
    }

    std::string inputFilename;
    std::string outputFilename;
    if (optind + 1 < argc) {
        inputFilename = argv[optind];
        outputFilename = argv[optind + 1];
    } else {
        printUsage();
        exit(EXIT_FAILURE);
    }

    auto reader = new proio::Reader(inputFilename);
    auto writer = new proio::Writer(outputFilename);
    switch (comp) {
        case 1:
            writer->SetCompression(proio::LZ4);
            break;
        case 2:
            writer->SetCompression(proio::GZIP);
            break;
        default:
            writer->SetCompression(proio::UNCOMPRESSED);
    }

    proio::Event event;
408
    int n_events = 0;
David Blyth's avatar
David Blyth committed
409
    while (reader->Next(&event)) {
410
        std::cout << "event " << n_events << std::endl;
David Blyth's avatar
David Blyth committed
411
        checkMetadata(&event);
412
        trackEvent(&event, n_validate, &fitter);
David Blyth's avatar
David Blyth committed
413
        writer->Push(&event);
414 415
        n_events++;
        if (n_events == 10) break;
David Blyth's avatar
David Blyth committed
416 417 418 419 420
    }

    delete writer;
    delete reader;
}