Survey.cpp 19.4 KB
Newer Older
gsell's avatar
gsell committed
1 2 3 4 5 6 7 8 9 10 11 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 38 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
// ------------------------------------------------------------------------
// $RCSfile: Survey.cpp,v $
// ------------------------------------------------------------------------
// $Revision: 1.2.4.1 $
// ------------------------------------------------------------------------
// Copyright: see Copyright.readme
// ------------------------------------------------------------------------
//
// Class: Survey
//   The Survey class implements a buffer for survey tables.
//
// ------------------------------------------------------------------------
//
// $Date: 2002/12/09 15:06:08 $
// $Author: jsberg $
//
// ------------------------------------------------------------------------

#include "Tables/Survey.h"
#include "AbstractObjects/BeamSequence.h"
#include "AbstractObjects/Element.h"
#include "AbstractObjects/Expressions.h"
#include "AbstractObjects/OpalData.h"
#include "AbstractObjects/PlaceRep.h"
#include "AbstractObjects/RangeRep.h"
#include "AbstractObjects/TableRowRep.h"
#include "Attributes/Attributes.h"
#include "Algorithms/Surveyor.h"
#include "BeamlineGeometry/Euclid3D.h"
#include "Physics/Physics.h"
#include "Tables/Flatten.h"
#include "Utilities/OpalException.h"
#include "Utilities/Options.h"

#include <cmath>
#include <iomanip>
#include <iostream>
#if defined(__GNUC__) && __GNUC__ < 3
#include <strstream>
#else
#include <sstream>
#endif


// Local structures.
// ------------------------------------------------------------------------

namespace {

    // Describe a column with name and function to get it.
    struct ColDesc {

        // The column name.
        const char *colName;

        // Method to return the selected column from the given row.
        double(Survey::*get)(const Survey::Row &, int, int) const;

        int printWidth;
        int printPrecision;

        int ind_1;
        int ind_2;
    };

    // The column entries table.
    const ColDesc allColumns[] = {
        { "S",     &Survey::getS,     14,  6, 0, 0 },

        { "X",     &Survey::getX,     10,  6, 0, 0 },
        { "Y",     &Survey::getY,     10,  6, 0, 0 },
        { "Z",     &Survey::getZ,     10,  6, 0, 0 },

        { "THETA", &Survey::getTheta, 14, 10, 0, 0 },
        { "PHI",   &Survey::getPhi,   14, 10, 0, 0 },
        { "PSI",   &Survey::getPsi,   14, 10, 0, 0 },

        { "W11",   &Survey::getW,     10,  6, 1, 1 },
        { "W21",   &Survey::getW,     10,  6, 2, 1 },
        { "W31",   &Survey::getW,     10,  6, 3, 1 },
        { "W12",   &Survey::getW,     10,  6, 1, 2 },
        { "W22",   &Survey::getW,     10,  6, 2, 2 },
        { "W32",   &Survey::getW,     10,  6, 3, 2 },
        { "W13",   &Survey::getW,     10,  6, 1, 3 },
        { "W23",   &Survey::getW,     10,  6, 2, 3 },
        { "W33",   &Survey::getW,     10,  6, 3, 3 },

        { 0,       0,                  0,  0, 0, 0 }
    };


    // The print column entries table.
    const ColDesc printColumns[] = {
        { "S",     &Survey::getS,     14,  6, 0, 0 },

        { "X",     &Survey::getX,     10,  6, 0, 0 },
        { "Y",     &Survey::getY,     10,  6, 0, 0 },
        { "Z",     &Survey::getZ,     10,  6, 0, 0 },

        { "THETA", &Survey::getTheta, 14, 10, 0, 0 },
        { "PHI",   &Survey::getPhi,   14, 10, 0, 0 },
        { "PSI",   &Survey::getPsi,   14, 10, 0, 0 },

        { 0,       0,                  0,  0, 0, 0 }
    };


    // Find a column by name.
109
    const ColDesc *findCol(const Survey &table, const std::string &colName) {
gsell's avatar
gsell committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        for(const ColDesc *col = allColumns; col->colName; ++col) {
            if(colName == col->colName) {
                return col;
            }
        }

        throw OpalException("Survey::findCol()",
                            "Survey table \"" + table.getOpalName() +
                            "\" has no column named \"" + colName + "\".");
    }


    // Local class Column.
    //   Returns the value for a given column in the current row of a given
    //   table.
    class Column: public Expressions::Scalar<double> {

    public:

        //: Constructor.
        //  Identify the table by its name [b]tab[/b], and the column by its
        //  name [b]col[/b] and the function [b]col[/b].
        //  The row is specified as the ``current'' row of the table.
133
        Column(const Survey &tab, const std::string &scol, const ColDesc &col);
gsell's avatar
gsell committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

        Column(const Column &);
        virtual ~Column();

        //: Make clone.
        virtual Expressions::Scalar<double> *clone() const;

        //: Evaluate.
        virtual double evaluate() const;

        //: Print expression.
        virtual void print(std::ostream &os, int precedence = 99) const;

    private:

        // Not implemented.
        Column();
        const Column &operator=(const Column &);

        // The Table referred.
        const Survey &itsTable;

        // Column name.
157
        std::string colName;
gsell's avatar
gsell committed
158 159 160 161 162 163 164 165 166 167 168 169 170

        // The function returning the column value from the given row.
        double(Survey::*get)(const Survey::Row &, int, int) const;

        // Indices for calling get().
        int ind_1, ind_2;
    };


    // Implementation.
    // ------------------------------------------------------------------------

    Column::Column(const Survey &tab,
171
                   const std::string &name,
gsell's avatar
gsell committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 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
                   const ColDesc &desc):
        itsTable(tab),
        colName(name),
        get(desc.get),
        ind_1(desc.ind_1),
        ind_2(desc.ind_2)
    {}


    Column::Column(const Column &rhs):
        itsTable(rhs.itsTable),
        colName(rhs.colName),
        get(rhs.get),
        ind_1(rhs.ind_1),
        ind_2(rhs.ind_2)
    {}


    Column::~Column()
    {}


    Expressions::Scalar<double> *Column::clone() const {
        return new Column(*this);
    }


    double Column::evaluate() const {
        // Apply the function to the current row of the table.
        return (itsTable.*get)(itsTable.getCurrent(), ind_1, ind_2);
    }


    void Column::print(std::ostream &os, int) const {
        os << colName;
    }
};


// Class Survey::Row
// ------------------------------------------------------------------------

Survey::Row::Row(ElementBase *elem, int occur):
    FlaggedElmPtr(elem) {
    setCounter(occur);
}


Survey::Row::Row(const FlaggedElmPtr &rhs):
    FlaggedElmPtr(rhs)
{}


Survey::Row::~Row()
{}


double Survey::Row::getS() const {
    return s;
}


const Euclid3D &Survey::Row::getMap() const {
    return euclid;
}


// Class Survey
// ------------------------------------------------------------------------

// The attributes of class Survey.
namespace {
    enum {
        LINE,        // The lattice to be used.
        RANGE,       // The range in the lattice.
        STATIC,      // The flag for suppressing recalculation.
        INIT,        // If given, take initial values from another table.
        X0,          // The initial position  X.
        Y0,          // The initial position  Y.
        Z0,          // The initial position  Z.
        THETA0,      // The initial azimuth   THETA.
        PHI0,        // The initial elevation PHI.
        PSI0,        // The initial roll      PSI.
        L,           // Sum of design lengths.
        SIZE
    };
}


Survey::Survey():
    Table(SIZE, "SURVEY",
          "The \"SURVEY\" command defines a table of survey data which "
          "can be matched or tabulated."),
    itsTable(0), itsVisitor(0) {
    itsAttr[LINE] = Attributes::makeString
                    ("LINE", "Name of the lattice to be surveyed");
    itsAttr[RANGE] = Attributes::makeRange
                     ("RANGE", "The range in the lattice");
    itsAttr[STATIC] = Attributes::makeBool
                      ("STATIC", "If true, the table is not recalculated at each iteration");
    itsAttr[INIT] = Attributes::makeTableRow
                    ("INIT", "If given, this table position is used to initialise");
    itsAttr[X0] = Attributes::makeReal
                  ("X0", "Initial X position in m");
    itsAttr[Y0] = Attributes::makeReal
                  ("Y0", "Initial Y position in m");
    itsAttr[Z0] = Attributes::makeReal
                  ("Z0", "Initial Z position in m");
    itsAttr[THETA0] = Attributes::makeReal
                      ("THETA0", "Initial azimuth angle in rad");
    itsAttr[PHI0] = Attributes::makeReal
                    ("PHI0", "Initial pitch angle in rad");
    itsAttr[PSI0] = Attributes::makeReal
                    ("PSI0", "Initial roll angle in rad");

    // READ ONLY.
    itsAttr[L] = Attributes::makeReal
                 ("L", "Sum of design lengths in m");
    itsAttr[L].setReadOnly(true);
}


294
Survey::Survey(const std::string &name, Survey *parent):
gsell's avatar
gsell committed
295 296 297 298 299 300 301 302 303 304
    Table(name, parent), itsTable(new TLine(name)), itsVisitor(0)
{}


Survey::~Survey() {
    if(itsTable)   delete itsTable;
    if(itsVisitor) delete itsVisitor;
}


305
Survey *Survey::clone(const std::string &name) {
gsell's avatar
gsell committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 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 408 409 410 411 412 413 414 415 416 417
    return new Survey(name, this);
}


void Survey::execute() {
    // Find BeamSequence definition.
    itsLine = Attributes::getString(itsAttr[LINE]);
    BeamSequence *use = BeamSequence::find(itsLine);

    // Make sure all is up-to-date.
    OpalData::getInstance()->update();

    // Create flat list with space for data storage.
    RangeRep range = Attributes::getRange(itsAttr[RANGE]);
    Flatten<Row> flattener(*use->fetchLine(), *itsTable, range);
    flattener.execute();

    if(itsTable->empty() && Options::warn) {
        std::cerr << "\n### Warning ### Survey table \"" << getOpalName()
                  << "\" contains no elements.\n" << std::endl;
    } else {
        itsTable->front().setSelectionFlag(true);
        itsTable->back().setSelectionFlag(true);
    }

    // Fill the table.
    itsVisitor = new Surveyor(*itsTable, false);
    fill();

    // Set static flag.
    if(Attributes::getBool(itsAttr[STATIC])) dynamic = false;
    printTable(std::cout, getDefault());
}


void Survey::fill() {
    if(refill) {
        // Reset the surveyor.
        double x, y, z, phi, theta, psi;
        if(itsAttr[INIT]) {
            TableRowRep rowrep = Attributes::getTableRow(itsAttr[INIT]);
            Table *init = Table::find(rowrep.getTabName());

            if(matches(init)) {
                PlaceRep pinit = rowrep.getPosition();
                Survey  *sinit = dynamic_cast<Survey *>(init);
                sinit->fill();
                const Row &row = sinit->findRow(pinit);
                itsVisitor->setMap(sinit->getMap(row));
            } else {
                throw OpalException("Survey::fill()", "Table \"" + rowrep.getTabName() +
                                    "\" is not suitable for initialising survey \"" +
                                    getOpalName() + "\".");
            }
        } else {
            x     = Attributes::getReal(itsAttr[X0]);
            y     = Attributes::getReal(itsAttr[Y0]);
            z     = Attributes::getReal(itsAttr[Z0]);
            phi   = Attributes::getReal(itsAttr[PHI0]);
            theta = Attributes::getReal(itsAttr[THETA0]);
            psi   = Attributes::getReal(itsAttr[PSI0]);

            // Use the OPAL-8 conventions.
            Rotation3D rot = Rotation3D::YRotation(theta) *
                             Rotation3D::XRotation(- phi) * Rotation3D::ZRotation(psi);
            itsVisitor->setMap(Euclid3D(Vector3D(x, y, z), rot));
        }

        s = 0.0;

        for(TLine::iterator i = itsTable->begin(); i != itsTable->end(); ++i) {
            // Advance through element.
            i->accept(*itsVisitor);

            // Update accumulated length.
            ElementBase &elem = *i->getElement();
            if(! dynamic_cast<Beamline *>(&elem)) {
                s += elem.getElementLength();
            }

            // Copy row to table line.
            itsVisitor->getMap(i->euclid);
            i->s = s;
        }

        Euclid3D map;
        itsVisitor->getMap(map);
        map.getAll(x, y, z, phi, theta, psi);
        Attributes::setReal(itsAttr[L], s);
        refill = false;
    }
}


const Survey::Row &Survey::findRow(const PlaceRep &place) {
    PlaceRep row(place);
    row.initialize();
    for(TLine::const_iterator i = itsTable->begin();
        i != itsTable->end(); ++i) {
        row.enter(*i);
        if(row.isActive()) return *i;
        row.leave(*i);
    }

#if defined(__GNUC__) && __GNUC__ < 3
    char buffer[128];
    std::ostrstream os(buffer, sizeof(buffer));
#else
    std::ostringstream os;
#endif
    os << row << std::ends;
#if defined(__GNUC__) && __GNUC__ < 3
418
    std::string name(buffer);
gsell's avatar
gsell committed
419 420 421 422 423 424 425 426 427
    throw OpalException("Survey::setRow()", "Row \"" + name +
                        "\" not found in survey table \"" + getOpalName() + "\".");
#else
    throw OpalException("Survey::setRow()", "Row \"" + os.str() +
                        "\" not found in survey table \"" + getOpalName() + "\".");
#endif
}


428
double Survey::getCell(const PlaceRep &place, const std::string &name) {
gsell's avatar
gsell committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    const Row &row = findRow(place);
    const ColDesc *col = findCol(*this, name);
    return (this->*(col->get))(row, col->ind_1, col->ind_2);
}


Table::CellArray Survey::getDefault() const {
    CellArray columns;
    for(const ColDesc *col = printColumns; col->colName; ++col) {
        Expressions::PtrToScalar<double> expr =
            new Column(*this, col->colName, *col);
        columns.push_back(Cell(expr, col->printWidth, col->printPrecision));
    }
    return columns;
}


446
std::vector<double> Survey::getColumn(const RangeRep &rng, const std::string &name) {
gsell's avatar
gsell committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    // Find proper column function.
    const ColDesc *col = findCol(*this, name);
    RangeRep range(rng);
    range.initialize();
    std::vector<double> column;

    for(current = itsTable->begin(); current != itsTable->end(); ++current) {
        range.enter(*current);
        if(range.isActive()) {
            column.push_back((this->*(col->get))(*current, col->ind_1, col->ind_2));
        }
        range.leave(*current);
    }

    return column;
}


const Survey::Row &Survey::getCurrent() const {
    return *current;
}


double Survey::getLength() {
    return itsTable->getElementLength();
}


const Beamline *Survey::getLine() const {
    return itsTable;
}


std::vector<double>
481
Survey::getRow(const PlaceRep &pos, const std::vector<std::string> &columns) {
gsell's avatar
gsell committed
482 483 484 485 486 487 488 489 490 491
    const Row &row = findRow(pos);
    std::vector<double> result;

    if(columns.empty()) {
        // Standard column selection.
        for(const ColDesc *col = printColumns; col->colName != 0; ++col) {
            result.push_back((this->*(col->get))(row, col->ind_1, col->ind_2));
        }
    } else {
        // User column selection.
492
        for(std::vector<std::string>::const_iterator name = columns.begin();
gsell's avatar
gsell committed
493 494 495 496 497 498 499 500 501 502
            name != columns.end(); ++name) {
            const ColDesc *col = findCol(*this, *name);
            result.push_back((this->*(col->get))(row, col->ind_1, col->ind_2));
        }
    }

    return result;
}


503
bool Survey::isDependent(const std::string &name) const {
gsell's avatar
gsell committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517
    // Test if name refers to LINE attribute.
    if(itsLine == name) return true;

    // Test if name occurs in table.
    for(TLine::const_iterator i = itsTable->begin(); i != itsTable->end(); ++i) {
        if(i->getElement()->getName() == name) return true;
    }

    // Otherwise replacement is not required.
    return false;
}


Expressions::PtrToScalar<double>
518
Survey::makeColumnExpression(const std::string &colName) const {
gsell's avatar
gsell committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    return new Column(*this, colName, *findCol(*this, colName));
}


bool Survey::matches(Table *rhs) const {
    return dynamic_cast<Survey *>(rhs) != 0;
}


void Survey::printTable(std::ostream &os, const CellArray &cells) const {
    // Write table specific header.
    OpalData::getInstance()->printTitle(os);
    os << '\n';
    os << "Geometric layout for line: " << itsAttr[LINE]
       << ", range: " << itsAttr[RANGE] << "." << '\n';

    // Find line length.
    int lineLength = 16;
    for(CellArray::const_iterator cell = cells.begin();
        cell < cells.end(); ++cell) {
        lineLength += cell->printWidth;
    }
541
    os << std::string(lineLength, '-') << '\n';
gsell's avatar
gsell committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555

    // Print table header.
    os << "Element         ";
    for(CellArray::const_iterator cell = cells.begin();
        cell < cells.end(); ++cell) {
#if defined(__GNUC__) && __GNUC__ < 3
        char buffer[256];
        std::ostrstream ss(buffer, 256);
#else
        std::ostringstream ss;
#endif
        cell->itsExpr->print(ss, 0);
        ss << std::ends;
#if defined(__GNUC__) && __GNUC__ < 3
556
        std::string image(buffer);
gsell's avatar
gsell committed
557 558 559 560 561 562
#else
        std::string image = ss.str();
#endif

        if(int(image.length()) < cell->printWidth) {
            // Right adjust the column header.
563
            os << std::string(cell->printWidth - image.length(), ' ') << image;
gsell's avatar
gsell committed
564 565
        } else {
            // Truncate the column header.
566
            os << ' ' << std::string(image, 0, cell->printWidth - 3) << "..";
gsell's avatar
gsell committed
567 568 569
        }
    }
    os << '\n';
570
    os << std::string(lineLength, '-') << '\n';
gsell's avatar
gsell committed
571 572 573 574 575 576 577 578

    // Save the formatting flags.
    std::streamsize old_prec = os.precision(6);
    os.setf(std::ios::fixed, std::ios::floatfield);

    // Write table body.
    for(current = itsTable->begin(); current != itsTable->end(); ++current) {
        if(current->getSelectionFlag()) {
579
            std::string name = current->getElement()->getName();
gsell's avatar
gsell committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
            if(int occur = current->getCounter()) {
#if defined(__GNUC__) && __GNUC__ < 3
                char buffer[128];
                std::ostrstream tos(buffer, 128);
#else
                std::ostringstream tos;
#endif
                tos << name << '[' << occur << ']' << std::ends;
#if defined(__GNUC__) && __GNUC__ < 3
                name = buffer;
#else
                name = tos.str();
#endif
            }

            if(name.length() > 16) {
                // Truncate the element name.
597
                os << std::string(name, 0, 13) << ".. ";
gsell's avatar
gsell committed
598 599
            } else {
                // Left adjust the element name.
600
                os << name << std::string(16 - name.length(), ' ');
gsell's avatar
gsell committed
601 602 603 604 605 606 607 608 609 610 611 612 613
            }

            for(CellArray::const_iterator cell = cells.begin();
                cell != cells.end(); ++cell) {
                os << std::setw(cell->printWidth)
                   << std::setprecision(cell->printPrecision)
                   << cell->itsExpr->evaluate();
            }
            os << '\n';
        }
    }

    // Write table specific summary.
614
    os << std::string(lineLength, '-') << '\n';
gsell's avatar
gsell committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654

    // Restore the formatting flags.
    os.precision(old_prec);
    os.setf(std::ios::fixed, std::ios::floatfield);
}


double Survey::getS(const Survey::Row &row, int, int) const {
    return current->getS();
}


const Euclid3D &Survey::getMap(const Survey::Row &row) const {
    return row.getMap();
}


double Survey::getX(const Survey::Row &row, int, int) const {
    return row.getMap().getX();
}


double Survey::getY(const Survey::Row &row, int, int) const {
    return row.getMap().getY();
}


double Survey::getZ(const Survey::Row &row, int, int) const {
    return row.getMap().getZ();
}


double Survey::getPhi(const Survey::Row &row, int, int) const {
    const Rotation3D &rot = row.getMap().getRotation();
    return atan2(rot(1, 2), sqrt(rot(1, 0) * rot(1, 0) + rot(1, 1) * rot(1, 1)));
}


double Survey::getTheta(const Survey::Row &row, int, int) const {
    const Rotation3D &rot = row.getMap().getRotation();
655
    double arg = std::abs(rot(0, 2)) + std::abs(rot(2, 2));
gsell's avatar
gsell committed
656 657 658 659 660 661
    return (arg > 1.0e-10) ? atan2(rot(0, 2), rot(2, 2)) : 0.0;
}


double Survey::getPsi(const Survey::Row &row, int, int) const {
    const Rotation3D &rot = row.getMap().getRotation();
662
    double arg = std::abs(rot(1, 0)) + std::abs(rot(1, 1));
gsell's avatar
gsell committed
663 664 665 666 667 668 669
    return (arg > 1.0e-10) ? atan2(rot(1, 0), rot(1, 1)) : 0.0;
}


double Survey::getW(const Survey::Row &row, int ind_1, int ind_2) const {
    return row.getMap().M(ind_1, ind_2);
}