diff --git a/doc/changes.rst b/doc/changes.rst index f3d650e0..38e78d9d 100644 --- a/doc/changes.rst +++ b/doc/changes.rst @@ -6,12 +6,9 @@ fiberassign change log 1.0.0 (planned) --------------- -* First tag of refactor/rewrite after merge of tsk_refactor. +* First tag of refactor/rewrite after merge (PR `#153`_). -0.11.2 (unreleased) -------------------- - -* No changes yet. +.. _`#153`: https://github.com/desihub/fiberassign/pull/153 0.11.1 (2019-01-25) ------------------- diff --git a/doc/running.rst b/doc/running.rst deleted file mode 100644 index fb6e0b7c..00000000 --- a/doc/running.rst +++ /dev/null @@ -1,92 +0,0 @@ -.. _running: - - -Running -=============== - - -The main executable ``fiberassign`` is a python wrapper around the C++ -``fiberassign.exec`` code. - -Running ``fiberassign --help`` gives the full set of command line -options:: - - usage: fiberassign [-h] --mtl MTL --sky SKY --stdstar STDSTAR --fibstatusfile FIBSTATUSFILE - [--footprint FOOTPRINT] - [--positioners POSITIONERS] [--surveytiles SURVEYTILES] - [--telra TELRA] [--teldec TELDEC] [--tileid TILEID] - [--tileobsconditions TILEOBSCONDITIONS] [--outdir OUTDIR] - [--starmask STARMASK] [--rundate RUNDATE] - [--gfafile GFAFILE] [--nstarpetal NSTARPETAL] - [--nskypetal NSKYPETAL] [--nocleanup] - - optional arguments: - -h, --help show this help message and exit - --mtl MTL input targets (FITS file) - --sky SKY input sky positions (FITS file) - --stdstar STDSTAR input std stars (FITS file) - --fibstatusfile FIBSTATUSFILE - list of positioners and its status (ECSV file) - --footprint FOOTPRINT - list of tiles defining the footprint (FITS file) - --positioners POSITIONERS - list of positioners on the focal plane (FITS file) - --surveytiles SURVEYTILES - set of tiles to run fiberassign on (text file) - --telra TELRA Right Ascension of arbitrary pointing - overrides - --surveytiles - --teldec TELDEC Declination of arbitrary pointing - overrides - --surveytiles - --tileid TILEID Integer ID of arbitrary pointing - overrides - --surveytiles - --tileobsconditions TILEOBSCONDITIONS - Mask describing observing program (DARK:1, GRAY:2, - BRIGHT:4) - overrides --surveytiles - --outdir OUTDIR output directory (default = ./) - --starmask STARMASK integer mask defining standard stars - --rundate RUNDATE run date [YYYY-MM-DD] - --gfafile GFAFILE GFA file (FITS tile) - --nstarpetal NSTARPETAL - number of standard stars per petal (default=10) - --nskypetal NSKYPETAL - number of sky fibers per petal (default=40) - --nocleanup - - - - -An example that provides the minimal set of required arguments would be:: - - fiberassign --mtl mtl.fits --stdstar std.fits --sky sky.fits - --fibstatusfile fiberstatus.ecsv --outdir $SCRATCH/temp/ - -In this example there are four files that must be **explicitly** -provided: - -- ``mtl.fits``: DESI Merged Target List files contain a single binary - table covering the entire footprint. They contain the variables in - the Targets files plus other variables that define the priority and - number of observations as required by fiber assignment. These - variables are computed using the available information both in the - target and the DESI redshift catalogs. The full datamodel can be - found `here - `_. - -- ``std.fits``: DESI standard star locations contain a single binary - table covering the entire footprint. They contain the variables in - the Targets files with the objects that were flagged as - standards. This file follows the `mtl` datamodel. - -- ``sky.fits``: DESI sky locations contain a single binary table - covering the entire Legacy Surveys footprint. The imaging “blob - maps” are bisected to achieve a requisite number of sky locations - per sq. deg. Sky locations are placed within the bisected grid as - far from blobs that contain sources as is possible. Flux is measured - in an aperture at each sky location. The full datamodel can be found - `here - `_. - - -- ``fiberstatus.ecsv``: - - diff --git a/old/src/collision.cpp b/old/src/collision.cpp deleted file mode 100644 index e2f844d3..00000000 --- a/old/src/collision.cpp +++ /dev/null @@ -1,358 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" -#include "collision.h" - -// Angles are dpair (cos t, sin t) -// PosP -PosP::PosP (double r10, double r20) { - r1 = r10; - r2 = r20; -} - -// Intersection of segments -int orientation (const dpair & p, const dpair & q, const dpair & r) { - // See 10th slides from following link for derivation of the formula - // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf - double val = (q.s - p.s) * (r.f - q.f) - (q.f - p.f) * (r.s - q.s); - /* - if (val == 0) { - printf("CAUTIOUS in orientation, colinear case ! \n"); - return 0; // colinear - } - */// clock or counterclock wise - return (val > 0) ? 1 : 2; -} - -bool intersect (const dpair & p1, const dpair & q1, const dpair & p2, - const dpair & q2) { - int o1 = orientation(p1, q1, p2); - int o2 = orientation(p1, q1, q2); - // (when error) terminate called after throwing an instance of - // 'std::bad_alloc' - if (o1 == o2) { - return false; - } - int o3 = orientation(p2, q2, p1); - int o4 = orientation(p2, q2, q1); - if (o3 == o4) { - return false; - } else { - return true; - } -} - -// Intersection of segment and circle -bool intersect_seg_circ (const dpair & A, const dpair & B, const dpair & O, - const double & rad) { - // Make a drawing, with C the projection of O on (AB), use scalar products - double rad_sq = sq(rad); - double AO_sq = sq(A, O); - double AB_AO = scalar_prod(A, B, O); - if (AB_AO <= 0) { - return AO_sq < rad_sq; - } - double BO_sq = sq(B, O); - double BA_BO = scalar_prod(B, A, O); - if (BA_BO <= 0) { - return BO_sq < rad_sq; - } - double AB_sq = sq(A, B); - return AO_sq * (1 - sq(AB_AO) / (AO_sq * AB_sq) ) < rad_sq; -} - -// element -element::element () { - color = 'k'; -} - -element::element (bool b) { - is_seg = b; - color = 'k'; -} - -element::element (const dpair & Ocenter, - const double & rad0) { - is_seg = false; - O = Ocenter; - rad = rad0; - color = 'k'; -} - -element::element (const dpair & A, - const dpair & B) { - is_seg = true; - add(A); - add(B); - color = 'k'; -} - -element::element (const dpair & A, char c, double transp, - double rad0) { - is_seg = true; - add(A); - color = c; - transparency = transp; - radplot = rad0; -} - -void element::add (const double & a, - const double & b) { - segs.push_back(dpair(a, b) ); -} -void element::add (const dpair & p) { - segs.push_back(p); -} -void element::transl (const dpair & t) { - if (is_seg) { - for (size_t i = 0; i < segs.size(); i++) { - segs[i] = segs[i] + t; - } - } else { - O = O + t; - } -} - -void element::rotation (const dpair & t, - const dpair & axis) { - if (is_seg) { - for (size_t i = 0; i < segs.size(); i++) { - rot_pt(segs[i], axis, t); - } - } else { - rot_pt(O, axis, t); - } -} - -void element::print () const { - printf("seg ? %d", is_seg); - fl(); - if (!O.isnull() || (rad != 0) ) { - printf(" - center (%f,%f) rad %f", O.f, O.s, rad); - fl(); - } - printf(" sizesegs= %lu ", segs.size() ); - fl(); - if (0 < segs.size() ) { - debl(" - segs : "); - for (size_t i = 0; i < segs.size(); i++) { - segs[i].print(); - } - } else { - printf(" no seg "); - } - printf("\n"); - fl(); -} - -void element::limits (Dlist & lims) const { - if (is_seg) { - for (size_t i = 0; i < segs.size(); i++) { - if (segs[i].f < lims[0]) lims[0] = segs[i].f; - if (segs[i].s < lims[2]) lims[2] = segs[i].s; - if (segs[i].f > lims[1]) lims[1] = segs[i].f; - if (segs[i].s > lims[3]) lims[3] = segs[i].s; - } - } else { - if (O.f - rad < lims[0]) lims[0] = O.f - rad; - if (O.s - rad < lims[2]) lims[2] = O.s - rad; - if (O.f + rad > lims[1]) lims[1] = O.f + rad; - if (O.s + rad > lims[3]) lims[3] = O.s + rad; - } -} - -bool intersect (const element & e1, const element & e2) { - if (e1.is_seg && e2.is_seg) { - for (size_t i = 0; i < e1.segs.size() - 1; i++) { - for (size_t j = 0; j < e2.segs.size() - 1; j++) { - bool b = intersect(e1.segs[i], e1.segs[i + 1], e2.segs[j], - e2.segs[j + 1]); - if (b) return true; - } - } - return false; - } - if (e1.is_seg && !e2.is_seg) { - for (size_t i = 0; i < e1.segs.size() - 1; i++) { - bool b = intersect_seg_circ(e1.segs[i], e1.segs[i + 1], e2.O, - e2.rad); - if (b) { - return true; - } - } - return false; - } - if (!e1.is_seg && e2.is_seg) { - for (size_t i = 0; i < e2.segs.size() - 1; i++) { - bool b = intersect_seg_circ(e2.segs[i], e2.segs[i + 1], e1.O, - e1.rad); - if (b) { - return true; - } - } - return false; - } - if (!e1.is_seg && !e2.is_seg) { - return (sq(e1.O, e2.O) < sq(e1.rad + e2.rad) ); - } - return false; -} - -// polygon -void polygon::add (const element & el) { - elmts.push_back(el); -} - -void polygon::add (const polygon & p) { - for (size_t i = 0; i < p.elmts.size(); i++) { - elmts.push_back(p.elmts[i]); - } -} - -void polygon::transl (const dpair & t) { - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].transl(t); - } - axis = axis + t; -} - -void polygon::rotation (const dpair & t) { - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].rotation(t, axis); - } -} - -void polygon::rotation_origin (const dpair & t) { - dpair origin = dpair(); - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].rotation(t, origin); - } - rot_pt(axis, origin, t); -} - -void polygon::print () const { - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].print(); - } - printf(" - axis : "); - axis.print(); -} - -void polygon::set_color (char c) { - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].color = c; - } -} - -Dlist polygon::limits () const { - Dlist lims = initDlist(4); - lims[0] = 1e4; - lims[2] = 1e4; - lims[1] = -1e4; - lims[3] = -1e4; - for (size_t i = 0; i < elmts.size(); i++) { - elmts[i].limits(lims); - } - return lims; -} - -polygon create_fh () { - polygon fh; - fh.axis = dpair(-3.0, 0); - // Only segments - // element el; - // el.add(-4.240,0.514); el.add(-3.514,1.240); el.add(-2.668,1.240); - // el.add(-2.235,0.990); el.add(0.387,0.990); el.add(0.967,0.410); - // el.add(0.967,-0.410); el.add(0.387,-0.990); el.add(-1.844,-0.990); - // el.add(-1.981,-1.757); el.add(-2.688,-2.015); el.add(-2.944,-1.922); - // el.add(-2.944,-1.339); el.add(-3.682,-1.072); el.add(-4.240,-0.514); - // el.add(-4.240,0.514); - // fh.add(el); - // Segments and disks - fh.add(element(dpair(), 0.967) ); // Head disk - fh.add(element(dpair(-3.0, 0.990), dpair(0, 0.990) ) ); // Upper segment - element set(true); // Lower segment - set.add(-2.944, -1.339); - set.add(-2.944, -2.015); - set.add(-1.981, -1.757); - set.add(-1.844, -0.990); - set.add(0, -0.990); - fh.add(set); - fh.transl(dpair(6.0, 0) ); - return fh; -} - -polygon create_cb () { - polygon cb; - cb.axis = dpair(3.0, 0); - // Segments and disks - cb.add(element(dpair(3.0, 0), 2.095) ); - element set(true); - set.add(5.095, -0.474); - set.add(4.358, -2.5); - set.add(2.771, -2.5); - set.add(1.759, -2.792); - set.add(0.905, -0.356); - cb.add(set); - return cb; -} - -// Functions -void rot_pt (dpair & A, const dpair & ax, const dpair & angle) { - dpair P = A - ax; - if (P.isnull() ) return; - double r = norm(P); - dpair cos_sin = cos_sin_angle(P); - dpair sum = sum_angles(cos_sin, angle); - A = ax + dpair(r * sum.f, r * sum.s); -} - -Dlist angles (const dpair & A, const PosP & posp) { - double phi = 2 * acos(norm(A) / (2 * posp.r1) ); - double theta = atan(A.s / A.f) - phi / 2 + (A.f < 0 ? M_PI : 0); - Dlist ang; - ang.push_back(cos(theta) ); - ang.push_back(sin(theta) ); - ang.push_back(cos(phi) ); - ang.push_back(sin(phi) ); - return ang; -} - -void repos_cb_fh (polygon & cb, polygon & fh, const dpair & O, const dpair & G, - const PosP & posp) { - // repositions positioner (central body, ferule holder) - dpair Gp = G - O; - if (sq(posp.r1 + posp.r2) < sq(Gp) ) { - printf( - "Error galaxy out of range of fiber in repos_fiber O.f %f O.s %f G.f %f G.s %f\n", O.f, O.s, G.f, - G.s ); - } - Dlist anglesT = angles(Gp, posp); - dpair theta_ = dpair(anglesT[0], anglesT[1]); - dpair phi_ = dpair(anglesT[2], anglesT[3]); - cb.rotation_origin(theta_); - fh.rotation_origin(theta_); - fh.rotation(phi_); - fh.transl(O); - cb.transl(O); -} - -bool collision (const polygon & p1, const polygon & p2) { - for (size_t i = 0; i < p1.elmts.size(); i++) { - for (size_t j = 0; j < p2.elmts.size(); j++) { - if (intersect(p1.elmts[i], p2.elmts[j]) ) { - return true; - } - } - } - return false; -} diff --git a/old/src/collision.h b/old/src/collision.h deleted file mode 100644 index c57db603..00000000 --- a/old/src/collision.h +++ /dev/null @@ -1,110 +0,0 @@ -#ifndef COLLISION_H -#define COLLISION_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" - -// Can contain information on geometry of fiber one day (hardcoded for now) not -// used yet -class PosP { - public: - double r1, r2; - PosP (double r1, double r2); -}; - -// Rotation of A (angle t) aroud axis axis -void rot_pt (dpair & A, const dpair & ax, const dpair & angle); - -// Intersection between segments p1-q1 and p2-q2 -bool intersect (const dpair & p1, const dpair & q1, const dpair & p2, - const dpair & q2); - -// List segments, or circles -class element { - public: - // True if segments, false if circle - bool is_seg; - // Segments - Dplist segs; - // Circle center - dpair O; - // Circle radius - double rad; - // For python plot - char color; - // For plotting - double transparency; - // For plotting - double radplot; - element (); - // b : is_seg - element (bool b); - // Creates circle - element (const dpair & O, const double & rad); - // Creates segment list with only the segment AB - element (const dpair & A, const dpair & B); - // Point with color - element (const dpair & A, char c, double transp, double rad0); - // Add point to segments list - void add (const double & a, const double & b); - // Add point to segments list - void add (const dpair & p); - // Translation by t - void transl (const dpair & t); - // Rotation of the angle def by t (cos,sin) around axis axis - void rotation (const dpair & t, const dpair & axis); - void print () const; - // Xmin, Xmax, Ymin, Ymax of the element - void limits (Dlist & lims) const; -}; - -class Elements : public std::vector {}; - -// Intersection between 2 elements -bool intersect (const element & e1, const element & e2); - -class polygon { - public: - // Segments and circles - Elements elmts; - dpair axis; - void add (const element & el); - // Add all elements of p - void add (const polygon & p); - // Translation - void transl (const dpair & t); - // Rotation aroud polygon's axis - void rotation (const dpair & t); - // Rotation around O - void rotation_origin (const dpair & t); - void print () const; - // Change color of the polygon - void set_color (char c); - // Xmin, Xmax, Ymin, Ymax of the polygon - Dlist limits () const; -}; - -// fh = ferrule holder -polygon create_fh (); -// cb = central body -polygon create_cb (); -// Check collision -bool collision (const polygon & p1, const polygon & p2); -// cos sin theta and phi for a galaxy which is in A (ref to the origin) -Dlist angles (const dpair & A, const PosP & posp); -// G loc of galaxy, O origin. Repositions fh and cb in the good position -// according to O, G -void repos_cb_fh (polygon & cb, polygon & fh, const dpair & O, const dpair & G, - const PosP & posp); - -#endif diff --git a/old/src/feat.cpp b/old/src/feat.cpp deleted file mode 100644 index c15c735e..00000000 --- a/old/src/feat.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include /* srand, rand */ -#include -#include "misc.h" -#include "collision.h" -#include "feat.h" -#include "version.h" - - -void Usage (char * ExecName) { - std::cout << "Usage: " << ExecName; - std::cout << " --mtl "; - std::cout << " --sky "; - std::cout << " --stdstar "; - std::cout << " --surveytiles "; - std::cout << " --footprint "; - std::cout << " --positioners "; - std::cout << " --fibstatusfile "; - std::cout << " --outdir "; - std::cout << " --starmask "; - std::cout << " --nskypetal "; - std::cout << " [--rundate ]" << std::endl; - std::cout << std::endl; - std::cout << " Or to print version to STDOUT: "; - std::cout << " --version" << std::endl; - exit(0); -} - -// Features ------------------------------------------------------------------ -Feat::Feat () { - Count = 0; - Categories = 0; - AvCollide = 3.2; - Collide = 1.98; - NoCollide = 7.0; - PatrolRad = 5.8; - NeighborRad = 14.05; - PlateRadius = 1.65; - MaxSS = 10; - MaxSF = 40; - InterPlate = 0; - Collision = false; - Exact = true; - StarMask = 60129542144; -} - -void Feat::readInputFile (const char file[]) { - const int Mc = 512; // Max chars per line - char delimiter = ' '; - std::ifstream fIn; - fIn.open(file); // open a file - if (!fIn.good() ) myexit(1); // Not found - while (!fIn.eof() ) { - char buf[Mc]; - fIn.getline(buf, Mc); - Slist tok = s2vec(buf, delimiter); - if (2 <= tok.size() ) { - if (tok[0] == "Targfile") Targfile = tok[1]; - if (tok[0] == "tileFile") tileFile = tok[1]; - if (tok[0] == "fibFile") fibFile = tok[1]; - if (tok[0] == "fibstatusFile") fibstatusFile = tok[1]; - if (tok[0] == "surveyFile") surveyFile = tok[1]; - if (tok[0] == "outDir") outDir = tok[1]; - if (tok[0] == "SStarsfile") SStarsfile = tok[1]; - if (tok[0] == "SkyFfile") SkyFfile = tok[1]; - if (tok[0] == "runDate") runDate = tok[1]; - } - } - fIn.close(); -} - -void Feat::parseCommandLine (int argc, char * * argv) { - int i; - for (i = 1; i < argc; ) { - if (!strcmp(argv[i], "--mtl") ) { - i++; - Targfile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--sky") ) { - i++; - SkyFfile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--stdstar") ) { - i++; - SStarsfile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--surveytiles") ) { - i++; - surveyFile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--outdir") ) { - i++; - outDir = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--footprint") ) { - i++; - tileFile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--positioners") ) { - i++; - fibFile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--fibstatusfile") ) { - i++; - fibstatusFile = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--rundate") ) { - i++; - runDate = str(argv[i]); - i++; - } else if (!strcmp(argv[i], "--starmask") ) { - i++; - StarMask = atol(argv[i]); - i++; - } else if (!strcmp(argv[i], "--nstarpetal") ) { - i++; - MaxSS = atoi(argv[i]); - i++; - } else if (!strcmp(argv[i], "--nskypetal") ) { - i++; - MaxSF = atoi(argv[i]); - i++; - } else if (!strcmp(argv[i], "--help") ) { - Usage(argv[0]); - } else if (!strcmp(argv[i], "-h") ) { - Usage(argv[0]); - } else if (!strcmp(argv[i], "--version") ) { - std::cout << version() << std::endl; - exit(0); - } else { - fprintf (stderr, "\nUnrecognized option: %s\n\n", argv[i]); - Usage(argv[0]); - } - } -} diff --git a/old/src/feat.h b/old/src/feat.h deleted file mode 100644 index 933752b6..00000000 --- a/old/src/feat.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef FEAT_H -#define FEAT_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" -#include "collision.h" - -// Feat -------------------------------------------------- -// F for features -class Feat { - public: - // Set by features file - str tileFile; - str fibFile; - str outDir; - str Targfile; - str SStarsfile; - str SkyFfile; - str surveyFile; - str fibstatusFile; - str runDate; - // bit in desi_target that signals a standard star - long StarMask; - int InterPlate; - int MaxSS; - int MaxSF; - double PlateRadius; - int PrintGalObs; - // True when we take collisions into account - bool Collision; - bool Exact; - double AvCollide; - double Collide; - double NoCollide; - double PatrolRad; - double NeighborRad; - bool Verif; - bool Ascii; - bool BrightTime; - int Categories; - // Set after reading other input files - int Nplate; - int NUsedplate; - int Ngal; - int NSStars; - int NSkyF; - int Ntarg; - int Nfiber; - int Npetal; - // Number of fibers by petals - int Nfbp; - // Memorizes geometry of central body and fiber holder - polygon cb; - polygon fh; - // Permit to count some things - int Count; - // Practical used lists - List no_ss_sf; - List ss_sf; - // Methods - Feat (); - void readInputFile (const char fname[]); - void parseCommandLine (int argc, char * * argv); - int id (str s) const; - // Init ids member - void init_ids (); - // Same - void init_ids_types (); - List init_ids_list (str l[], int size) const; - void init_types (); - void init_no_ss_sf (); - void init_ss_sf (); - // Whether kind is of type "type" - bool iftype (int kind, str type) const; -}; - -#endif diff --git a/old/src/fiberassign.cpp b/old/src/fiberassign.cpp deleted file mode 100644 index c3b06a32..00000000 --- a/old/src/fiberassign.cpp +++ /dev/null @@ -1,258 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "modules/htmTree.h" -#include "modules/kdTree.h" -#include "misc.h" -#include "feat.h" -#include "structs.h" -#include "collision.h" -#include "global.h" - -#include -#include -#include -#include - - -namespace py = pybind11; - -using ShapeContainer = py::detail::any_container; - - -void fiberassign_exec ( - std::string mtlfile, - std::string skyfile, - std::string stdstarfile, - std::string surveyfile, - std::string tilefile, - std::string fiberfile, - std::string statusfile, - std::string rundate, - std::string outdir, - long starmask - ) { - - // t for global, time for local - Time t, time; - init_time(t); - Feat F; - MTL M; - - // Assign members of Feat class. - // FIXME: This should really be in the constructor. - F.Targfile = mtlfile; - F.SkyFfile = skyfile; - F.SStarsfile = stdstarfile; - F.surveyFile = surveyfile; - F.outDir = outdir; - F.tileFile = tilefile; - F.fibFile = fiberfile; - F.fibstatusFile = statusfile; - F.runDate = rundate; - F.StarMask = starmask; - - // Read input files for standards, skys and targets. - // Try to read SS and SF before targets to avoid wasting time if these - // smaller files can't be read. - init_time_at(time, "# Read target, SS, SF files", t); - MTL SStars = read_MTLfile(F.SStarsfile, F, F.StarMask, 0); - MTL SkyF = read_MTLfile(F.SkyFfile, F, 0, 1); - MTL Targ = read_MTLfile(F.Targfile, F, 0, 0); - print_time(time, "# ...read targets took :"); - - // combine the three input files - M = Targ; - printf(" Target size %lu \n", M.size() ); - std::cout.flush(); - - // need to be able to match immutable target id to position in list - // check for duplicates on mtl only to allow duplication with SS - std::map invert_target; - std::map ::iterator targetid_to_idx; - std::pair ::iterator, bool> ret; - for (unsigned i = 0; i < M.size(); ++i) { - ret = invert_target.insert(std::make_pair(M[i].id, i) ); - // check for duplicates (std::map.insert only created keys, fails on - // duplicate keys) - if (ret.second == false ) { - std::ostringstream o; - o << "Duplicate targetid " << M[i].id << " in MTL"; - throw std::logic_error(o.str().c_str() ); - } - } - M.insert(M.end(), SStars.begin(), SStars.end() ); - printf(" Standard Star size %lu \n", M.size() ); - M.insert(M.end(), SkyF.begin(), SkyF.end() ); - printf(" Sky Fiber size %lu \n", M.size() ); - init_time_at(time, "# map position in target list to immutable targetid", - t); - init_time_at(time, "# assign priority classes", t); - F.Ngal = M.size(); - assign_priority_class(M); - std::vector count_class(M.priority_list.size(), 0); - for (size_t i = 0; i < M.size(); ++i) { - if (!M[i].SS && !M[i].SF) { - count_class[M[i].priority_class] += 1; - } - } - for (size_t i = 0; i < M.priority_list.size(); ++i) { - printf(" class %lu number %d\n", i, count_class[i]); - } - print_time(time, "# ...priority list took :"); - init_time_at(time, "# Start positioners", t); - - // fiber positioners - F.Npetal = 10; // spectrometers run 0 to 9 unless pacman - FP pp = read_fiber_positions(F); - read_fiber_status(pp, F); - - // order the fibers by their fiber number (fib_num) not simply order in - // list - // need to fix spectrom (List) and fp - // each fiber has two co-ordinates so divide by two - F.Nfiber = pp.size(); - - // fibers per petal = 500 - F.Nfbp = F.Nfiber / F.Npetal; - print_time(time, "# ..posiioners took :"); - init_time_at(time, "# Start plates", t); - - // P is original list of plates - Plates P = read_plate_centers(F); - F.Nplate = P.size(); - printf("# Read %s plate centers from %s and %d fibers from %s\n", - f(F.Nplate).c_str(), F.tileFile.c_str(), F.Nfiber, - F.fibFile.c_str() ); - print_time(time, "# ..plates took :"); - - // Computes geometries of cb and fh: pieces of positioner - used to - // determine possible collisions - F.cb = create_cb(); // cb=central body - F.fh = create_fh(); // fh=fiber holder - - //// Collect available galaxies <-> tilefibers -------------------- - // HTM Tree of galaxies - const double MinTreeSize = 0.01; - init_time_at(time, "# Start building HTM tree", t); - htmTree T(M, MinTreeSize); - print_time(time, "# Doing kd-tree... took :"); // T.stats(); - init_time_at(time, "# collect galaxies at ", t); - - // For plates/fibers, collect available galaxies; done in parallel P[plate - // j].av_gal[k]=[g1,g2,..] - collect_galaxies_for_all(M, T, P, pp, F); - print_time(time, "# ... took :"); // T.stats(); - init_time_at(time, "# collect available tile-fibers at", t); - - // For each galaxy, computes available tilefibers G[i].av_tfs = - // [(j1,k1),(j2,k2),..] - collect_available_tilefibers(M, P, F); - - //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| - printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); - Assignment A(M, F); - - // Make a plan ---------------------------------------------------- - print_time(t, "# Start assignment at : "); - simple_assign(M, P, pp, F, A); - - // check to see if there are tiles with no galaxies - // need to keep mapping of old tile list to new tile list and inverse map - A.inv_order = initList(F.Nplate, -1); - int inv_count = 0; - for (int j = 0; j < F.Nplate; ++j) { - bool not_done = true; - for (int k = 0; k < F.Nfiber && not_done; ++k) { - if (A.TF[j][k] != -1) { - // suborder[jused] is jused-th used plate - A.suborder.push_back(j); - not_done = false; - // inv_order[j] is -1 unless used - A.inv_order[j] = inv_count; - inv_count++; - } - } - } - F.NUsedplate = A.suborder.size(); - printf(" Plates actually used %d \n", F.NUsedplate); - - // Smooth out distribution of free fibers, and increase the number of - // assignments - // probably should not hard wire the limits i<1, i<3 in redistribute and - // improve - // more iterations will improve performance slightly - for (int i = 0; i < 1; i++) { - redistribute_tf(M, P, pp, F, A, 0); - } - for (int i = 0; i < 1; i++) { - improve(M, P, pp, F, A, 0); - redistribute_tf(M, P, pp, F, A, 0); - } - init_time_at(time, "# assign SS and SF ", t); - - // try assigning SF and SS before real time assignment - for (int jused = 0; jused < F.NUsedplate; ++jused) { - int j = A.suborder[jused]; - // Assign SS and SF for each tile - assign_sf_ss(j, M, P, pp, F, A); - assign_unused(j, M, P, pp, F, A); - } - - // fill all unused fibers with sky fibers - for (int jused = 0; jused < F.NUsedplate; ++jused) { - int j = A.suborder[jused]; - fill_unused_with_sf(j, M, P, pp, F, A); - } - - // Results -------------------------------------------------------*/ - std::vector total_used_by_class(M.priority_list.size(), 0); - int total_used_SS = 0; - int total_used_SF = 0; - for (int jused = 0; jused < F.NUsedplate; ++jused) { - std::vector used_by_class(M.priority_list.size(), 0); - int used_SS = 0; - int used_SF = 0; - int j = A.suborder[jused]; - for (int k = 0; k < F.Nfiber; ++k) { - int g = A.TF[j][k]; - if (g != -1) { - if (M[g].SS) { - total_used_SS++; - used_SS++; - } else if (M[g].SF) { - used_SF++; - total_used_SF++; - } else { - used_by_class[M[g].priority_class]++; - total_used_by_class[M[g].priority_class]++; - } - } - } - } - - init_time_at(time, "# count SS and SF ", t); - printf(" Totals SS %4d SF %4d", total_used_SS, total_used_SF); - for (size_t pr = 0; pr < M.priority_list.size(); ++pr) { - printf(" class %2lu %5d", pr, total_used_by_class[pr]); - } - printf("\n"); - - init_time_at(time, "# print fits files ", t); - for (int jused = 0; jused < F.NUsedplate; jused++) { - int j = A.suborder[jused]; - fa_write(j, F.outDir, M, P, pp, F, A); // Write output - } - print_time(t, "# Finished !... in"); - return; -} diff --git a/old/src/fiberassign.h b/old/src/fiberassign.h deleted file mode 100644 index d30c4412..00000000 --- a/old/src/fiberassign.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef FIBERASSIGN_H -#define FIBERASSIGN_H - -#include - - -void fiberassign_exec ( - std::string mtlfile, - std::string skyfile, - std::string stdstarfile, - std::string surveyfile, - std::string tilefile, - std::string fiberfile, - std::string statusfile, - std::string rundate, - std::string outdir, - long starmask -); - - -#endif diff --git a/old/src/global.cpp b/old/src/global.cpp deleted file mode 100644 index b34e3ca6..00000000 --- a/old/src/global.cpp +++ /dev/null @@ -1,1125 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "modules/htmTree.h" -#include "modules/kdTree.h" -#include "misc.h" -#include "feat.h" -#include "structs.h" -#include "global.h" - -// t for global, time for local -Time t; - -// Collecting information from input -// ------------------------------------------------------------ -void collect_galaxies_for_all (const MTL & M, - const htmTree & T, Plates & P, - const FP & pp, - const Feat & F) { - // provides list of galaxies available to fiber k on tile j: - // P[j].av_gals[k] - init_time(t, "# Begin collecting available galaxies"); - double rad = F.PlateRadius * M_PI / 180.; - - #pragma omp parallel - { - #pragma omp master - { - printf(" "); - } - // Collects for each plate - // start at jj=0 not id - #pragma omp for - for (int j = 0; j < F.Nplate; j++) { - plate p = P[j]; - // Takes neighboring galaxies that fall on this plate - std::vector nbr = T.near(M, p.nhat, rad); - // Projects thoses galaxies on the focal plane - Onplates O; - for (size_t gg = 0; gg < nbr.size(); gg++) { - int g = nbr[gg]; - // struct onplate op = change_coords(M[g],p); - struct onplate op = radec2xy(M[g], p); - op.id = g; - // Check that the target corresponds to the right program - if (M[g].obsconditions & p.obsconditions) { - O.push_back(op); - } - } - // Build 2D KD tree of those galaxies - KDtree kdT(O, 2); - // For each fiber, finds all reachable galaxies within patrol - // radius, thanks to the tree - for (int k = 0; k < F.Nfiber; k++) { - dpair X = pp[k].coords; - std::vector posit; - posit.push_back(pp[k].fp_x); - posit.push_back(pp[k].fp_y); - std::vector gals = kdT.near(&posit[0], 0.0, F.PatrolRad); - for (size_t g = 0; g < gals.size(); g++) { - dpair Xg = projection(gals[g], j, M, P); - if (sq(Xg, X) < sq(F.PatrolRad) ) { - P[j].av_gals[k].push_back(gals[g]); - int q = pp[k].spectrom; - // better to make SS & SF assigned to fibers - if (M[gals[g]].SS) { - P[j].SS_av_gal[q].push_back(gals[g]); - P[j].SS_av_gal_fiber[k].push_back(gals[g]); - } - if (M[gals[g]].SF) { - P[j].SF_av_gal[q].push_back(gals[g]); - P[j].SF_av_gal_fiber[k].push_back(gals[g]); - } - } - } - } - } - } - print_time(t, "# ... took :"); -} - -bool pairCompare (const std::pair & firstElem, - const std::pair & secondElem) { - // used to sort galaxies by subpriority - return firstElem.first < secondElem.first; -} - -std::vector sort_by_subpriority (MTL & M, std::vector init) { - // sorts list of galaxies by subpriority - std::vector out; - std::vector > pairs; - for (size_t gg = 0; gg < init.size(); ++gg) { - int g = init[gg]; - std::pair this_pair (M[g].subpriority, g); - pairs.push_back(this_pair); - } - std::sort(pairs.begin(), pairs.end(), pairCompare); - for (size_t gg = 0; gg < init.size(); ++gg) { - out.push_back(pairs[gg].second); - } - return out; -} - -bool int_pairCompare (const std::pair & firstElem, - const std::pair & secondElem) { - // used to sort fibers by fib_num - return firstElem.first < secondElem.first; -} - -void collect_available_tilefibers (MTL & M, const Plates & P, const Feat & F) { - // M[i].av_tfs is list of tile-fiber pairs available to galaxy i - Time t; - init_time(t, "# Begin computing available tilefibers"); - for (int j = 0; j < F.Nplate; j++) { - for (int k = 0; k < F.Nfiber; k++) { - for (size_t m = 0; m < P[j].av_gals[k].size(); m++) { - // i is the id of the mth galaxy available to tile j and fiber - // k - int i = P[j].av_gals[k][m]; - // list of tile-fibers available to galaxy i - M[i].av_tfs.push_back(pair(j, k) ); - } - } - } - print_time(t, "# ... took :"); - int count_outside = 0; - for (size_t g = 0; g < M.size(); ++g) { - if ( ( M[g].av_tfs.size() == 0) && M[g].SF) { - ++count_outside; - } - } - printf("galaxies outside footprint %d\n", count_outside); -} - -// Assignment sub-functions -// ------------------------------------------------------------------ -// Allow (j,k) to observe g ? -inline bool ok_assign_g_to_jk (int g, int j, int k, const Plates & P, - const MTL & M, const FP & pp, const Feat & F, - const Assignment & A) { - // if fiber is stuck or broken do not assign anything - if (pp[k].stuck || pp[k].broken) { - return false; - } - if (F.Collision) { - for (size_t i = 0; i < pp[k].N.size(); i++) { - if (g == A.TF[j][pp[k].N[i]]) { - return false; - } - } - } - // Avoid 2 neighboring fibers observe the same galaxy (can happen only when - // Collision=true) - if (A.find_collision(j, k, g, pp, M, P, F) != -1) { - return false; - } - // No collision - return true; - // doesn't require that jk is unassigned//doesn't require that g isn't - // assigned already on this plate - // use is_assigned_jg for this -} - -// makes sure we don't exceed limit on SS and SF -inline bool ok_for_limit_SS_SF (int g, int j, int k, const MTL & M, - const Plates & P, const FP & pp, - const Feat & F) { - bool is_SF = M[g].SF; - bool too_many_SF = P[j].SF_in_petal[pp[k].spectrom] > F.MaxSF - 1; - bool is_SS = M[g].SS; - bool too_many_SS = P[j].SS_in_petal[pp[k].spectrom] > F.MaxSS - 1; - return !(is_SF && too_many_SF) && !(is_SS && too_many_SS); -} - -// Find, for (j,k), find the best galaxy it can reach among the possible ones -// Null list means you can take all possible kinds, otherwise you can only -// take, for the galaxy, a kind among this list -// Not allowed to take the galaxy of id no_g -inline int find_best (int j, int k, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, - const Assignment & A) { - int best = -1; - int mbest = -1; - int pbest = 0; - double subpbest = 0.; - List av_gals = P[j].av_gals[k]; - // For all available galaxies - for (size_t gg = 0; gg < av_gals.size(); gg++) { - int g = av_gals[gg]; - // if(ok_for_limit_SS_SF(g,j,k,M,P,pp,F)){//don't assign SS, SF with - // find_best 11/20/15 - if (!M[g].SS && !M[g].SF) { - // Check whether it needs further observation - int m = M[g].nobs_remain; - if (m >= 1) { - int prio = M[g].t_priority; - double subprio = M[g].subpriority; - // Takes it if better priority, or if same, if it needs more - // observations, - // so shares observations if two QSOs are close - // If still tied, use subpriority - if ( (prio > pbest) || ( (prio == pbest) && (m > mbest) ) || - ( ( prio == pbest) && ( m == mbest) && - ( subprio > subpbest) ) ) { - // Check that g is not assigned yet on this plate, or on - // the InterPlate around, check with ok_to_assign - int isa = A.is_assigned_jg(j, g, M, F); - int ok = ok_assign_g_to_jk(g, j, k, P, M, pp, F, A); - if ( (isa == -1) && ok) { - best = g; - pbest = prio; - mbest = m; - subpbest = subprio; - } - } - } - } - } - return best; -} - -// Tries to assign the fiber (j,k) -inline int assign_fiber (int j, int k, MTL & M, Plates & P, const FP & pp, - const Feat & F, - Assignment & A) { - if (A.is_assigned_tf(j, k) ) { - return -1; - } - int best = find_best(j, k, M, P, pp, F, A); - if (best != -1) { - A.assign(j, k, best, M, P, pp); - } - return best; -} - -inline int assign_galaxy (int g, MTL & M, Plates & P, const FP & pp, - const Feat & F, Assignment & A, - int jstart) { - // Tries to assign the galaxy g to one of the used plates after jstart - // jstart runs possibly to F.Nplate - int jb = -1; - int kb = -1; - int unusedb = -1; - Plist av_tfs = M[g].av_tfs; - // All the tile-fibers that can observe galaxy g - for (size_t tfs = 0; tfs < av_tfs.size(); tfs++) { - int j = av_tfs[tfs].f; - int k = av_tfs[tfs].s; - // Check if the assignment is possible, if ok, if the tf is not used - // yet, and if the plate is in the list - if ( (jstart < j) && - !A.is_assigned_tf(j, k) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) ) { - // unused fibers on this petal - int unused = A.unused[j][pp[k].spectrom]; - if (unusedb < unused) { - jb = j; - kb = k; - // observe this galaxy by fiber on petal with most free fibefs - unusedb = unused; - } - } - } - if (jb != -1) { - A.assign(jb, kb, g, M, P, pp); - return 1; - } else { - return 0; - } -} - -// Takes an unassigned fiber and tries to assign it with the "improve" -// technique described in the doc -// not used for SS or SF -inline int improve_fiber (int jused_begin, int jused, int k, MTL & M, - Plates & P, const FP & pp, const Feat & F, - Assignment & A, - int no_g = -1) { - int j = A.suborder[jused]; - if (!A.is_assigned_tf(j, k) ) { - // Unused tilefiber (j,k) - // maybe doesn't allow SS or SF - int g_try = assign_fiber(j, k, M, P, pp, F, A); - if ( (g_try != -1) && (g_try != -2) ) { - return g_try; - } else { - // Improve - int gb = -1; - int bb = -1; - int jpb = -1; - int kpb = -1; - int mb = -1; - int pb = 1e3; - int unusedb = -1; - std::vector av_g_init = P[j].av_gals[k]; - std::vector av_g; - // For all available galaxies within reach that are already - // observed - av_g = sort_by_subpriority(M, av_g_init); - for (size_t i = 0; i < av_g.size(); i++) { - // a galaxy accessible to j,k - int g = av_g[i]; - if ( (g != -1) && (g != no_g) && !M[g].SS && !M[g].SF) { - // not SS or SF - if (ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - // Which tile-fibers have taken g ? - // all tile-fibers that observe g in tiles from begin - // to end - Plist tfs = - A.chosen_tfs(g, F, A.suborder[jused_begin]); - for (size_t p = 0; p < tfs.size(); p++) { - // (jp,kp) currently assigned to galaxy g - int jp = tfs[p].f; - int kp = tfs[p].s; - - // FIND BEST JP KP !!! - // best!=g because !A.assigned_pg(best) - int best = find_best(jp, kp, M, P, pp, F, A); - if ( (best != -1) && - ( (A.is_assigned_jg(j, g, M, F) == -1) || - ( jp == j) ) ) { - int prio = M[g].t_priority; - int m = M[g].nobs_remain; - // We take the most unused - int unused = A.unused[jp][pp[kp].spectrom]; - if ( (prio > pb) || - ( (prio == pb) && (m > mb) ) || - ( ( prio == pb) && ( m == mb) && - ( unused > unusedb) ) ) { - gb = g; - bb = best; - jpb = jp; - kpb = kp; - mb = m; - pb = prio; - unusedb = unused; - } - } - } - } - } - } - // Modify assignment - if (gb != -1) { - A.unassign(jpb, kpb, gb, M, P, pp); - A.assign(j, k, gb, M, P, pp); - A.assign(jpb, kpb, bb, M, P, pp); - return gb; - } - } - } - return -1; -} - -// Assignment functions -// --------------------------------------------------------- -// Assign fibers naively -bool inverse_pairCompare (const std::pair & firstElem, - const std::pair & secondElem) { - // used to sort galaxies by subpriority - return firstElem.first > secondElem.first; -} - -void simple_assign (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A) { - Time t; - init_time(t, "# Begin simple assignment :"); - int countme = 0; - for (int j = 0; j < F.Nplate; j++) { - std::vector > pairs; - for (int k = 0; k < F.Nfiber; k++) { - List av_gals = P[j].av_gals[k]; - double Max_fiber_priority = 0.; - // loop over the potential list to find pbest and subpbest - // and then combine them to give the fiber_weight - for (size_t gg = 0; gg < av_gals.size(); gg++) { - int g = av_gals[gg]; - // not SS and SF - if (!M[g].SS && !M[g].SF) { - int m = M[g].nobs_remain; - // unobserved - if (m >= 1) { - int prio = M[g].t_priority; - double subprio = M[g].subpriority; - double fiber_priority = (double)prio + subprio; - if (fiber_priority > Max_fiber_priority) { - Max_fiber_priority = fiber_priority; - } - } - } - } - std::pair this_pair(Max_fiber_priority, k); - pairs.push_back(this_pair); - } - std::sort(pairs.begin(), pairs.end(), inverse_pairCompare); - std::vector fiber_loop_order; - for (int k = 0; k < F.Nfiber; k++) { - fiber_loop_order.push_back(pairs[k].second); - } - int best = -1; - for (int k = 0; k < F.Nfiber; k++) { - // Fiber - best = assign_fiber(j, fiber_loop_order[k], M, P, pp, F, A); - if ( ( best != -1) || ( best != -2) ) { - countme++; - } - } - } - print_time(t, "# ... took :"); - printf(" countme %d \n", countme); -} - -void improve (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A, int jused_start) { - // jstart is in list from 0 to F.NUsedplate - Time t; - init_time(t, "# Begin improve :"); - int improvements = 0; - for (int jused = jused_start; jused < F.NUsedplate; jused++) { - for (int k = 0; k < F.Nfiber; k++) { - int worked = improve_fiber(jused_start, jused, k, M, P, pp, F, A); - if (worked != -1) improvements++; - } - } - printf(" improvements %d\n", improvements); - print_time(t, "# ... took :"); -} - -// If there are galaxies discovered as fake for example, they won't be observed -// several times in the plan -// has access to G,not just M, because it needs to know the truth -void new_replace (int j, int p, MTL & M, Plates & P, const FP & pp, - const Feat & F, Assignment & A) { - // do standard stars,going through priority classes from least to most - // keep track of reassignments - int reassign_SS = 0; - int reassign_SF = 0; - int add_SS = 0; - int add_SF = 0; - // can get all available SS,SF on plate from P[j].av_gals_plate restricting - // to plate p - for (size_t c = 0; - P[j].SS_in_petal[p] < F.MaxSS && c < M.priority_list.size(); ++c ) { - // try to do this for lowest priority first - // standard stars on this petal - std::vector gals_init = P[j].SS_av_gal[p]; - std::vector gals; - // sort these by priority - gals = sort_by_subpriority(M, gals_init); - for (size_t gg = 0; gg < gals.size(); ++gg) { - // all the standard stars on this petal - // a standard star - int g = gals[gg]; - if (A.is_assigned_jg(j, g) == -1) { - // not assigned on this tile - // all tiles and fibers that reach g - Plist tfs = M[g].av_tfs; - // quit after we've used this SS - int done = 0; - std::vector could_be_replaced; - std::vector sorted_could_be_replaced; - for (size_t i = 0; i < tfs.size() && done == 0; ++i) { - // al the tile-fibers that can reach this standard star - if ( (tfs[i].f == j) && (pp[tfs[i].s].spectrom == p) ) { - // a tile fiber from this petal - // we know g can be reached by this petal of plate j - // and fiber k - int k = tfs[i].s; - // what is now at (j,k) g_old can't be -1 or we would - // have used it already in assign_sf - int g_old = A.TF[j][k]; - // require that this galaxy is used only once to keep - // things simple - if ( (g_old != -1) && !M[g_old].SS && !M[g_old].SF && - ( A.GL[g_old].size() == 1) ) { - if ( ((size_t)M[g_old].priority_class == c) && - ( A.is_assigned_jg(j, g, M, F) == -1) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - // right priority; this SS not already assigned - // on this plate - could_be_replaced.push_back(g_old); - } - } - } - } - if (could_be_replaced.size() > 0) { - // now have list of possible targets to be replaced with - // lowest priority - // use subpriority to choose - std::vector sorted_could_be_replaced = - sort_by_subpriority(M, could_be_replaced); - int g_chosen = sorted_could_be_replaced[0]; - int j = A.GL[g_chosen][0].f; - int k = A.GL[g_chosen][0].s; - A.unassign(j, k, g_chosen, M, P, pp); - // try to assign, increment counter - reassign_SS += assign_galaxy(g_chosen, M, P, pp, F, A, j); - A.assign(j, k, g, M, P, pp); - add_SS++; - done = 1; - } - } - } - } - for (size_t c = 0; - P[j].SF_in_petal[p] < F.MaxSF && c < M.priority_list.size(); ++c ) { - // try to do this for lowest priority - // sky fibers on this petak - std::vector gals_init = P[j].SF_av_gal[p]; - // sort these by subpriority - std::vector > galaxy_pairs; - for (size_t gg = 0; gg < gals_init.size(); ++gg) { - int g = gals_init[gg]; - std::pair this_pair (M[g].subpriority, g); - galaxy_pairs.push_back(this_pair); - } - std::sort(galaxy_pairs.begin(), galaxy_pairs.end(), pairCompare); - std::vector gals; - for (size_t gg = 0; gg < gals_init.size(); ++gg) { - gals.push_back(galaxy_pairs[gg].second); - } - for (size_t gg = 0; gg < gals.size(); ++gg) { - int g = gals[gg]; // a sky fiber - if (A.is_assigned_jg(j, g) == -1) { - Plist tfs = M[g].av_tfs; - int done = 0; - std::vector could_be_replaced; - for (size_t i = 0; i < tfs.size() && done == 0; ++i) { - if ( (tfs[i].f == j) && (pp[tfs[i].s].spectrom == p) ) { - // g is accesible to j,k - // we know g can be reached by this petal of plate j - // and fiber k - int k = tfs[i].s; - // what is now at (j,k) - int g_old = A.TF[j][k]; - if ( (g_old != -1) && !M[g_old].SS && !M[g_old].SF && - ( A.GL[g_old].size() == 1) ) { - if ( ((size_t)M[g_old].priority_class == c) && - ( A.is_assigned_jg(j, g, M, F) == -1) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - could_be_replaced.push_back(g_old); - } - } - } - } - // now have list of possible targets to be replaced with lowest - // priority - // use subpriority to choose - sort_by_subpriority(M, could_be_replaced); - if (could_be_replaced.size() > 0) { - int g_chosen = could_be_replaced[0]; - int j = A.GL[g_chosen][0].f; - int k = A.GL[g_chosen][0].s; - A.unassign(j, k, g_chosen, M, P, pp); - // try to assign - reassign_SF += assign_galaxy(g_chosen, M, P, pp, F, A, j); - A.assign(j, k, g, M, P, pp); - add_SF++; - done = 1; - } - } - } - } -} - -void assign_unused (int j, MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A) { - // Tries to assign remaining fibers in tile jth tile with galaxies on it - // even taking objects observed later - // js is a tile with galaxies on it - for (int k = 0; k < F.Nfiber; k++) { - if (!A.is_assigned_tf(j, k) ) { - int best = -1; - int mbest = -1; - int pbest = 0; - int jpb = -1; - int kpb = -1; - double subpbest = 0; - // all available galaxies for this fiber k - std::vector av_gals = P[j].av_gals[k]; - std::vector sorted_av_gals = sort_by_subpriority(M, av_gals); - for (size_t gg = 0; gg < sorted_av_gals.size(); gg++) { - // available galaxies - int g = sorted_av_gals[gg]; - int m = M[g].nobs_remain; - int prio = M[g].t_priority; - double subprio = M[g].subpriority; - if ( (prio > pbest) || ( (prio == pbest) && (m > mbest) ) || - ( ( prio == pbest) && ( m == mbest) && - ( subprio > subpbest) ) ) { - if ( (A.is_assigned_jg(j, g, M, F) == -1) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) ) { - // not assigned this plate or within excluded interval - for (size_t i = 0; i < A.GL[g].size(); i++) { - // GL[g].size() is number of tf that could observe - // g - int jp = A.GL[g][i].f; - int kp = A.GL[g][i].s; - if ( (j < jp) && (jpb < jp) ) { - // take best opportunity - best = g; - pbest = prio; - mbest = m; - subpbest = subprio; - jpb = jp; - kpb = kp; - } - } - } - } - } - if (best != -1) { - A.unassign(jpb, kpb, best, M, P, pp); - A.assign(j, k, best, M, P, pp); - } - } - } -} - -void assign_sf_ss (int j, MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A) { - // assigns sky fibers and standard stars to unused fibers - for (int ppet = 0; ppet < F.Npetal; ppet++) { - // for each petal - int p = ppet; - std::vector SS_av_init = P[j].SS_av_gal[p]; - std::vector SS_av; - SS_av = sort_by_subpriority(M, SS_av_init); - // use subpriority to order SS, SF - std::vector SF_av_init = P[j].SF_av_gal[p]; - std::vector SF_av; - SF_av = sort_by_subpriority(M, SF_av_init); - if ( (SS_av.size() > 0) || (SF_av.size() > 0) ) { - // look at fibers on this petal - for (int kk = 0; kk < F.Nfbp; kk++) { - int k = pp.fibers_of_sp[p][kk]; - // for a particular fiber on this petal consider SS and SF by - // subpriority order - std::vector SS_av_k_init = P[j].SS_av_gal_fiber[k]; - std::vector SF_av_k_init = P[j].SF_av_gal_fiber[k]; - std::vector SS_av_k; - std::vector SF_av_k; - SS_av_k = sort_by_subpriority(M, SS_av_k_init); - SF_av_k = sort_by_subpriority(M, SF_av_k_init); - if (A.TF[j][k] == -1) { - // this fiber isn't assigned yet - int done = 0; - for (size_t gg = 0; gg < SS_av_k.size() && done == 0; gg++) { - // SS on this with reach of this fiber - int g = SS_av_k[gg]; - // if g isn't already assigned on this fiber and we - // still need it and it's ok to assign, then assign - if ( (A.is_assigned_jg(j, g, M, F) == -1) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - A.assign(j, k, g, M, P, pp); - done = 1; - } - } - for (size_t gg = 0; gg < SF_av_k.size() - && done == 0; gg++) { - // SF on this petal - int g = SF_av_k[gg]; - if ( (A.is_assigned_jg(j, g, M, F) == -1) && - ok_for_limit_SS_SF(g, j, k, M, P, pp, F) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - A.assign(j, k, g, M, P, pp); - done = 1; - } - } - } - } - new_replace(j, p, M, P, pp, F, A); - } - } -} - -void fill_unused_with_sf (int j, MTL & M, Plates & P, const FP & pp, - const Feat & F, Assignment & A) { - // assigns sky fibers to fill all unused fibers - for (int ppet = 0; ppet < F.Npetal; ppet++) { - // for each petal - int p = ppet; - // use subpriority to order SF (Sky Fiber) - std::vector SF_av_init = P[j].SF_av_gal[p]; - std::vector SF_av; - SF_av = sort_by_subpriority(M, SF_av_init); - if (SF_av.size() > 0) { - // look at fibers on this petal - for (int kk = 0; kk < F.Nfbp; kk++) { - int k = pp.fibers_of_sp[p][kk]; - // for a particular fiber on this petal consider SF by - // subpriority order - std::vector SF_av_k_init = P[j].SF_av_gal_fiber[k]; - std::vector SF_av_k; - SF_av_k = sort_by_subpriority(M, SF_av_k_init); - if (A.TF[j][k] == -1) { - // this fiber isn't assigned yet - int done = 0; - for (size_t gg = 0; gg < SF_av_k.size() - && done == 0; gg++) { - // SF on this petal - int g = SF_av_k[gg]; - if ( (A.is_assigned_jg(j, g, M, F) == -1) && - ok_assign_g_to_jk(g, j, k, P, M, pp, F, A) ) { - A.assign(j, k, g, M, P, pp); - done = 1; - } - } - } - } - new_replace(j, p, M, P, pp, F, A); - } - } -} - -void redistribute_tf (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A, int jused_start) { - // diagnostic - printf("start redistribute \n"); - Time t; - init_time(t, "# Begin redistribute TF :"); - int red(0); - // consider every occupied plate and every fiber - Table Done = initTable(F.NUsedplate, F.Nfiber); - for (int jused = jused_start; jused < F.NUsedplate; jused++) { - int j = A.suborder[jused]; - for (int k = 0; k < F.Nfiber; k++) { - if (Done[jused][k] == 0) { - // current assignment of (j,k) only look if assigned - int g = A.TF[j][k]; - if ( (g != -1) && !M[g].SS && !M[g].SF) { - int jpb = -1; - int kpb = -1; - int unusedb = A.unused[j][pp[k].spectrom]; - // all possible tile fibers for this galaxy - Plist av_tfs = M[g].av_tfs; - for (size_t i = 0; i < av_tfs.size(); i++) { - int jp = av_tfs[i].f; - int kp = av_tfs[i].s; - // unused for jp, spectrom[kp] - int unused = A.unused[jp][pp[kp].spectrom]; - if (A.inv_order[jp] != -1) { - // necessary because underdense targets may leave - // some plates unused - if ( ( A.inv_order[jp] > F.NUsedplate) || - ( A.inv_order[jp] < 0) ) { - printf("**out range %d\n", A.inv_order[jp]); - } - if (A.suborder[jused_start] <= jp) { - if (!A.is_assigned_tf(jp, kp) ) { - if (Done[A.inv_order[jp]][kp] == 0) { - if ( ok_assign_g_to_jk(g, jp, kp, P, M, - pp, F, A) ) { - if (A.is_assigned_jg(jp, g, M, F) - == -1) { - if ( 0 < unused) { - if (unusedb < unused) { - // Takes the most - // unused petal - jpb = jp; - kpb = kp; - unusedb = unused; - } - } - } - } - } - } - } - } - } - if (jpb != -1) { - A.unassign(j, k, g, M, P, pp); - A.assign(jpb, kpb, g, M, P, pp); - Done[A.inv_order[j]][k] = 1; - Done[A.inv_order[jpb]][kpb] = 1; - red++; - } - } - } - } - } - printf(" %s redistributions of tile-fibers \n", f(red).c_str() ); - print_time(t, "# ... took :"); -} - -void fa_write (int j, str outdir, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, const Assignment & A) { - // generate a quiet NaN to use for invalid entries. We cannot - // guarantee that we have C++11, so we can't use the nice functions - // included in that standard... - // const unsigned long maxU = ~0; - // const double qNan = *((double*)&maxU); - // double qNan = nan(""); - double testra, testdec; - double arcsec = 1.0 / 3600.0; - // constants for the filename length and fixed object - // type length - size_t cfilesize = 512; - //size_t objtypelen = 8; - size_t bricklen = 8; - // check if the file exists, and if so, throw an exception - char filename[cfilesize]; - int ret = snprintf(filename, cfilesize, "%s/tile_%05d.fits", - outdir.c_str(), P[j].tileid); - struct stat filestat; - ret = ::stat(filename, &filestat ); - if (ret == 0) { - std::cerr << "ERROR: output file " << filename << " already exists" - << std::endl; - std::exit(1); - // std::ostringstream o; - // o << "output file " << filename << " already exists"; - // throw std::runtime_error(o.str().c_str()); - } - // create the file - int status = 0; - fitsfile * fptr; - fits_create_file (&fptr, filename, &status); - fits_report_error (stderr, status); - // Set up the schema for the table. We explicitly malloc these - // string arrays, since the CFITSIO API requires non-const pointers - // to them (i.e. arrays of literals won't work). - size_t ncols = 14; - char * * ttype; - char * * tform; - char * * tunit; - ttype = (char * *) malloc ( ncols * sizeof(char *) ); - tform = (char * *) malloc ( ncols * sizeof(char *) ); - tunit = (char * *) malloc ( ncols * sizeof(char *) ); - if ( !( ttype && tform && tunit ) ) { - std::ostringstream o; - o << "cannot allocate column info for binary table"; - throw std::runtime_error(o.str().c_str() ); - } - for ( size_t c = 0; c < ncols; ++c ) { - ttype[c] = (char *) malloc ( FLEN_VALUE * sizeof(char) ); - tform[c] = (char *) malloc ( FLEN_VALUE * sizeof(char) ); - tunit[c] = (char *) malloc ( FLEN_VALUE * sizeof(char) ); - if ( !( ttype[c] && tform[c] && tunit[c] ) ) { - std::ostringstream o; - o << "cannot allocate column info for binary table"; - throw std::runtime_error(o.str().c_str() ); - } - } - strcpy(ttype[0], "FIBER"); - strcpy(tform[0], "J"); - strcpy(tunit[0], ""); - strcpy(ttype[1], "LOCATION"); - strcpy(tform[1], "J"); - strcpy(tunit[1], ""); - strcpy(ttype[2], "NUMTARGET"); - strcpy(tform[2], "I"); // int not long - strcpy(tunit[2], ""); - strcpy(ttype[3], "PRIORITY"); - strcpy(tform[3], "J"); - strcpy(tunit[3], ""); - strcpy(ttype[4], "TARGETID"); - strcpy(tform[4], "K"); - strcpy(tunit[4], ""); - strcpy(ttype[5], "DESI_TARGET"); - strcpy(tform[5], "K"); - strcpy(tunit[5], ""); - strcpy(ttype[6], "BGS_TARGET"); - strcpy(tform[6], "K"); - strcpy(tunit[6], ""); - strcpy(ttype[7], "MWS_TARGET"); - strcpy(tform[7], "K"); - strcpy(tunit[7], ""); - strcpy(ttype[8], "RA"); - strcpy(tform[8], "D"); - strcpy(tunit[8], "deg"); - strcpy(ttype[9], "DEC"); - strcpy(tform[9], "D"); - strcpy(tunit[9], "deg"); - strcpy(ttype[10], "XFOCAL_DESIGN"); - strcpy(tform[10], "E"); - strcpy(tunit[10], "mm"); - strcpy(ttype[11], "YFOCAL_DESIGN"); - strcpy(tform[11], "E"); - strcpy(tunit[11], "mm"); - strcpy(ttype[12], "BRICKNAME"); - snprintf(tform[12], FLEN_VALUE, "%dA", (int)bricklen); - strcpy(tunit[12], ""); - strcpy(ttype[13], "FIBERMASK"); - strcpy(tform[13], "J"); - strcpy(tunit[13], ""); - char extname[FLEN_VALUE]; - strcpy(extname, "FIBER_ASSIGNMENTS"); - // create the table with the full size on disk. - ret = fits_create_tbl(fptr, BINARY_TBL, F.Nfiber, ncols, ttype, tform, - tunit, extname, &status); - fits_report_error(stderr, status); - int tileid = P[j].tileid; - double tilera = P[j].tilera; - double tiledec = P[j].tiledec; - fits_write_key(fptr, TINT, "TILEID", &(tileid), "Tile ID number", &status); - fits_report_error(stderr, status); - fits_write_key(fptr, TDOUBLE, "TILERA", &(tilera), "Tile RA [deg]", - &status); - fits_report_error(stderr, status); - fits_write_key(fptr, TDOUBLE, "TILEDEC", &(tiledec), "Tile DEC [deg]", - &status); - fits_report_error(stderr, status); - // get the number of rows to write for each internal FITS buffer. - long optimal; - ret = fits_get_rowsize(fptr, &optimal, &status); - fits_report_error(stderr, status); - // initialize arrays to the optimal number of rows for writing. - //int tile_id[optimal]; - int fiber_id[optimal]; - int positioner_id[optimal]; - int num_target[optimal]; - int fibermask[optimal]; - //char objtype[optimal][objtypelen]; - char brickname[optimal][bricklen + 1]; - char * bn_tmp[optimal]; - //char * ot_tmp[optimal]; - for (int i = 0; i < optimal; i++) { - //ot_tmp[i] = objtype[i]; - bn_tmp[i] = brickname[i]; - } - long long target_id[optimal]; - long long desi_target[optimal]; - long long bgs_target[optimal]; - long long mws_target[optimal]; - double ra[optimal]; - double dec[optimal]; - double x_focal[optimal]; - double y_focal[optimal]; - // new - int t_priority[optimal]; - std::vector potentialtargetid; - long long offset = 0; - long long n = optimal; - while ( n == optimal ) { - if ( offset + optimal > F.Nfiber ) { - n = F.Nfiber - offset; - } - if ( n > 0 ) { - for (long long i = 0; i < n; ++i) { - long long fib = offset + i; - int g = A.TF[j][fib]; - fiber_id[i] = fib; - positioner_id[i] = pp[fib].location; - num_target[i] = P[j].av_gals[fib].size(); - // target_id[i] = g; ******** - if (g > 0) { - target_id[i] = M[g].id; - } else { - target_id[i] = -1; - } - if (g < 0) { - // For negative target ID, must still initialize - // memory buffer that will be written - t_priority[i] = 1; - - if (pp[fib].stuck) { - fibermask[i] = FIBER_STUCK; - x_focal[i] = pp[fib].fp_x; - y_focal[i] = pp[fib].fp_y; - xy2radec(&(ra[i]), &(dec[i]), tilera, tiledec, - x_focal[i], y_focal[i]); - desi_target[i] = 0; - bgs_target[i] = 0; - mws_target[i] = 0; - strncpy(brickname[i], "notbrick", bricklen + 1); - } else if (pp[fib].broken) { - fibermask[i] = FIBER_BROKEN; - x_focal[i] = pp[fib].fp_x; - y_focal[i] = pp[fib].fp_y; - xy2radec(&(ra[i]), &(dec[i]), tilera, tiledec, - x_focal[i], y_focal[i]); - desi_target[i] = 0; - bgs_target[i] = 0; - mws_target[i] = 0; - strncpy(brickname[i], "notbrick", bricklen + 1); - } else { - fibermask[i] = FIBER_UNUSED; - x_focal[i] = pp[fib].fp_x; - y_focal[i] = pp[fib].fp_y; - xy2radec(&(ra[i]), &(dec[i]), tilera, tiledec, - x_focal[i], y_focal[i]); - desi_target[i] = 0; - bgs_target[i] = 0; - mws_target[i] = 0; - strncpy(brickname[i], "notbrick", bricklen + 1); - } - } else { - // we aren't supposed to know the kind use priority - // instead - // strncpy(objtype[i], F.kind[G[g].id].c_str(), - // objtypelen); - fibermask[i] = FIBER_USED; - ra[i] = M[g].ra; - dec[i] = M[g].dec; - dpair proj = projection(g, j, M, P); - x_focal[i] = proj.f; - y_focal[i] = proj.s; - // testing that xy2radec is working with good precision. - xy2radec(&testra, &testdec, tilera, tiledec, x_focal[i], - y_focal[i]); - double dra = - (testra * cos(testdec * M_PI / 180.0) - ra[i] * - cos(dec[i] * M_PI / 180.0) ) / arcsec; - double ddec = (testdec - dec[i]) / arcsec; - if (fabs(dra) > 0.01) { - // arcsecond precision - fprintf(stderr, - "problem with xy2radec conversion [dRA (arcsec)]: %f\n", - dra); - fprintf(stderr, "[dDEC (arcsec)]: %f \n", ddec); - myexit(1); - } - if (fabs(ddec) > 0.01) { - // arcsecond precision - fprintf(stderr, - "problem with xy2radec conversion [dDEC]: %f\n", - ddec); - fprintf(stderr, "[dRA]: %f\n", dra); - myexit(1); - } - t_priority[i] = M[g].t_priority; // new - desi_target[i] = M[g].desi_target; - bgs_target[i] = M[g].bgs_target; - mws_target[i] = M[g].mws_target; - strncpy(brickname[i], M[g].brickname, bricklen + 1); - } - // Store the potential targetids accesible to this fibre (the - // actual targetid, not the index). - for (size_t k = 0; k < P[j].av_gals[fib].size(); ++k) { - // MTL index for k'th target accessible to this fibre - int gal_idx = P[j].av_gals[fib][k]; - if (gal_idx >= 0) { - potentialtargetid.push_back(M[gal_idx].id); - } - } - } - fits_write_col(fptr, TINT, 1, offset + 1, 1, n, fiber_id, &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TINT, 2, offset + 1, 1, n, positioner_id, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TINT, 3, offset + 1, 1, n, num_target, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TINT, 4, offset + 1, 1, n, t_priority, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TLONGLONG, 5, offset + 1, 1, n, target_id, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TLONGLONG, 6, offset + 1, 1, n, desi_target, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TLONGLONG, 7, offset + 1, 1, n, bgs_target, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TLONGLONG, 8, offset + 1, 1, n, mws_target, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TDOUBLE, 9, offset + 1, 1, n, ra, &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TDOUBLE, 10, offset + 1, 1, n, dec, &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TDOUBLE, 11, offset + 1, 1, n, x_focal, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TDOUBLE, 12, offset + 1, 1, n, y_focal, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TSTRING, 13, offset + 1, 1, n, bn_tmp, - &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TINT, 14, offset + 1, 1, n, fibermask, - &status); - fits_report_error(stderr, status); - } - offset += n; - } - // PotentialFiberMap table. We have only one column, so it is safe - // from a performance perspective to write the whole thing. - // NO 12/15/16 - strcpy(ttype[0], "POTENTIALTARGETID"); - strcpy(tform[0], "K"); - strcpy(tunit[0], ""); - strcpy(extname, "POTENTIAL_ASSIGNMENTS"); - ret = fits_create_tbl(fptr, BINARY_TBL, - potentialtargetid.size(), 1, ttype, tform, tunit, extname, &status); - fits_report_error(stderr, status); - fits_write_col(fptr, TLONGLONG, 1, 1, 1, potentialtargetid.size(), - &(potentialtargetid[0]), &status); - fits_report_error(stderr, status); - fits_close_file(fptr, &status); - fits_report_error(stderr, status); - for ( size_t c = 0; c < ncols; ++c ) { - free ( ttype[c] ); - free ( tform[c] ); - free ( tunit[c] ); - } - free ( ttype ); - free ( tform ); - free ( tunit ); - return; -} diff --git a/old/src/global.h b/old/src/global.h deleted file mode 100644 index 611c4375..00000000 --- a/old/src/global.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef GLOBAL_H -#define GLOBAL_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" -#include "feat.h" -#include "structs.h" - -#define FIBER_BROKEN 4 -#define FIBER_STUCK 2 -#define FIBER_UNUSED 1 -#define FIBER_USED 0 - -// Collect ----------------------------------------------------------- -// From the HTM tree, collects for each fiber and for each plate, the available -// galaxies -void collect_galaxies_for_all (const MTL & M, - const htmTree & T, Plates & P, - const FP & pp, const Feat & F); - -// From the previous computations, computes the inverse map, that is to say, -// for each target, computes the tile-fibers which can reach it -void collect_available_tilefibers (MTL & M, const Plates & P, const Feat & F); - -// Assignment functions ---------------------------------------------- -// First simple assignment plan, executing find_best on every plate on every -// fiber -void simple_assign (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A); - -// More fine first assignment plan, -void improve (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A, int jstart); - -void improve_from_kind (MTL & M, const Plates & P, const FP & pp, - const Feat & F, Assignment & A, str kind, - int next = -1); - -void update_plan_from_one_obs (int j, const Gals & G, MTL & M, Plates & P, - const FP & pp, const Feat & F, Assignment & A); - -// void redistribute_tf(MTL& M, Plates&P, const FP& pp, const Feat& F, -// Assignment& A, int next=-1); -void redistribute_tf (MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A, int jstart); - -void assign_sf_ss (int j, MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A); - -void fill_unused_with_sf (int j, MTL & M, Plates & P, const FP & pp, - const Feat & F, Assignment & A); - -void assign_unused (int j, MTL & M, Plates & P, const FP & pp, const Feat & F, - Assignment & A); - -void diagnostic (const Gals & G, Feat & F, const Assignment & A); - -// Results functions -------------------------------------------------- - -void diagnostic (const MTL & M, const Gals & G, Feat & F, - const Assignment & A); - -void write_FAtile_ascii (int j, str outdir, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, const Assignment & A); - -void fa_write (int j, str outdir, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, const Assignment & A); - -void write_save_av_gals (int j, str outdir, const MTL & M, const Plates & P, - const FP & pp, const Feat & F); - -void overlappingTiles (str fname, const Feat & F, const Assignment & A); - -bool myorder (int i, int j); - - -#endif diff --git a/old/src/misc.cpp b/old/src/misc.cpp deleted file mode 100644 index 567d2dc1..00000000 --- a/old/src/misc.cpp +++ /dev/null @@ -1,1264 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" - -// pair ------------------------------------------------------ -pair::pair () { - f = -1; - s = -1; -} - -pair::pair (int a, int b) { - f = a; - s = b; -} - -void pair::setnull () { - f = -1; - s = -1; -} - -bool pair::isnull () const { - if ( (f == -1) && (s == -1) ) { - return true; - } - return false; -} - -void pair::print_pair () const { - printf("(%d,%d) ", f, s); - fl(); -} - -// dpair ------------------------------------------------------ -dpair::dpair () { - f = 0; - s = 0; -} - -dpair::dpair (double a, double b) { - f = a; - s = b; -} - -dpair operator+ (dpair const & a, dpair const & b) { - return dpair(a.f + b.f, a.s + b.s); -} - -dpair operator- (dpair const & a, dpair const & b) { - return dpair(a.f - b.f, a.s - b.s); -} - -dpair operator- (dpair const & a, double b) { - return dpair(a.f - b, a.s - b); -} - -void dpair::print () const { - printf("(%f,%f) ", f, s); - fl(); -} - -bool dpair::isnull () const { - if ( (f == 0) && (s == 0) ) { - return true; - } - return false; -} - -dpair cartesian (double r, double theta) { - return dpair(r * cos(theta), r * sin(theta) ); -} - -dpair cartesian (dpair X) { - return dpair(X.f * cos(X.s), X.f * sin(X.s) ); -} - -dpair sum_angles (dpair t, dpair a) { - return dpair(t.f * a.f - t.s * a.s, t.s * a.f + t.f * a.s); -} - -dpair cos_sin_angle (dpair P) { - double r_inv = 1 / norm(P); - return dpair(P.f * r_inv, P.s * r_inv); -} - -double dist (dpair c1, dpair c2) { - return norm(c1.f - c2.f, c1.s - c2.s); -} - -double sq (dpair p) { - return p.f * p.f + p.s * p.s; -} - -double sq (dpair p, dpair q) { - return sq(p.f - q.f) + sq(p.s - q.s); -} - -double scalar_prod (dpair p, dpair q, dpair d) { - return (q.f - p.f) * (d.f - p.f) + (q.s - p.s) * (d.s - p.s); -} - -// List ------------------------------------------------------ - -List Null () { - List L; - return L; -} - -Slist Snull () { - Slist L; - return L; -} - -List initList (int l, int val) { - List L; - L.resize(l, val); - return L; -} - -List initList (std::vector l) { - int n(l.size() ); - List L; - L.resize(n); - for (int i = 0; i < n; i++) { - L[i] = l[i]; - } - return L; -} - -List initList (int l[], int size) { - List L; - L.resize(size); - for (int i = 0; i < size; i++) { - L[i] = l[i]; - } - return L; -} - -Dlist initDlist (int l, double val) { - Dlist L; - L.resize(l, val); - return L; -} - -Slist initList (str l[], int size) { - Slist L; - L.resize(size); - for (int i = 0; i < size; i++) { - L[i] = l[i]; - } - return L; -} - -void print_list (str s, const List & L) { - printf("%s \n", s.c_str() ); - int n = L.size(); - // if (n==0) { // doesn't want to be compiled... mystery - // printf(" ! Empty list\n"); - // return; - // } - for (int i = 0; i < n; i++) { - printf("%5d : %s \n", i, f(L[i]).c_str() ); - } - printf("\n"); -} - -void print_list (str s, Slist L) { - printf("%s \n", s.c_str() ); - int n = L.size(); - // if (n==0) { // doesn't want to be compiled... mystery - // printf(" ! Empty list\n"); - // return; - // } - for (int i = 0; i < n; i++) { - printf("%5d : %s \n", i, L[i].c_str() ); - } - printf("\n"); -} - -void print_list_line (const List & L) { - printf("("); - for (size_t i = 0; i < L.size(); i++) { - str s = (i == L.size() - 1) ? "" : ","; - printf("%d%s", L[i], s.c_str() ); - } - printf(") "); - std::cout.flush(); -} - -void print_Dlist (str s, const Dlist & L) { - printf("%s \n", s.c_str() ); - int n = L.size(); - for (int i = 0; i < n; i++) { - printf("%5d : %.3f\n", i, L[i]); - } - printf("\n"); -} - -void print_Plist (const Plist & L, str s) { - printf("%s \n", s.c_str() ); - int n = L.size(); - for (int i = 0; i < n; i++) { - printf("%5d : (%d,%d)\n", i, L[i].f, L[i].s); - } - printf("\n"); -} - -bool isnull (const List & L) { - // Test if the list is null - for (size_t i = 0; i < L.size(); i++) { - if (L[i] != 0) { - return false; - } - } - return true; -} - -bool isnull (const Slist & L) { - for (size_t i = 0; i < L.size(); i++) { - if (L[i] != "") { - return false; - } - } - return true; -} - -int sumlist (const List & L) { - // Sum of the list - int s(0); - for (size_t i = 0; i < L.size(); i++) { - s += L[i]; - } - return s; -} - -double sumlist (const Dlist & L) { - double d = 0; - for (size_t l = 0; l < L.size(); l++) { - d += L[l]; - } - return d; -} - -int max (const List & L) { - int m(-1e8); - for (size_t i = 0; i < L.size(); i++) { - if (L[i] > m) { - m = L[i]; - } - } - return m; -} - -Dlist percents (const List & L, int n) { - Dlist Dl; - for (size_t i = 0; i < L.size(); i++) { - Dl.push_back(percent(L[i], n) ); - } - return Dl; -} - -Dlist percents (const Dlist & L, double n) { - Dlist Dl; - for (size_t i = 0; i < L.size(); i++) { - Dl.push_back(percent(L[i], n) ); - } - return Dl; -} - -bool isfound (int n, const List & L) { - if (L.size() == 0) { - return false; - } - for (size_t i = 0; i < L.size(); i++) { - if (L[i] == n) { - return true; - } - } - return false; -} - -int isfound_pos (double n, const Dlist & L) { - if (L.size() == 0) { - return -1; - } - for (size_t i = 0; i < L.size(); i++) { - if (L[i] == n) { - return i; - } - } - return -1; -} - -int isfound (pair p, const Plist & L) { - int j = p.f; - int k = p.s; - if (L.size() == 0) { - return -1; - } - for (size_t i = 0; i < L.size(); i++) { - if ( ( L[i].f == j) && ( L[i].s == k) ) { - return i; - } - } - return -1; -} - -bool isfound (str n, const Slist & L) { - if (L.size() == 0) { - return false; - } - for (size_t i = 0; i < L.size(); i++) { - if (L[i] == n) { - return true; - } - } - return false; -} - -List values (const List & L) { - List l; - for (size_t i = 0; i < L.size(); i++) { - int n = L[i]; - if (!isfound(n, l) ) { - l.push_back(n); - } - } - return l; -} - -void print_hist (str s, int i0, List hist, bool latex) { - str et = latex ? " & " : " | "; - str slash = latex ? "\\\\ \n" : "\n"; - str rrr(10, 'r'); - if (latex) { - printf( - "\\begin{table}[H]\\begin{center} \n \\caption{%s (interval %d)} \n \\begin{tabular}{%s}\n", - s.c_str(), i0, rrr.c_str() ); - } else { - printf("%s (interval %d)\n", s.c_str(), i0); - } - size_t size = hist.size(); - for (size_t i = 0; i < size; i++) { - str s = ( (i + 1) % 10 == 0 || i == size - 1) ? slash : et; - printf("%4s %s", f(hist[i]).c_str(), s.c_str() ); - } - if (latex) { - printf("\\end{tabular}\\end{center}\\end{table} \n"); - } - fl(); -} - -void print_mult_table_latex (str s, str ss, Table T, int multX) { - printf("# %s \n Output data in %s \n\n", s.c_str(), ss.c_str() ); - FILE * pFile; - pFile = fopen(ss.c_str(), "w"); - if (!pFile) { - printf("File opening failed \n"); - fl(); - myexit(1); - } - fprintf(pFile, "x "); - for (size_t i = 0; i < T.size(); i++) { - fprintf(pFile, "%lu ", i); - } - fprintf(pFile, "\n"); - size_t maxrow = max_row(T); - for (size_t j = 0; j < maxrow; j++) { - fprintf(pFile, "%d ", (int)j * multX); - for (size_t i = 0; i < T.size(); i++) { - if (j < T[i].size() ) { - fprintf(pFile, "%d ", T[i][j]); - } else { - fprintf(pFile, "0 "); - } - } - fprintf(pFile, "\n"); - } - fclose(pFile); -} - -void print_mult_Dtable_latex (str s, str ss, Dtable T, double multX) { - printf("# %s \n Output data in %s \n\n", s.c_str(), ss.c_str() ); - FILE * pFile; - pFile = fopen(ss.c_str(), "w"); - if (!pFile) { - printf("File opening failed \n"); - fl(); - myexit(1); - } - fprintf(pFile, "x "); - for (size_t i = 0; i < T.size(); i++) { - fprintf(pFile, "%lu ", i); - } - fprintf(pFile, "\n"); - size_t maxrow = max_row(T); - for (size_t j = 0; j < maxrow; j++) { - fprintf(pFile, "%f ", (double)j * multX); - for (size_t i = 0; i < T.size(); i++) { - if (j < T[i].size() ) { - fprintf(pFile, "%f ", T[i][j]); - } else { - fprintf(pFile, "0 "); - } - } - fprintf(pFile, "\n"); - } - fclose(pFile); -} - -void erase (int i, List & L) { - L.erase (L.begin() + i); -} - -void erase (int i, Plist & L) { - L.erase (L.begin() + i); -} - -List complementary (int size, const List & L) { - List l = initList(size); - for (int i = 0; i < size; i++) { - l.push_back(i); - } - for (size_t i = 0; i < L.size(); i++) { - erase(L[i], l); - } - return l; -} - -List sublist (int begin, int size, const List & L) { - List l = initList(size); - for (int i = 0; i < size; i++) { - l[i] = L[begin + i]; - } - return l; -} - -void switch_elmts (int a, int b, List & L) { - if ( (L.size() <= (size_t)a) || (L.size() <= (size_t)b) ) { - printf("Error in switch elmts\n"); - fl(); - } - int tmp = L[a]; - L[a] = L[b]; - L[b] = tmp; -} - -List sort (const List & L) { - List l = L; - std::sort(l.begin(), l.end() ); - return l; -} - -List inverse (const List & L) { - List l = initList(max(L) + 1); - for (size_t i = 0; i < L.size(); i++) { - l[L[i]] = i; - } - return l; -} - -List cumulate (const List & L) { - List l = initList(L.size() ); - int a = 0; - for (size_t i = 0; i < L.size(); i++) { - a += L[i]; - l[i] = a; - } - return l; -} - -Dlist cumulate (const Dlist & L) { - Dlist l = initDlist(L.size() ); - double a = 0; - for (size_t i = 0; i < L.size(); i++) { - a += L[i]; - l[i] = a; - } - return l; -} - -Dlist division (const Dlist & L, double d) { - Dlist Dl; - for (size_t i = 0; i < L.size(); i++) { - Dl.push_back(L[i] / d); - } - return Dl; -} - -void addlist (List & L, const List & l) { - for (size_t i = 0; i < l.size(); i++) { - L.push_back(l[i]); - } -} - -// Table ----------------------------------------------------- -Table initTable (int l, int c, int val) { - Table T; - T.resize(l); - for (int i = 0; i < l; i++) { - T[i].resize(c, val); - } - return T; -} - -Ptable initPtable (int l, int c) { - Ptable T; - T.resize(l); - for (int i = 0; i < l; i++) { - T[i].resize(c, pair() ); - } - return T; -} - -Dtable initDtable (int l, int c, double val) { - Dtable T; - T.resize(l); - for (int i = 0; i < l; i++) { - T[i].resize(c, val); - } - return T; -} - -void verif (const Table & T) { - size_t l = T.size(); - if (l == 0) { - printf(" ! Empty table\n"); - return; - } - size_t c = T[0].size(); - for (size_t i = 0; i < l; i++) { - if (T[i].size() != c) { - printf( - " ! Table has different number of columns depending to the lines\n"); - return; - } - } -} - -size_t max_row (const Table & T) { - size_t max(0); - for (size_t i = 0; i < T.size(); i++) { - size_t c = T[i].size(); - if (c > max) { - max = c; - } - } - return max; -} - -size_t max_row (const Dtable & T) { - size_t max(0); - for (size_t i = 0; i < T.size(); i++) { - size_t c = T[i].size(); - if (c > max) { - max = c; - } - } - return max; -} - -void print_table (str s, const Table & T, bool latex, - Slist labels) { - //size_t SIZE = 7; - size_t MAXSIZE = 10; - size_t MAXLINE = 50; - size_t STANDARDSIZE = 1; - bool square(true); - size_t l = T.size(); - if (MAXLINE < l) { - printf( - "Caution, table is of size %lu, only %lu will be displayed \n", l, - MAXLINE); - } - size_t cc = T[0].size(); - for (size_t i = 0; i < l; i++) { - if (T[i].size() != cc) { - square = false; - } - } - size_t max = max_row(T); - List maxRow = initList(max); - if (square) { - Table sizestr = initTable(l, max); - for (size_t i = 0; i < l; i++) { - for (size_t j = 0; j < max; j++) { - size_t sz = f(T[i][j]).size() + 1; - sizestr[i][j] = sz < MAXSIZE ? sz : MAXSIZE; - } - } - maxRow = max_on_row(sizestr); - } else { - maxRow = initList(max, STANDARDSIZE); - } - str et = latex ? " &" : "|"; - str slash = latex ? " \\\\ \n" : "\n"; - str rrr(T[0].size(), 'r'); - printf("%s", s.c_str() ); - printf("\n"); - bool labelsB = isnull(labels); - str space(6, ' '); - printf("%s", space.c_str() ); - for (size_t j = 0; j < max; j++) { - str s = (j == max - 1) ? slash : et; - printf("%s%s", format(maxRow[j], f((int)j) ).c_str(), s.c_str() ); - } - for (size_t i = 0; i < l && i < MAXLINE; i++) { - str pre = labelsB ? f((int)i) : format(11, labels[i]); - printf("%3s %s", pre.c_str(), et.c_str() ); - size_t c = T[i].size(); - if (c == 0) printf("\n"); - for (size_t j = 0; j < c; j++) { - str s = (j == c - 1) ? slash : et; - str num = T[i][j] == -1 ? "" : f(T[i][j]).c_str(); - printf("%s%s", format(maxRow[j], num).c_str(), s.c_str() ); - } - } - printf("\n"); -} - -void print_table (str s, const Dtable & T, bool latex, - Slist labels) { - //size_t SIZE = 7; - size_t MAXSIZE = 10; - size_t MAXLINE = 50; - size_t STANDARDSIZE = 1; - bool square(true); - size_t l = T.size(); - if (MAXLINE < l) { - printf( - "Caution, table is of size %lu, only %lu will be displayed \n", l, - MAXLINE); - } - size_t cc = T[0].size(); - for (size_t i = 0; i < l; i++) { - if (T[i].size() != cc) { - square = false; - } - } - size_t max = max_row(T); - List maxRow = initList(max); - if (square) { - Table sizestr = initTable(l, max); - for (size_t i = 0; i < l; i++) { - for (size_t j = 0; j < max; j++) { - size_t sz = f(T[i][j]).size() + 1; - sizestr[i][j] = sz < MAXSIZE ? sz : MAXSIZE; - } - } - maxRow = max_on_row(sizestr); - } else { - maxRow = initList(max, STANDARDSIZE); - } - str et = latex ? " &" : "|"; - str slash = latex ? " \\\\ \n" : "\n"; - str rrr(T[0].size(), 'r'); - printf("%s", s.c_str() ); - printf("\n"); - bool labelsB = isnull(labels); - str space(6, ' '); - printf("%s", space.c_str() ); - printf("Obs. made "); - for (size_t j = 0; j < 6; j++) { - str s = (j == max - 1) ? slash : et; - printf("%s%s", format(maxRow[j], f((int)j) ).c_str(), s.c_str() ); - } - printf("initial& fibers&obs'rvd&percent& wght'd\\\\ \n"); - for (size_t i = 0; i < l && i < MAXLINE; i++) { - str pre = labelsB ? f((int)i) : format(11, labels[i]); - printf("%3s %s", pre.c_str(), et.c_str() ); - size_t c = T[i].size(); - if (c == 0) printf("\n"); - for (size_t j = 0; j < c; j++) { - str s = (j == c - 1) ? slash : et; - str num = T[i][j] == -1 ? "" : f(T[i][j]).c_str(); - printf("%s%s", format(maxRow[j], num).c_str(), s.c_str() ); - } - } - printf("\n"); -} - -void print_table (str s, const Ptable & T) { - printf("%s", s.c_str() ); - printf("\n"); - size_t l = T.size(); - if (l == 0) { - printf(" ! Empty table\n"); - return; - } - size_t c = T[0].size(); - for (size_t i = 0; i < l; i++) { - if (T[i].size() != c) { - printf( - " ! Table has different number of columns depending to the lines\n"); - return; - } - } - str s0(" ", 10); - const char * space = s0.c_str(); - printf("%s", space); - for (size_t j = 0; j < c; j++) { - printf("%11lu", j); - } - printf("\n"); - for (size_t i = 0; i < l; i++) { - printf("%4lu", i); - for (size_t j = 0; j < c; j++) { - printf("%11s", p2s(T[i][j]).c_str() ); - } - printf("\n"); - } - printf("\n"); -} - -List histogram (const Table & T, int interval) { - List hist; - size_t l = T.size(); - for (size_t i = 0; i < l; i++) { - size_t c = T[i].size(); - for (size_t j = 0; j < c; j++) { - int a = T[i][j]; - if (a != -1) { - if (a < 0) { - printf("Error in print_hist, neg\n"); - fl(); - } - size_t n = floor(a / interval); - // printf("%d %d %d %d-",n,a,i,j); - // makes histogram size expand to include last element - if (n >= hist.size() ) { - hist.resize(n + 1); - hist[n] = 0; - } - hist[n]++; - } - } - } - return hist; -} - -List histogram (const List & L, int interval) { - List hist; - size_t l = L.size(); - for (size_t i = 0; i < l; i++) { - int a = L[i]; - if (a != -1) { - if (a < 0) { - printf("Error in print_hist, neg\n"); - fl(); - } - size_t n = floor(a / interval); - if (n >= hist.size() ) { - hist.resize(n + 1); - hist[n] = 0; - } - hist[n]++; - } - } - return hist; -} - -Dlist histogram (const Dlist & L, double interval) { - Dlist hist; - size_t l = L.size(); - for (size_t i = 0; i < l; i++) { - double a = L[i]; - if (a != -1) { - if (a < 0) { - printf("Error in print_hist, neg\n"); - fl(); - } - size_t n = floor(a / interval); - if (n >= hist.size() ) { - hist.resize(n + 1); - hist[n] = 0; - } - hist[n]++; - } - } - return hist; -} - -Dlist histogram (const Dplist & L, double interval) { - Dlist hist; - size_t l = L.size(); - for (size_t i = 0; i < l; i++) { - double a = L[i].f; - if (a != -1) { - if (a < 0) { - printf("Error in print_hist, neg\n"); - fl(); - } - size_t n = floor(a / interval); - if (n >= hist.size() ) { - hist.resize(n + 1); - hist[n] = 0; - } - hist[n] += L[i].s; - } - } - return hist; -} - -Table with_tot (const Table & T) { - Table M = T; - for (size_t i = 0; i < M.size(); i++) { - M[i].push_back(sumlist(M[i]) ); - } - return M; -} - -List max_on_row (const Table & T) { - verif(T); - size_t l = T.size(); - size_t c = T[0].size(); - List L = initList(c, -1e7); - for (size_t i = 0; i < l; i++) { - for (size_t j = 0; j < c; j++) { - int a = T[i][j]; - if (a > L[j]) L[j] = a; - } - } - return L; -} - -void make_square (Table & T) { - size_t max = max_row(T); - for (size_t i = 0; i < T.size(); i++) { - if (T[i].size() < max) { - T[i].resize(max); - } - } -} - -Dtable divide (const Table & T, double d) { - Dtable t; - for (size_t i = 0; i < T.size(); i++) { - Dlist l; - for (size_t j = 0; j < T[i].size(); j++) { - l.push_back(T[i][j] / d); - } - t.push_back(l); - } - return t; -} - -Dtable divide (const Dtable & T, double d) { - Dtable t; - for (size_t i = 0; i < T.size(); i++) { - Dlist l; - for (size_t j = 0; j < T[i].size(); j++) { - l.push_back(T[i][j] / d); - } - t.push_back(l); - } - return t; -} - -Dtable mult (const Dtable & T, double d) { - Dtable t; - for (size_t i = 0; i < T.size(); i++) { - Dlist l; - for (size_t j = 0; j < T[i].size(); j++) { - l.push_back(T[i][j] * d); - } - t.push_back(l); - } - return t; -} - -Table divide_floor (const Table & T, double d) { - Table t; - for (size_t i = 0; i < T.size(); i++) { - List l; - for (size_t j = 0; j < T[i].size(); j++) { - l.push_back(T[i][j] / d); - } - t.push_back(l); - } - return t; -} - -Dtable ddivide_floor (const Table & T, double d) { - Dtable t; - for (size_t i = 0; i < T.size(); i++) { - Dlist l; - for (size_t j = 0; j < T[i].size(); j++) { - l.push_back(floor(T[i][j] / d) ); - } - t.push_back(l); - } - return t; -} - -Dtable concatenate (const Dtable & T1, const Dtable & T2) { - if (T1.size() != T2.size() ) { - printf("Error in concatenation : different sizes \n"); - myexit(1); - } - Dtable T3 = T1; - for (size_t i = 0; i < T1.size(); i++) { - for (size_t j = 0; j < T2[i].size(); j++) { - T3[i].push_back(T2[i][j]); - } - } - return T3; -} - -// Cube ------------------------------------------------------ -Cube initCube (int l, int c, int d, int val) { - Cube C; - C.resize(l); - for (int i = 0; i < l; i++) { - C[i].resize(c); - for (int j = 0; j < c; j++) { - C[i][j].resize(d, val); - } - } - return C; -} - -Dcube initDcube (int l, int c, int d, double val) { - Dcube C; - C.resize(l); - for (int i = 0; i < l; i++) { - C[i].resize(c); - for (int j = 0; j < c; j++) { - C[i][j].resize(d, val); - } - } - return C; -} - -size_t max_row (const Dcube & C) { - size_t max(0); - for (size_t i = 0; i < C.size(); i++) { - size_t c = C[i].size(); - if (c > max) { - max = c; - } - } - return max; -} - -// Time ------------------------------------------------------ -Time::Time () { - s = get_time(); - e = get_time(); -} - -double get_time () { - // Get wall time - struct timeval time; - if (gettimeofday(&time, NULL) ) { - return (0); - } else { - return ( (double)time.tv_sec + (double)time.tv_usec * .000001); - } -} - -double time_diff (Time t) { - return (t.e - t.s); -} - -void init_time (Time & t, const str s) { - t.s = get_time(); - if (s.size() != 0) { - std::cout << s << std::endl; - } -} - -void init_time_at (Time & time, const str s, Time & t) { - time.s = get_time(); - std::cout << s; - print_time(t, " at"); -} - -void print_time (Time & t, const str s) { - t.e = get_time(); - double d = time_diff(t); - if (d < 60.) { - std::cout << s << " " << std::setprecision(3) << d << " s\n" << - std::flush; - } else { - int mn = floor(d / 60); - double sc = d - (mn * 60); - std::cout << s << " " << mn << " mn " << std::setprecision(3) << sc << - " s\n" << std::flush; - } -} - -// Errors ----------------------------------------------------- - -void myexit (const int flag) { - std::cout.flush(); - std::cerr.flush(); - exit(flag); -} - -void myexception (const std::exception & e) { - std::cout << "Exception: " << e.what() << std::endl; - std::cout.flush(); - std::cerr.flush(); - exit(1); -} - -void myexception (std::exception & e) { - std::cout << "Exception: " << e.what() << std::endl; - std::cout.flush(); - std::cerr.flush(); - exit(1); -} - -void error (str s) { - std::cout << "Error : " << s << std::endl; - std::cout.flush(); - std::cerr.flush(); - exit(1); -} - -void deb (int a) { - std::cout << " " << a << std::endl; -} - -void deb (str a) { - std::cout << " " << a << std::endl; -} - -void deb (int a, int b) { - std::cout << " " << a << "," << b << " " << std::endl; -} - -void debl (int a) { - std::cout << a << " " << std::flush; -} - -void debl (str a) { - std::cout << a << " " << std::flush; -} - -void debl (double a) { - std::cout << a << " " << std::flush; -} - -void debl (bool a) { - std::cout << (a ? "true" : "false") << " " << std::flush; -} - -void deb (double a) { - std::cout << " " << a << std::endl; -} - -// Conversions ------------------------------------------------ - -str f (int i) { - std::stringstream ss; - ss << i; - str s = ss.str(); - str str(""); - int n = s.size(); - for (int l = 0; l < n; l++) { - str.push_back(s[l]); - if ( ( (n - 1 - l) % 3 == 0) && (n - l - 1 != 0) ) { - str.push_back(','); - } - } - return str.c_str(); -} - -str f (double i) { - std::stringstream ss; - ss << i; - str s = ss.str(); - str str(""); - int n = s.size(); - bool dot(true); - int dec(0); - int dot_pos(-1); - // for (int a=0; a n) { - for (int h = 0; h < size - n; h++) { - sp.push_back(' '); - } - } - return sp + s; -} - -str erase_spaces (str s) { - str ss = ""; - for (size_t h = 0; h < s.size(); h++) { - if (s[h] != ' ') { - ss.push_back(s[h]); - } - } - return ss; -} - -// Parse ------------------------------------------------------ - -Slist s2vec (str const & s, char const delimiter) { - Slist vec; - str element; - for (size_t i = 0; i < s.length(); i++) { - char ch = s[i]; - if (ch != delimiter) { - element += ch; - } else if (element.length() > 0) { - vec.push_back(element); - element.clear(); - } - } - // Push in the last element if the string does not end with the delimiter - if (element.length() > 0) { - vec.push_back(element); - } - return vec; -} - -void printFile (const char file[]) { - int Mc = 512; - std::ifstream fIn; - fIn.open(file); // open a file - if (!fIn.good() ) myexit(1); // Not found - char buf[Mc]; - while (!fIn.eof() && buf[0] != '-') { - fIn.getline(buf, Mc); - printf("%s", buf); - printf(" \n"); - } - fIn.close(); -} - -// Other ------------------------------------------------------ - -// Check if the arguments of the executable are right -void check_args (int n) { - if (n != 2) { - std::cerr << "Usage: assign " << std::endl; - myexit(1); - } -} - -int max (int a, int b) { - if (a > b) { - return a; - } - return b; -} - -int min (int a, int b) { - if (a > b) { - return b; - } - return a; -} - -int sq (int n) { - return (n * n); -} - -double sq (double n) { - return (n * n); -} - -double sq (double a, double b) { - return (a * a + b * b); -} - -double norm (double a, double b) { - return (sqrt(a * a + b * b) ); -} - -double norm (dpair p) { - return (sqrt(p.f * p.f + p.s * p.s) ); -} - -double percent (int a, int b) { - return (a * 100. / b); -} - -void fl () { - std::cout.flush(); -} diff --git a/old/src/misc.h b/old/src/misc.h deleted file mode 100644 index cf9b1963..00000000 --- a/old/src/misc.h +++ /dev/null @@ -1,353 +0,0 @@ -#ifndef MISC_H -#define MISC_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef std::string str; -typedef std::map Smap; - -// pair ------------------------------------------------------ -class pair { - public: - int f, s; - pair (); - pair (int a, int b); - void setnull (); - bool isnull () const; - void print_pair () const; -}; - -class dpair { - public: - double f, s; - dpair (); - dpair (double a, double b); - void print () const; - bool isnull () const; -}; - -// Add coords of 2 points -dpair operator+ (dpair const & a, dpair const & b); -dpair operator- (dpair const & a, dpair const & b); -dpair operator- (dpair const & a, double b); - -// Gives cartesian coordinates of a point defined by polar coords -dpair cartesian (double r, double theta); - -// Gives cartesian coordinates of a point defined by polar coords (in a dpair) -dpair cartesian (dpair X); - -// Cos and sin of the angle xOP -dpair cos_sin_angle (dpair P); - -// cos(t+a) = cos t * cos a + ... and sin(t+a) = ... -dpair sum_angles (dpair p1, dpair p2); - -// Distance between 2 points -double dist (dpair c1, dpair c2); -double norm (dpair p); - -// Norm squared of a point -double sq (dpair p); - -// |AB|² -double sq (dpair A, dpair B); - -// vec(AB).vec(AC) -double scalar_prod (dpair A, dpair B, dpair C); - -// List ------------------------------------------------------ - -class List : public std::vector {}; - -class Dlist : public std::vector {}; - -class Plist : public std::vector {}; - -class Dplist : public std::vector {}; - -class Slist : public std::vector {}; - -List Null (); -Slist Snull (); - -// Initialize a list of size l, with values val -List initList (int l, int val = 0); -Dlist initDlist (int l, double val = 0.0); - -// Transform l into the List type -List initList (std::vector l); - -// Initialize a list from array l which is of size size -List initList (int l[], int size); -Slist initList (str l[], int size); - -// Print list L, printing the message s before -void print_list (str s, const List & L); -void print_list (str s, Slist L); -void print_Dlist (str s, const Dlist & L); -void print_Plist (const Plist & L, str s = ""); - -// Print on a line -void print_list_line (const List & L); - -// Test if the list is null -bool isnull (const List & L); - -// Test if the list is null ("") -bool isnull (const Slist & L); - -// Sum of the list -int sumlist (const List & L); -double sumlist (const Dlist & L); - -// Max of the list -int max (const List & L); - -// List of 100*L[i]/n -Dlist percents (const List & L, int n); -Dlist percents (const Dlist & L, double n); - -// True iff n is found in L -bool isfound (int n, const List & L); - -// Return the position of where p is found, -1 if not -int isfound_pos (double n, const Dlist & L); - -// Return the position of where p is found, -1 if not -int isfound (pair p, const Plist & L); -bool isfound (str n, const Slist & L); - -// List of different taken values (ex 1,1,5,2,5 gives 1,5,2) -List values (const List & L); - -// Return a random permutation of [0,n-1] -List random_permut (int n); - -// Random permut of L -List random_permut (const List & L); - -// Print histogram hist with interval i, printing s before, in latex format if -// wished -void print_hist (str s, int i, List hist, bool latex = false); - -// Erase i th element -void erase (int i, List & L); - -// Erase i th element -void erase (int i, Plist & L); - -// Complementary list (provided L is a subset of [0,size-1]) -List complementary (int size, const List & L); - -// Return sublist -List sublist (int begin, int size, const List & L); - -// Switch elements a and b in L -void switch_elmts (int a, int b, List & L); - -// Sort L by increasing order -List sort (const List & L); - -// Gives the inverse map defined by L -List inverse (const List & L); - -// Cumulated sum of L (integral) -List cumulate (const List & L); -Dlist cumulate (const Dlist & L); - -// L[i]/d -Dlist division (const Dlist & L, double d); - -// Add elements of l to L -void addlist (List & L, const List & l); - -// L but with slight variations of elements -Dlist var (const List & L); - -// Get permutation that leads to sort this list -List get_permut_sort (const List & l); - -// Table ----------------------------------------------------- - -class Table : public std::vector {}; - -class Dtable : public std::vector {}; - -class Ptable : public std::vector {}; - -Table initTable (int l, int c, int val = 0); -Table initTable (const Table & T); -Ptable initPtable (int l, int c); -Dtable initDtable (int l, int c, double val = 0.0); - -// Verifies it's square -void verif (const Table & T); - -void print_table (str s, const Table & T, bool latex = false, - Slist labels = Snull() ); -void print_table (str s, const Dtable & T, bool latex = false, - Slist labels = Snull() ); -void print_table (str s, const Ptable & T); - -// Other constr wouldn't work if we would define a constructor in class Table -// Build histogram of interval interval from values in T -List histogram (const Table & T, int interval); - -// Build histogram of interval interval from values in L -List histogram (const List & L, int interval); -Dlist histogram (const Dlist & L, double interval); -Dlist histogram (const Dplist & L, double interval); - -// Print, in latex format, data from table T in file ss, writing s on cout -void print_mult_table_latex (str s, str ss, Table T, int multX = 1); -void print_mult_Dtable_latex (str s, str ss, Dtable T, double multX = 1); - -// Add a row with sum of lines -Table with_tot (const Table & T); - -// Max number of rows -size_t max_row (const Table & T); -size_t max_row (const Dtable & T); - -// List of max on each row -List max_on_row (const Table & T); - -// Make it square, filling with zeros -void make_square (Table & T); - -Dtable divide (const Table & T, double d); -Dtable divide (const Dtable & T, double d); -Dtable mult (const Dtable & T, double d); - -// floor(T[i][j]/d) -Table divide_floor (const Table & T, double d); - -// floor(T[i][j]/d) -Dtable ddivide_floor (const Table & T, double d); - -// Horizontal concatenation T1:T2 -Dtable concatenate (const Dtable & T1, const Dtable & T2); - -// Cube ------------------------------------------------------ - -class Cube : public std::vector {}; - -Cube initCube (int l, int c, int d, int val = 0); -class Dcube : public std::vector {}; - -Dcube initDcube (int l, int c, int d, double val = 0.0); - -// Max size of 2nd dim -size_t max_row (const Dcube & C); - -// Time ------------------------------------------------------ - -struct Time { - // Tstart, Tend (t.s & t.e) - double s, e; - Time (); -}; - -// Time from the hardware -double get_time (); - -// Difference e-s -double time_diff (Time t); - -// Update e and print elapsed time -void print_time (Time & t, const str s = "# Elapsed time"); - -// Init t (init s) -void init_time (Time & t, const str s = ""); - -// Init time, printing global time t -void init_time_at (Time & time, const str s, Time & t); - -// Errors ----------------------------------------------------- - -void myexit (const int i); -void myexception (const std::exception & e); - -// Intel compiler needs this version too -void myexception (std::exception & e); -void error (str s); - -// Used for debug, just prints a -void deb (int a); -void deb (str a); -void deb (int a, int b); -void deb (double a); - -// Debug : debl prints without skipping a line -void debl (int a); -void debl (str a); -void debl (double a); - -// Conversions ------------------------------------------------ - -// int 1526879 -> str 1,526,879 -str f (int i); - -// double 1523.5412 -> str 1,523.54 -str f (double i); - -// int to string -str i2s (int i); -str d2s (double i); -str p2s (pair p); -str p2s (int j, int k); -int s2i (str s); -bool s2b (str s); -double s2d (str s); - -// like in prinft("%5s") where 5 = size -str format (int size, str s); - -// Same str without spaces -str erase_spaces (str s); - -// Parse ------------------------------------------------------ - -// "a b cd" gives vec of "a"; "b"; "cd" if delimiter = " " -Slist s2vec (str const & s, char const delimiter); - -// Print the file -void printFile (const char file[]); - -// Other ------------------------------------------------------ - -// Check number of arguments -void check_args (int n); -int max (int a, int b); -int min (int a, int b); - -// n*n -int sq (int n); -double sq (double n); - -// a*a+b*b -double sq (double a, double b); - -// sqrt(a*a+b*b) -double norm (double a, double b); -double percent (int a, int b); - -// cout.flush() -void fl (); - -// Generates a random number between fMin and fMax -double fRand (double fMin, double fMax); - -#endif diff --git a/old/src/structs.cpp b/old/src/structs.cpp deleted file mode 100644 index 4d1a411e..00000000 --- a/old/src/structs.cpp +++ /dev/null @@ -1,1428 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "misc.h" -#include "feat.h" -#include "structs.h" -#include "collision.h" -#include "fitsio.h" - -// targets -// ----------------------------------------------------------------------- -MTL read_MTLfile (str readfile, const Feat & F, long SS, long SF) { - // reads fits files, specifically mtl, standard stars, sky fibers - str s = readfile; - MTL M; - std::string buf; - const char * fname; - fname = s.c_str(); - std::ifstream fs(fname); - int ii; - fitsfile * fptr; - int status = 0, anynulls; - int hdutype; - int nkeys; - int hdupos; - long nrows; - long nkeep; - int ncols; - long long * targetid; - long * desi_target; - long * bgs_target; - long * mws_target; - long starmask = SS; - int * numobs; - int * priority; - double * ra; - double * dec; - int colnum; - char * * brickname; - uint16_t * obsconditions; - double * subpriority; - fprintf(stdout, "star mask %ld\n", starmask); - // General purpose output stream for exceptions - std::ostringstream o; - // Check that input file exists and is readable by cfitsio - std::cout << "Finding file: " << fname << std::endl; - int file_exists; - fits_file_exists(fname, &file_exists, &status); - std::ostringstream exists_str; - exists_str << "(CFITSIO file_exists code: " << file_exists << ")"; - // Throw exceptions for failed read, see cfitsio docs - if (!file_exists) { - switch (file_exists) { - case -1: o << "Input MTL file must be a disk file: " << fname << - " " << exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - case 0: o << "Could not find MTL input file: " << fname << " " << - exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - case 2: o << "Cannot handle zipped MTL input file: " << fname << - " " << exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - } - } - std::cout << "Found MTL input file: " << fname << std::endl; - if (!fits_open_file(&fptr, fname, READONLY, &status) ) { - std::cout << "Reading MTL input file " << fname << std::endl; - if ( fits_movabs_hdu(fptr, 2, &hdutype, &status) ) myexit(status); - fits_get_hdrspace(fptr, &nkeys, NULL, &status); - fits_get_hdu_num(fptr, &hdupos); - // Get the HDU type - fits_get_hdu_type(fptr, &hdutype, &status); - fits_get_num_rows(fptr, &nrows, &status); - fits_get_num_cols(fptr, &ncols, &status); - fflush(stdout); - if (!(targetid = (long long *)malloc(nrows * sizeof(long long) ) ) ) { - fprintf(stderr, "problem with targetid allocation\n"); - myexit(1); - } - if (!(desi_target = (long *)malloc(nrows * sizeof(long) ) ) ) { - fprintf(stderr, "problem with desi_target allocation\n"); - myexit(1); - } - if (!(mws_target = (long *)malloc(nrows * sizeof(long) ) ) ) { - fprintf(stderr, "problem with mws_target allocation\n"); - myexit(1); - } - if (!(bgs_target = (long *)malloc(nrows * sizeof(long) ) ) ) { - fprintf(stderr, "problem with bgs_target allocation\n"); - myexit(1); - } - if (!(numobs = (int *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with numobs allocation\n"); - myexit(1); - } - if (!(priority = (int *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with priority allocation\n"); - myexit(1); - } - if (!(subpriority = (double *)malloc(nrows * sizeof(double) ) ) ) { - fprintf(stderr, "problem with priority allocation\n"); - myexit(1); - } - if (!(ra = (double *)malloc(nrows * sizeof(double) ) ) ) { - fprintf(stderr, "problem with ra allocation\n"); - myexit(1); - } - if (!(dec = (double *)malloc(nrows * sizeof(double) ) ) ) { - fprintf(stderr, "problem with dec allocation\n"); - myexit(1); - } - if (!(obsconditions = (uint16_t *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with obsconditions allocation\n"); - myexit(1); - } - if (!(brickname = (char **)malloc(nrows * sizeof(char *) ) ) ) { - fprintf(stderr, "problem with brickname allocation\n"); - myexit(1); - } - for (ii = 0; ii < nrows; ii++) { - if (!(brickname[ii] = (char *)malloc(9 * sizeof(char) ) ) ) { - fprintf(stderr, "problem with brickname allocation\n"); - myexit(1); - } - } - - // ----- TARGETID - // find which column contains the TARGETID values - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"TARGETID", &colnum, - &status) ) { - fprintf(stderr, "error finding TARGETID column\n"); - myexit(status); - } - long frow, felem, nullval; - frow = 1; - felem = 1; - nullval = -99.; - if (fits_read_col(fptr, TLONGLONG, colnum, frow, felem, nrows, - &nullval, targetid, &anynulls, &status) ) { - fprintf(stderr, "error reading TARGETID column\n"); - myexit(status); - } - - // ----- RA - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"RA", &colnum, - &status) ) { - fprintf(stderr, "error finding RA column\n"); - myexit(status); - } - if (fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nrows, &nullval, - ra, &anynulls, &status) ) { - fprintf(stderr, "error reading RA column\n"); - myexit(status); - } - - // ----- DEC - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"DEC", &colnum, - &status) ) { - fprintf(stderr, "error finding DEC column\n"); - myexit(status); - } - if (fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nrows, &nullval, - dec, &anynulls, &status) ) { - fprintf(stderr, "error reading DEC column\n"); - myexit(status); - } - - // ----- Target mask bits - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"DESI_TARGET", &colnum, - &status) ) { - fprintf(stderr, "error finding DESI_TARGET column\n"); - myexit(status); - } - if (fits_read_col(fptr, TLONG, colnum, frow, felem, nrows, &nullval, - desi_target, &anynulls, &status) ) { - fprintf(stderr, "error reading DESI_TARGET column\n"); - myexit(status); - } - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"MWS_TARGET", &colnum, - &status) ) { - fprintf(stderr, "error finding MWS_TARGET column\n"); - myexit(status); - } - if (fits_read_col(fptr, TLONG, colnum, frow, felem, nrows, &nullval, - mws_target, &anynulls, &status) ) { - fprintf(stderr, "error reading MWS_TARGET column\n"); - myexit(status); - } - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"BGS_TARGET", &colnum, - &status) ) { - fprintf(stderr, "error finding BGS_TARGET column\n"); - myexit(status); - } - if (fits_read_col(fptr, TLONG, colnum, frow, felem, nrows, &nullval, - bgs_target, &anynulls, &status) ) { - fprintf(stderr, "error reading BGS_TARGET column\n"); - myexit(status); - } - - // OBSCONDITIONS - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"OBSCONDITIONS", &colnum, - &status) ) { - fprintf(stderr, "error finding OBSCONDITIONS column\n"); - myexit(status); - } - if (fits_read_col(fptr, USHORT_IMG, colnum, frow, felem, nrows, - &nullval, obsconditions, &anynulls, &status) ) { - fprintf(stderr, "error reading OBSCONDITIONS column\n"); - myexit(status); - } - - // ----- BRICKNAME - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"BRICKNAME", &colnum, - &status) ) { - fprintf(stderr, "error finding BRICKNAME column\n"); - myexit(status); - } - if (fits_read_col(fptr, TSTRING, colnum, frow, felem, nrows, &nullval, - brickname, &anynulls, &status) ) { - fprintf(stderr, "error reading BRICKNAME column\n"); - myexit(status); - } - - // ----- SUBPRIORITY - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"SUBPRIORITY", &colnum, - &status) ) { - fprintf(stderr, "error finding SUBPRIORITY column\n"); - myexit(status); - } - if (fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nrows, &nullval, - subpriority, &anynulls, &status) ) { - fprintf(stderr, "error reading SUBPRIORITY column\n"); - myexit(status); - } - - // ----- NUMOBS_MORE - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"NUMOBS_MORE", &colnum, - &status) ) { - // fprintf(stderr, "error finding NUMOBS_MORE column\n"); - // myexit(status); - std::cout << "NUMOBS_MORE not found ... setting to 1" << std::endl; - for (int i = 0; i < nrows; i++) { - numobs[i] = 1; - } - } else if (fits_read_col(fptr, TINT, colnum, frow, felem, nrows, - &nullval, numobs, &anynulls, &status) ) { - fprintf(stderr, "error reading NUMOBS_MORE column\n"); - myexit(status); - } - // ----- PRIORITY - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"PRIORITY", &colnum, - &status) ) { - // fprintf(stderr, "error finding PRIORITY column\n"); - // myexit(status); - std::cout << "PRIORITY not found ... setting to 1" << std::endl; - for (int i = 0; i < nrows; i++) { - priority[i] = 1; - } - } else if (fits_read_col(fptr, TINT, colnum, frow, felem, nrows, - &nullval, priority, &anynulls, &status) ) { - fprintf(stderr, "error reading PRIORITY column\n"); - myexit(status); - } - nkeep = 0; - for (ii = 0; ii < nrows; ii++) { - if ( ( (SS != 0) && ( (desi_target[ii] & starmask) != 0) ) || - (SS == 0) ) { - nkeep++; - } - } - // count how many rows we will keep and reserve that amount - // nkeep = nrows; - printf("Keeping %ld targets within ra/dec ranges\n", nkeep); - try { - M.reserve(nkeep); - } catch (std::exception & e) { - myexception(e); - } - for (ii = 0; ii < nrows; ii++) { - str xname; - // make sure ra is between 0 and 360 - if (ra[ii] < 0.) ra[ii] += 360.; - if (ra[ii] >= 360.) ra[ii] -= 360.; - if ( ( dec[ii] <= -90.) || ( dec[ii] >= 90.) ) { - std::cout << "DEC=" << dec[ii] << " out of range reading " << - fname << std::endl; - myexit(1); - } - double theta = (90.0 - dec[ii]) * M_PI / 180.; - double phi = (ra[ii] ) * M_PI / 180.; - struct target Q; - Q.nhat[0] = cos(phi) * sin(theta); - Q.nhat[1] = sin(phi) * sin(theta); - Q.nhat[2] = cos(theta); - Q.obsconditions = obsconditions[ii]; - // priority not present for sky fibers or standard stars - Q.t_priority = priority[ii]; - Q.subpriority = subpriority[ii]; - Q.nobs_remain = numobs[ii]; - // need to keep track of this, too - Q.nobs_done = 0; - // changed only in update_plan - Q.once_obs = 0; - Q.ra = ra[ii]; - Q.dec = dec[ii]; - Q.id = targetid[ii]; - Q.desi_target = desi_target[ii]; - Q.mws_target = mws_target[ii]; - Q.bgs_target = bgs_target[ii]; - - if (SS != 0) { - Q.SS = 1; - } else { - Q.SS = SS; - } - Q.SF = SF; - - // These variables were not initialized elsewhere - Q.lastpass = 0; - Q.priority_class = 0; - strncpy(Q.brickname, brickname[ii], 9); - if ( ( (SS != -1) && ( (desi_target[ii] & starmask) != 0) ) || - (SS == 0) ) { - try { - M.push_back(Q); - } catch (std::exception & e) { - myexception(e); - } - bool in = false; - for (size_t j = 0; j < M.priority_list.size(); ++j) { - if (Q.t_priority == M.priority_list[j]) { - in = true; - } - } - if (!in) { - M.priority_list.push_back(Q.t_priority); - } - } - } // end ii loop over targets - - // Free memory - free(targetid); - free(desi_target); - free(mws_target); - free(bgs_target); - free(numobs); - free(priority); - free(subpriority); - free(ra); - free(dec); - free(obsconditions); - for (ii = 0; ii < nrows; ii++) { - free(brickname[ii]); - } - free(brickname); - - // Close file - fits_close_file(fptr, &status); - - std::sort(M.priority_list.begin(), M.priority_list.end() ); - return (M); - } else { - std::ostringstream open_status_str; - open_status_str << "(CFITSIO open_file status: " << status << ")"; - o << "Problem opening input MTL fits file: " << fname << " " << - open_status_str.str(); - throw std::runtime_error(o.str().c_str() ); - } -} - -void assign_priority_class (MTL & M) { - // assign each target to a priority class - // this needs to be updated - for (size_t i = 0; i < M.size(); ++i) { - if (!M[i].SS && !M[i].SF) { - for (size_t j = 0; j < M.priority_list.size(); ++j) { - if (M[i].t_priority == M.priority_list[j]) { - M[i].priority_class = j; - } - } - } - } -} - -// FP -// ---------------------------------------------------------------------------- -// Read the positions of the fibers on each plate. -// need also to get the petal, i.e. spectrometer rnc 1/16/15 added S -FP read_fiber_positions (const Feat & F) { - std::string buf; - std::ifstream fs(F.fibFile.c_str() ); - if (!fs) { - // An error occurred opening the file. - std::cerr << "Unable to open file " << F.fibFile << std::endl; - myexit(1); - } - getline(fs, buf); - while (fs.eof() == 0 && - ( (buf[0] == '#') || (buf.size() == 0) ) ) { - getline(fs, buf); - } - int i(0); - int petals_pac[] = {0, 1, 2, 7, 8, 9}; - List petals_pacL = initList(petals_pac, 6); - List inv = inverse(petals_pacL); - // collection of fibersfound(spectro,petals_pacL)) - FP FibPos; - fpos fiber_pos; - printf("before reading positioners \n"); - std::cout.flush(); - while (fs.eof() == 0) { - double x, y; - int fiber, location, spectro; - std::istringstream(buf) >> fiber >> location >> spectro >> x >> y; - try { - fiber_pos.fib_num = fiber; - fiber_pos.location = location; - fiber_pos.fp_x = x; - fiber_pos.fp_y = y; - //int sp = spectro; - fiber_pos.spectrom = spectro; - fiber_pos.coords = dpair(x, y); - } catch (std::exception & e) { - myexception(e); - } - FibPos.push_back(fiber_pos); - getline(fs, buf); - i++; - } - fs.close(); - printf("read the positioner file\n"); - int fiber_size = FibPos.size(); - // sort by fiber number - std::vector > pairs; - for (size_t f = 0; f < FibPos.size(); ++f) { - std::pair this_pair (FibPos[f].fib_num, f); - pairs.push_back(this_pair); - } - std::sort(pairs.begin(), pairs.end(), int_pairCompare); - std::vector out; - for (size_t f = 0; f < FibPos.size(); ++f) { - out.push_back(FibPos[pairs[f].second]); - } - copy(out.begin(), out.end(), FibPos.begin() ); - printf(" sorted by fiber number\n"); - for (int i = 0; i < 10; ++i) { - printf(" i %d FibPos[i].fib_num %d \n", i, FibPos[i].fib_num); - } - // create fibers_of_sp - FibPos.fibers_of_sp.resize(F.Npetal); - for (int k = 0; k < fiber_size; k++) { - FibPos.fibers_of_sp[FibPos[k].spectrom].push_back(k); - } - // create table of Neighbors - for (int i = 0; i < fiber_size; i++) { - for (int j = 0; j < fiber_size; j++) { - if (i != j) { - if (sq(FibPos[i].fp_x - FibPos[j].fp_x) + - sq(FibPos[i].fp_y - FibPos[j].fp_y) < - sq(F.NeighborRad) ) { - FibPos[i].N.push_back(j); - } - } - } - } - printf(" made neighbors \n"); - return (FibPos); -} - -// FP::FP() {}; -int A_less_than_B (int year_A, int month_A, int day_A, int year_B, int month_B, - int day_B) { - // fprintf(stdout, "%d %d %d %d %d %d\n",year_A, month_A, day_A, year_B, - // month_B, day_B); - if ( ( (year_A + month_A / 12.0) < (year_B + month_B / 12.0) ) ) return 1; - if ( ( (year_A + month_A / 12.0) > (year_B + month_B / 12.0) ) ) return 0; - if ( ( (year_A + month_A / 12.0) == (year_B + month_B / 12.0) ) ) { - if (day_A < day_B) { - return 1; - } else { - return 0; - } - } - return -1; -} - -void read_fiber_status (FP & FibPos, const Feat & F) { - std::string buf; - //char date_now[512]; - char date_init[512]; - char date_end[512]; - std::ifstream fs(F.fibstatusFile.c_str() ); - int fiber_size = FibPos.size(); - std::tm input_time = {}; - std::tm init_time = {}; - std::tm end_time = {}; - std::tm current_time = {}; - // current time - auto now = std::chrono::system_clock::to_time_t( - std::chrono::system_clock::now() ); - current_time = *(std::gmtime(&now) ); - // input time - std::stringstream ss(F.runDate); - ss >> std::get_time(&input_time, "%Y-%m-%d"); - // if the input time was set in the input file, then override the current - // machine time with the input time - if (A_less_than_B(input_time.tm_year, input_time.tm_mon, - input_time.tm_mday, 1, 1, 1) ) { - std::cout << "INPUT time is not set"; - } else { - current_time = input_time; - } - std::cout << "Input Time" << std::put_time(&input_time, "%c") << "\n"; - std::cout << "Current Time" << std::put_time(¤t_time, "%c") << "\n"; - if (!fs) { - // An error occurred opening the file. - std::cerr << "Unable to open file " << F.fibstatusFile << std::endl; - myexit(1); - } - getline(fs, buf); - while (fs.eof() == 0 && ( (buf[0] == '#') || (buf.size() == 0) ) ) { - getline(fs, buf); - } - std::cout.flush(); - int i(0); - printf("before reading status \n"); - std::cout.flush(); - while (fs.eof() == 0) { - double x, y; - int fiber, location, broken, stuck; - getline(fs, buf); - std::istringstream(buf) >> fiber >> location >> x >> y >> broken >> - stuck >> date_init >> date_end; - fprintf(stdout, - "Read from fiber status: Fiber_pos %d Location %d Broken %d Stuck %d dates %s %s \n", fiber, location, broken, stuck, date_init, - date_end); - std::stringstream si(date_init); - si >> std::get_time(&init_time, "%Y-%m-%dT%H:%M:%S"); - std::cout << "Init Time for Fiber" << - std::put_time(&init_time, "%c") << "\n"; - // std::stringstream ss(date_end); - std::stringstream se(date_end); - se >> std::get_time(&end_time, "%Y-%m-%dT%H:%M:%S"); - std::cout << "End Time for Fiber" << - std::put_time(&end_time, "%c") << "\n"; - i++; - // if the current time is within the time interval for the stuck/broken - // fiber, then make the change - if (A_less_than_B(init_time.tm_year, init_time.tm_mon, - init_time.tm_mday, current_time.tm_year, - current_time.tm_mon, - current_time.tm_mday) && - A_less_than_B(current_time.tm_year, current_time.tm_mon, - current_time.tm_mday, end_time.tm_year, - end_time.tm_mon, - end_time.tm_mday) ) { - for (int j = 0; j < fiber_size; j++) { - if (fiber == FibPos[j].fib_num) { - if (location == FibPos[j].location) { - fprintf(stdout, - "Changing fiberastatus entry: Fiber %d Location %d\n", fiber, - location); - if (broken == 1) { - fprintf(stdout, "BROKEN\n"); - FibPos[j].broken = broken; - } - if (stuck == 1) { - fprintf(stdout, "STUCK\n"); - FibPos[j].stuck = stuck; - FibPos[j].fp_x = x; - FibPos[j].fp_y = y; - } - } else { - std::cerr << "Fiber ID Matches But Not Location ID " << - F.fibFile << std::endl; - myexit(1); - } - } - } - } - } - fs.close(); - printf("read status file\n"); -} - -// plate -// --------------------------------------------------------------------------- -List plate::av_gals_plate (const Feat & F, const MTL & M, - const FP & pp) const { - // list of galaxies available to plate no repetitions - List gals = initList(F.Ngal); - List L = initList(0); - for (int k = 0; k < F.Nfiber; k++) { - for (size_t i = 0; i < av_gals[k].size(); i++) { - if (gals[av_gals[k][i]] == 0) { - gals[av_gals[k][i]] = 1; - L.push_back(i); - } - } - } - return L; -} - -Plates read_plate_centers (const Feat & F) { - Plates P, PQ; - const char * fname; - /*Variables used to read fits file*/ - fitsfile * fptr; - int status = 0, anynulls; - int hdutype; - int nkeys; - int hdupos; - long nrows; - //long nkeep; - int ncols; - int ii; - uint16_t * obsconditions; - int * in_desi; - int * tile_id; - int tileid; - int * ipass; - double * ra; - double * dec; - int colnum; - long frow, felem, nullval; - frow = 1; - felem = 1; - nullval = -99.; - Time t, time; // t for global, time for local - init_time(t); - // read the strategy file - // survey_list is list of tiles specified by tileid (arbitrary int) in - // order of survey - std::ifstream fsurvey(F.surveyFile.c_str() ); - if (!fsurvey) { - // An error occurred opening the file. - std::cerr << "Unable to open file " << F.surveyFile << std::endl; - myexit(1); - } - int survey_tile; - std::vector survey_list; - std::string buf; - while (getline(fsurvey, buf) ) { - std::istringstream ss(buf); - if (!(ss >> survey_tile) ) break; - survey_list.push_back(survey_tile); - } - printf(" number of tiles %lu \n", survey_list.size() ); - // NEW - // read list of tile centers - // Check that input file exists and is readable by cfitsio - fname = F.tileFile.c_str(); - std::cout << "Finding file: " << fname << std::endl; - int file_exists; - fits_file_exists(fname, &file_exists, &status); - std::ostringstream exists_str; - exists_str << "(CFITSIO file_exists code: " << file_exists << ")"; - std::ostringstream o; - // Throw exceptions for failed read, see cfitsio docs - if (!file_exists) { - switch (file_exists) { - case -1: o << "Input tile centers file must be a disk file: " << - fname << " " << exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - case 0: o << "Could not find input tile centers file: " << - fname << " " << exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - case 2: o << "Cannot handle zipped tile centers input file: " << - fname << " " << exists_str.str(); - throw std::runtime_error(o.str().c_str() ); - } - } - std::cout << "Found input tile centers file: " << fname << std::endl; - if (!fits_open_file(&fptr, fname, READONLY, &status) ) { - std::cout << "Reading input tile centers file " << fname << std::endl; - if ( fits_movabs_hdu(fptr, 2, &hdutype, &status) ) myexit(status); - fits_get_hdrspace(fptr, &nkeys, NULL, &status); - fits_get_hdu_num(fptr, &hdupos); - fits_get_hdu_type(fptr, &hdutype, &status); /* Get the HDU type */ - fits_get_num_rows(fptr, &nrows, &status); - fits_get_num_cols(fptr, &ncols, &status); - /* - std::cout << ncols << " columns " << nrows << "nrows" << std::endl; - std::cout << "HDU " << hdupos << std::endl; - if (hdutype == ASCII_TBL){ - std::cout << "ASCII TABLE: " << std::endl; - }else{ - std::cout << "BINARY TABLE: " << std::endl; - } - */ - if (!(obsconditions = (uint16_t *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with priority allocation\n"); - myexit(1); - } - if (!(ipass = (int *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with ipass allocation\n"); - myexit(1); - } - if (!(in_desi = (int *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with priority allocation\n"); - myexit(1); - } - if (!(tile_id = (int *)malloc(nrows * sizeof(int) ) ) ) { - fprintf(stderr, "problem with priority allocation\n"); - myexit(1); - } - if (!(ra = (double *)malloc(nrows * sizeof(double) ) ) ) { - fprintf(stderr, "problem with ra allocation\n"); - myexit(1); - } - if (!(dec = (double *)malloc(nrows * sizeof(double) ) ) ) { - fprintf(stderr, "problem with dec allocation\n"); - myexit(1); - } - - // ----- RA - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"RA", &colnum, - &status) ) { - fprintf(stderr, "error finding RA column\n"); - myexit(status); - } - if (fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nrows, &nullval, - ra, &anynulls, &status) ) { - fprintf(stderr, "error reading RA column\n"); - myexit(status); - } - - // ----- DEC - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"DEC", &colnum, - &status) ) { - fprintf(stderr, "error finding DEC column\n"); - myexit(status); - } - if (fits_read_col(fptr, TDOUBLE, colnum, frow, felem, nrows, &nullval, - dec, &anynulls, &status) ) { - fprintf(stderr, "error reading DEC column\n"); - myexit(status); - } - - // ----- IN_DESI - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"IN_DESI", &colnum, - &status) ) { - fprintf(stderr, "error finding IN_DESI column\n"); - myexit(status); - } - if (fits_read_col(fptr, TINT, colnum, frow, felem, nrows, &nullval, - in_desi, &anynulls, &status) ) { - fprintf(stderr, "error reading IN_DESI column\n"); - myexit(status); - } - - // ----- OBSCONDITIONS - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"OBSCONDITIONS", &colnum, - &status) ) { - fprintf(stderr, "error finding OBSCONDITIONS column\n"); - myexit(status); - } - if (fits_read_col(fptr, USHORT_IMG, colnum, frow, felem, nrows, - &nullval, obsconditions, &anynulls, &status) ) { - fprintf(stderr, "error reading OBSCONDITIONS column\n"); - myexit(status); - } - - // ----- TILEID - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"TILEID", &colnum, - &status) ) { - fprintf(stderr, "error finding OBSCONDITIONS column\n"); - myexit(status); - } - if (fits_read_col(fptr, TINT, colnum, frow, felem, nrows, &nullval, - tile_id, &anynulls, &status) ) { - fprintf(stderr, "error reading TILEID column\n"); - myexit(status); - } - - // ----- PASS - if ( fits_get_colnum(fptr, CASEINSEN, (char *)"PASS", &colnum, - &status) ) { - fprintf(stderr, "error finding PASS column\n"); - myexit(status); - } - if (fits_read_col(fptr, TINT, colnum, frow, felem, nrows, &nullval, - ipass, &anynulls, &status) ) { - fprintf(stderr, "error reading PASS column\n"); - myexit(status); - } - try { - P.reserve(400000); - } catch (std::exception & e) { - myexception(e); - } - for (ii = 0; ii < nrows; ii++) { - // fprintf(stdout, "in desi %d\n", in_desi[ii]); - if ( (in_desi[ii] == 1) && (obsconditions[ii] != 0) ) { - if (ra[ii] < 0.) ra[ii] += 360.; - if (ra[ii] >= 360.) ra[ii] -= 360.; - if ( ( dec[ii] < -90.) || ( dec[ii] > 90.) ) { - std::cout << "DEC=" << dec << " out of range reading " << - F.tileFile << std::endl; - myexit(1); - } - double theta = (90.0 - dec[ii]) * M_PI / 180.; - double phi = (ra[ii] ) * M_PI / 180.; - struct plate Q; - Q.tileid = tile_id[ii]; - Q.obsconditions = obsconditions[ii]; - // std::cout << "TILEID " << tileid << std::endl; - Q.tilera = ra[ii]; - Q.tiledec = dec[ii]; - Q.nhat[0] = sin(theta) * cos(phi); - Q.nhat[1] = sin(theta) * sin(phi); - Q.nhat[2] = cos(theta); - // <- be careful, format of input file - Q.ipass = ipass[ii]; - // <- added - Q.av_gals.resize(F.Nfiber); - // <- added - Q.density.resize(F.Nfiber); - // was Nfbp - Q.SS_av_gal.resize(F.Npetal); - // was Nfbp - Q.SF_av_gal.resize(F.Npetal); - Q.SS_in_petal.resize(F.Npetal); - Q.SF_in_petal.resize(F.Npetal); - Q.SS_av_gal_fiber.resize(F.Nfiber); - Q.SF_av_gal_fiber.resize(F.Nfiber); - for (int i = 0; i < F.Npetal; ++i) { - Q.SS_in_petal[i] = 0; - } - for (int i = 0; i < F.Npetal; ++i) { - Q.SF_in_petal[i] = 0; - } - try { - P.push_back(Q); - } catch (std::exception & e) { - myexception(e); - } - } - } - - // Free memory - free(obsconditions); - free(ipass); - free(in_desi); - free(tile_id); - free(ra); - free(dec); - - // Close file - fits_close_file(fptr, &status); - - } - printf(" size of P %lu\n", P.size() ); - // Map each valid tileid in order to an index in P[]. - // Tileid is an arbitrary int - std::map invert_tile; - std::map ::iterator tileid_to_idx; - std::pair ::iterator, bool> ret; - init_time_at(time, "# Start invert tiles", t); - for (unsigned i = 0; i < P.size(); ++i) { - ret = invert_tile.insert(std::make_pair(P[i].tileid, i) ); - // Check for duplicates (std::map.insert only creates keys, fails on - // duplicate keys) - if ( ret.second == false ) { - std::cerr << "ERROR: Duplicate tileid " << P[i].tileid << - " in tileFile!" << std::endl; - std::exit(1); - // std::ostringstream o; - // o << "Duplicate tileid " << P[i].tileid << " in tileFile!"; - // throw std::logic_error(o.str().c_str()); - } - } - print_time(time, "# ..inversion took :"); - // Create PQ, a subset of P containing those tileids specified in the - // surveyFile, in the order in which they are specified. - init_time_at(time, "# do inversion of used plates", t); - for (size_t i = 0; i < survey_list.size(); ++i) { - tileid = survey_list[i]; - tileid_to_idx = invert_tile.find(tileid); - if (tileid_to_idx == invert_tile.end() ) { - // Can end up with no mapping if surveyFile contains valid tileids - // that have in_desi = 0 in the tileFile. - std::cerr << "ERROR: surveyFile contains tileid " << tileid << - ", which is not included (or has in_desi = 0) in tileFile." << - std::endl; - std::exit(1); - // std::ostringstream o; - // o << "surveyFile contains tileid " << tileid << ", which is not - // included (or has in_desi = 0) in tileFile."; - // throw std::range_error(o.str().c_str()); - } - // Found a valid index, push the tile to the ordered list. - PQ.push_back(P[tileid_to_idx->second]); - } - print_time(time, "# .. sued plates inversion took :"); - return (PQ); -} - -// Assignment -// ----------------------------------------------------------------------------- -Assignment::Assignment (const MTL & M, const Feat & F) { - // galaxy assigned to tile-fiber TF[j][k] - TF = initTable(F.Nplate, F.Nfiber, -1); - // tile-fiber pair for galaxy GL[g] - GL = initPtable(F.Ngal, 0); - inv_order = initList(F.Nplate, -1); - next_plate = 0; - kinds = initCube(F.Nplate, F.Npetal, F.Categories); - // initialized to number of fibers on a petal - unused = initTable(F.Nplate, F.Npetal, F.Nfbp); -} - -Assignment::~Assignment () { -} - -// Assign g with tile/fiber (j,k), and check for duplicates -void Assignment::assign (int j, int k, int g, MTL & M, Plates & P, - const FP & pp) { - // Assign (j,k) - int q = TF[j][k]; - if (q != -1) { - printf( - "### !!! ### DUPLICATE (j,k) = (%d,%d) assigned with g = %d and %d ---> information on first g lost \n", j, k, q, - g); - myexit(1); - } - // Assign g - TF[j][k] = g; - // pair list, tf's for this g - Plist pl = GL[g]; - pair p = pair(j, k); - for (size_t i = 0; i < pl.size(); i++) { - if (pl[i].f == j) { - printf( - "### !!! ### DUPLICATE g = %d assigned with (j,k) = (%d,%d) and (%d,%d) ---> information on first (j,k) lost \n", g, - pl[i].f, pl[i].s, j, k); - // Can be commented if want to force continuing - myexit(1); - } - } - GL[g].push_back(p); - M[g].nobs_done++; - M[g].nobs_remain--; - if (M[g].SF) { - int q = pp[k].spectrom; - P[j].SF_in_petal[q] += 1; - } - if (M[g].SS) { - int q = pp[k].spectrom; - P[j].SS_in_petal[q] += 1; - } - unused[j][pp[k].spectrom]--; -} - -void Assignment::unassign (int j, int k, int g, MTL & M, Plates & P, - const FP & pp) { - // diagnostic - if (TF[j][k] == -1) { - printf( - "### !!! ### TF (j,k) = (%d,%d) gets unassigned but was already not assigned\n", j, k); - } - int a = isfound(pair(j, k), GL[g]); - if (a == -1) { - printf( - "### !!! ### Galaxy g = %d gets unassigned but was already not assigned\n", g); - } - TF[j][k] = -1; - if (a != -1) { - erase(a, GL[g]); - } - M[g].nobs_done--; - M[g].nobs_remain++; - if (M[g].SF) { - int p = pp[k].spectrom; - P[j].SF_in_petal[p] -= 1; - } - if (M[g].SS) { - int p = pp[k].spectrom; - P[j].SS_in_petal[p] -= 1; - } - unused[j][pp[k].spectrom]++; -} - -int Assignment::is_assigned_jg (int j, int g) const { - // is galaxy g assigned on tile j - for (size_t i = 0; i < GL[g].size(); i++) { - if (GL[g][i].f == j) { - return (int)i; - } - } - return -1; -} - -int Assignment::is_assigned_jg (int j, int g, const MTL & M, - const Feat & F) const { - // No occurrence too nearby in tiles - for (size_t i = 0; i < GL[g].size(); i++) { - if ( ( fabs(j - GL[g][i].f) < F.InterPlate) || - ( j == GL[g][i].f) ) { - return i; - } - } - return -1; -} - -bool Assignment::is_assigned_tf (int j, int k) const { - return (TF[j][k] != -1); -} - -int Assignment::na (const Feat & F, int begin, int size) const { - // unassigned fibers in tiles begin to begin+size - int size1 = (size == -1) ? F.Nplate : size; - int cnt(0); - for (int j = begin; j < begin + size1; j++) { - for (int k = 0; k < F.Nfiber; k++) { - if (TF[j][k] != -1) { - cnt++; - } - } - } - return cnt; -} - -Plist Assignment::chosen_tfs (int g, const Feat & F, int begin) const { - // creates list of tile-fibers observing g starting from plate begin - Plist chosen; - for (size_t i = 0; i < GL[g].size(); i++) { - pair tf = GL[g][i]; - if (begin <= tf.f ) { - if (TF[tf.f][tf.s] != g) { - printf("ERROR in chosen_tfs\n"); - fl(); - } - chosen.push_back(tf); - } - } - return chosen; -} - -Table Assignment::unused_fbp (const FP & pp, const Feat & F) const { - // table unused fibers on petal on tile j - Table unused = initTable(F.Nplate, F.Npetal); - // List Sp = pp.spectrom; - for (int j = 0; j < F.Nplate; j++) { - for (int k = 0; k < F.Nfiber; k++) { - if (!is_assigned_tf(j, k) ) { - unused[j][pp[k].spectrom]++; - } - } - } - return unused; -} - -// not used -List Assignment::unused_f (const Feat & F) const { - // total unused fibers - List unused = initList(F.Nplate); - for (int j = 0; j < F.Nplate; j++) { - for (int k = 0; k < F.Nfiber; k++) { - if (!is_assigned_tf(j, k) ) { - unused[j]++; - } - } - } - return unused; -} - -int Assignment::unused_f (int j, const Feat & F) const { - // unused fibers on tile j - int unused(0); - for (int k = 0; k < F.Nfiber; k++) { - if (!is_assigned_tf(j, k) ) { - unused++; - } - } - return unused; -} - -int Assignment::unused_fbp (int j, int k, const FP & pp, - const Feat & F) const { - // unused fibers on petal containing fiber k, tile j - List fibs = pp.fibers_of_sp[pp[k].spectrom]; - int unused(0); - for (size_t i = 0; i < fibs.size(); i++) { - if (!is_assigned_tf(j, fibs[i]) ) { - unused++; - } - } - return unused; -} - -int Assignment::nkind (int j, int k, int kind, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, bool pet) const { - // if pet is false, used petal of fiber k,, if pet is true use petal k - if (!pet) { - return kinds[j][pp[k].spectrom][kind]; - } else { - return kinds[j][k][kind]; - } -} - -List Assignment::fibs_unassigned (int j, int pet, const MTL & M, const FP & pp, - const Feat & F) const { - // list of unassigned fibers on petal pet - List L; - List fibs = pp.fibers_of_sp[pet]; - for (int kk = 0; kk < F.Nfbp; kk++) { - int k = fibs[kk]; - if (!is_assigned_tf(j, k) ) { - L.push_back(k); - } - } - return L; -} - -// Returns the radial distance on the plate (mm) given the angle, -// theta (radians). This is simply a fit to the data provided. -double plate_dist (const double theta) { - const double p[4] = {8.297e5, -1750., 1.394e4, 0.0}; - double rr = 0; - for (int i = 0; i < 4; i++) { - rr = theta * rr + p[i]; - } - return rr; -} - -// returns the angle (theta) on the plate given the distance -// on the plate (mm) -double plate_angle (double r_plate) { - double theta; - double delta_theta = 1E-4; - double error = 1.0; - theta = 0.1; - while (abs(error) > 1E-7) { - error = plate_dist(theta) - r_plate; - theta -= (error) / - ( (plate_dist(theta + delta_theta) - plate_dist(theta) ) / - delta_theta); - } - // fprintf(stdout, "%f %f %f\n", r_plate, theta, plate_dist(theta)); - return theta; -} - -// Returns the x-y position on the plate centered at P for galaxy O. -struct onplate change_coords (const struct target & O, - const struct plate & P) { - struct onplate obj; - // Rotate the "galaxy" vector so that the plate center is at z-hat. - double nhat1[3], nhat2[3]; - const double ct = P.nhat[2], st = sqrt(1 - P.nhat[2] * P.nhat[2]) + 1e-30; - const double cp = P.nhat[0] / st, sp = P.nhat[1] / st; - // First rotate by -(Phi-Pi/2) about z. Note sin(Phi-Pi/2)=-cos(Phi) - // and cos(Phi-Pi/2)=sin(Phi). - nhat1[0] = O.nhat[0] * sp - O.nhat[1] * cp; - nhat1[1] = O.nhat[0] * cp + O.nhat[1] * sp; - nhat1[2] = O.nhat[2]; - // then rotate by Theta about x - nhat2[0] = nhat1[0]; - nhat2[1] = nhat1[1] * ct - nhat1[2] * st; - nhat2[2] = nhat1[1] * st + nhat1[2] * ct; - // now work out the "radius" on the plate - double tht = sqrt(sq(nhat2[0], nhat2[1]) ); - double rad = plate_dist(tht); - // the x-y position is given by our nhat's scaled by this - obj.pos[0] = nhat2[0] / tht * rad; - obj.pos[1] = nhat2[1] / tht * rad; - return obj; -} - -struct onplate radec2xy (const struct target & O, const struct plate & P) { - // following - // https://github.com/desihub/desimodel/blob/master/py/desimodel/focalplane.py#L259 - struct onplate obj; - double inc; // inclination - double coord[3], coord1[3], coord2[3]; - double deg_to_rad = M_PI / 180.0; - double x, y, z, x0, y0, z0, x_focalplane, y_focalplane, radius_rad; - double newteldec, newtelra, ra_rad, dec_rad, q_rad, radius_mm; - double testra, testdec, dra, ddec; - double arcsec = 1.0 / 3600.0; - - // Inclination is 90 degrees minus the declination in degrees - inc = 90.0 - O.dec; - x0 = sin(inc * deg_to_rad) * cos(O.ra * deg_to_rad); - y0 = sin(inc * deg_to_rad) * sin(O.ra * deg_to_rad); - z0 = cos(inc * deg_to_rad); - coord[0] = x0; - coord[1] = y0; - coord[2] = z0; - - coord1[0] = cos(P.tilera * deg_to_rad) * coord[0] + sin( - P.tilera * deg_to_rad) * coord[1]; - coord1[1] = -sin(P.tilera * deg_to_rad) * coord[0] + cos( - P.tilera * deg_to_rad) * coord[1]; - coord1[2] = coord[2]; - - coord2[0] = cos(P.tiledec * deg_to_rad) * coord1[0] + sin( - P.tiledec * deg_to_rad) * coord1[2]; - coord2[1] = coord1[1]; - coord2[2] = -sin(P.tiledec * deg_to_rad) * coord1[0] + cos( - P.tiledec * deg_to_rad) * coord1[2]; - x = coord2[0]; - y = coord2[1]; - z = coord2[2]; - newteldec = 0; - newtelra = 0; - ra_rad = atan2(y, x); - if (ra_rad < 0) { - ra_rad = 2.0 * M_PI + ra_rad; - } - dec_rad = (M_PI / 2) - acos(z / sqrt( (x * x) + (y * y) + (z * z) ) ); - radius_rad = 2 * - asin(sqrt( (pow(sin( (dec_rad - newteldec) / 2), 2) ) + - ( (cos(newteldec) ) * cos(dec_rad) * - (pow(sin( ( ra_rad - newtelra) / 2), 2) ) ) ) ); - q_rad = atan2(z, -y); - radius_mm = plate_dist(radius_rad); - x_focalplane = radius_mm * cos(q_rad); - y_focalplane = radius_mm * sin(q_rad); - obj.pos[0] = x_focalplane; - obj.pos[1] = y_focalplane; - // test the conversion - xy2radec(&testra, &testdec, P.tilera, P.tiledec, obj.pos[0], obj.pos[1]); - dra = (testra * cos(testdec * M_PI / 180.0) - O.ra * - cos(O.dec * M_PI / 180.0) ) / arcsec; - ddec = (testdec - O.dec) / arcsec; - if (fabs(dra) > 0.01) { - // 0.01 arcsecond precision - fprintf(stderr, - "onplate problem with xy2radec conversion [dRA (arcsec)]: %f\n", - dra); - fprintf(stderr, "[dDEC (arcsec)]: %f \n", ddec); - // myexit(1); - } - if (fabs(ddec) > 0.01) { - // 0.01 arcsecond precision - fprintf(stderr, - "onplate problem with xy2radec conversion [dDEC]: %f\n", ddec); - fprintf(stderr, "[dRA]: %f\n", dra); - // myexit(1); - } - return obj; -} - -// Returns the ra-dec position of an x, y position on the focal plane given the -// telescope pointing telra, teldec -void xy2radec (double * ra, double * dec, double telra, double teldec, - double x, double y) { - // following - // https://github.com/desihub/desimodel/blob/master/py/desimodel/focalplane/geometry.py#L165 - double coord[3], coord1[3], coord2[3]; - double x1, y1, z1, x2, y2, z2; - double teldec_rad = teldec * M_PI / 180.; - double telra_rad = telra * M_PI / 180.; - double radius; - double r_rad; - double q, q_rad; - double ra_rad, dec_rad; - - // radial distance on the focal plane in radians - radius = sqrt(x * x + y * y); - r_rad = plate_angle(radius); - - // fprintf(stdout, "tel ra %f tel dec %f\n", telra, teldec); - // q signifies the angle the position makes with the +x-axis of focal plane - q_rad = atan2(y, x); - q = q_rad * 180.0 / M_PI; - - // The focal plane is oriented with +yfocal = +dec but +xfocal = -RA - // Rotate clockwise around z by r_rad - // zrotate = np.zeros(shape=(3,3)) - // zrotate[0] = [np.cos(r_rad), np.sin(r_rad), 0] - // zrotate[1] = [-np.sin(r_rad), np.cos(r_rad), 0] - // zrotate[2] = [0, 0, 1] - // v1 = zrotate.dot(v0) - - x1 = cos(r_rad); // y0=0 so drop sin(r_rad) term - y1 = -sin(r_rad); // y0=0 so drop cos(r_rad) term - z1 = 0.0; - - // clockwise rotation around the x-axis - // xrotate = np.zeros(shape=(3,3)) - // q_rad = np.radians(q) - // xrotate[0] = [1, 0, 0] - // xrotate[1] = [0, np.cos(q_rad), np.sin(q_rad)] - // xrotate[2] = [0, -np.sin(q_rad), np.cos(q_rad)] - - x2 = x1; - y2 = y1 * cos(q_rad); //# z1=0 so drop sin(q_rad) term - z2 = -y1 * sin(q_rad); - - coord[0] = x2; - coord[1] = y2; - coord[2] = z2; - - // Clockwise rotation around y axis by declination of the tile center - coord1[0] = cos(teldec_rad) * coord[0] - sin(teldec_rad) * coord[2]; - coord1[1] = coord[1]; - coord1[2] = sin(teldec_rad) * coord[0] + cos(teldec_rad) * coord[2]; - - // Counter-clockwise rotation around the z-axis by the right ascension of the tile center - coord2[0] = cos(telra_rad) * coord1[0] - sin(telra_rad) * coord1[1]; - coord2[1] = sin(telra_rad) * coord1[0] + cos(telra_rad) * coord1[1]; - coord2[2] = coord1[2]; - - ra_rad = atan2(coord2[1], coord2[0]); - if (ra_rad < 0) ra_rad = 2.0 * M_PI + ra_rad; - // fprintf(stdout, "NORM %f %f %f\n", coord4[0], coord4[1], coord4[2]); - dec_rad = (M_PI / 2.0) - acos(coord2[2]); - - *ra = std::fmod( (ra_rad * 180.0 / M_PI), 360.0); - *dec = dec_rad * 180.0 / M_PI; - // fprintf(stdout, "FINAL: %f %f \n", *ra, *dec); -} - -bool collision (dpair O1, dpair G1, dpair O2, dpair G2, const Feat & F) { - double dist_sq = sq(G1, G2); - if (dist_sq < sq(F.Collide) ) return true; - if (dist_sq > sq(F.NoCollide) ) return false; - PosP posp(3, 3); - polygon fh1 = F.fh; - polygon fh2 = F.fh; - polygon cb1 = F.cb; - polygon cb2 = F.cb; - repos_cb_fh(cb1, fh1, O1, G1, posp); - repos_cb_fh(cb2, fh2, O2, G2, posp); - if (collision(fh1, fh2) ) return true; - if (collision(cb1, fh2) ) return true; - if (collision(cb2, fh1) ) return true; - return false; -} - -// (On plate p) finds if there is a collision if fiber k would observe galaxy g -// (collision with neighbor) -// j is in list that runs to F.Nplate since it is used in TF[j][k] -int Assignment::find_collision (int j, int k, int g, const FP & pp, - const MTL & M, const Plates & P, - const Feat & F, int col) const { - // check all neighboring fibers - bool bol = (col == -1) ? F.Collision : false; - if (bol) { - return -1; - } - dpair G1 = projection(g, j, M, P); - for (size_t i = 0; i < pp[k].N.size(); i++) { - // i numbers the fibers neighboring fiber k - int kn = pp[k].N[i]; - int gn = TF[j][kn]; - if (gn != -1) { - dpair G2 = projection(gn, j, M, P); - bool b = - F.Exact ? collision(pp[k].coords, G1, pp[kn].coords, G2, - F) : (sq(G1, G2) < sq(F.AvCollide) ); - if (b) { - return kn; - } - } - } - return -1; -} - -bool Assignment::find_collision (int j, int k, int kn, int g, int gn, - const FP & pp, const MTL & M, - const Plates & P, const Feat & F, - int col) const { - // check two fibers - bool bol = (col == -1) ? F.Collision : false; - if (bol) { - return false; - } - dpair G1 = projection(g, j, M, P); - dpair G2 = projection(gn, j, M, P); - return F.Exact ? collision(pp[k].coords, G1, pp[k].coords, G2, - F) : (sq(G1, G2) < sq(F.AvCollide) ); -} - -int Assignment::is_collision (int j, int k, const FP & pp, const MTL & M, - const Plates & P, const Feat & F) const { - // find collision for galaxy g - int g = TF[j][k]; - if (g != -1) { - return find_collision(j, k, g, pp, M, P, F, 0); - } else { - return -1; - } -} - -float Assignment::colrate (const FP & pp, const MTL & M, const Plates & P, - const Feat & F, int jend0) const { - // rate of collisions - int jend = (jend0 == -1) ? F.Nplate : jend0; - int col = 0; - for (int j = 0; j < jend; j++) { - List done = initList(F.Nfiber); - for (int k = 0; k < F.Nfiber; k++) { - if (done[k] == 0) { - int c = is_collision(j, k, pp, M, P, F); - if (c != -1) { - done[c] = 1; - col += 2; - } - } - } - } - return percent(col, jend * F.Nfiber); -} - -dpair projection (int g, int j, const MTL & M, - const Plates & OP) { - // x and y coordinates for galaxy observed on plate j - // struct onplate op = change_coords(M[g],OP[j]); - struct onplate op = radec2xy(M[g], OP[j]); - return dpair(op.pos[0], op.pos[1]); -} diff --git a/old/src/structs.h b/old/src/structs.h deleted file mode 100644 index 3102e51c..00000000 --- a/old/src/structs.h +++ /dev/null @@ -1,320 +0,0 @@ -#ifndef STRUCTS_H -#define STRUCTS_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "feat.h" - -// fiber-positioner ----------------------------------- - -class fpos { - public: - // number of fiber(!) not positioner, read from fibpos file - int fib_num; - // x position in mm of positioner - double fp_x; - // y position in mm of positioner - double fp_y; - // location of fiber - int location; - // which spectrometer 0 - 9 - int spectrom; - // 0=OK - int stuck = 0; - // 0=OK - int broken = 0; - // Identify neighboring positioners : neighbors of fiber k are N[k] - std::vector N; - dpair coords; -}; - -class FP : public std::vector { - public: - // Inv map of spectrom, fibers_of_sp[sp] are fibers of spectrom sp, - // redundant - Table fibers_of_sp; -}; - -FP read_fiber_positions (const Feat & F); - -void read_fiber_status (FP & FibPos, const Feat & F); - -bool int_pairCompare (const std::pair & firstElem, - const std::pair & secondElem); - -// galaxy truth ------------------------------------------- - -class galaxy { - public: - // the unique identifier - long long targetid; - - // the true type when used with a secret file - long category; - double z; - uint16_t obsconditions; -}; - -class Gals : public std::vector {}; - -Gals read_Secretfile (str filename, const Feat & F); - -Gals read_Secretfile_ascii (str filename, const Feat & F); - -std::vector count_galaxies (const Gals & G); - -// target ----------------------------------------------------- - -class target { - public: - // note that this is how we read it in! not long - long long id; - int nobs_remain, nobs_done; - double nhat[3]; - double ra, dec, subpriority; - long desi_target, mws_target, bgs_target; - int SS, SF, lastpass, priority_class, t_priority, once_obs; - char brickname [9]; - Plist av_tfs; - // 16bit mask indicating under what conditions this target can be - // observed. - uint16_t obsconditions; -}; - -class MTL : public std::vector { - public: - std::vector priority_list; -}; - -MTL read_MTLfile (str filename, const Feat & F, long SS, long SF); - -void assign_priority_class (MTL & M); - -// Plate ------------------------------------------------- - -struct onplate { - // The position of a galaxy in plate coordinates - int id; - double pos[2]; -}; - -class Onplates : public std::vector {}; - -class plate { - public: - int tileid; - double tilera; - double tiledec; - // Unit vector pointing to plate - double nhat[3]; - // Pass - int ipass; - // av_gals[k] : available galaxies of fiber k - Table av_gals; - // density[k] is the weighted number of objects available to (j,k) - List density; - // SS_av_gal[p] are available standard stars on petal p of this plate - Table SS_av_gal; - Table SF_av_gal; - Table SS_av_gal_fiber; - Table SF_av_gal_fiber; - // number of SS assigned to a petal in this plate - std::vector SS_in_petal; - std::vector SF_in_petal; - // true if tile has some galaxies within reach - bool is_used; - // mask defining the kind of program (DARK, BRIGHT, GRAY) - uint16_t obsconditions; - // Av gals of the plate - List av_gals_plate (const Feat & F, const MTL & M, const FP & pp) const; -}; - -class Plates : public std::vector {}; - -Plates read_plate_centers (const Feat & F); - -// Assignment --------------------------------------------- - -// 2 mappings of assignments : (j,k) -> id(gal) ; id(gal)[5] -> (j,k) -class Assignment { - public: - //// ----- Members - // TF for tile fiber, #tiles X #fibers TF[j][k] is the chosen galaxy, - // -1 if not yet chosen - Table TF; - - // Order of tiles we want to assign, only 1-n in simple increasing - // order for the moment - List order; - - // Order of tiles actually containing targets. size is F.Nplate - List suborder; - - // inverse of suborder unused tiles map to -1 - List inv_order; - - // Next plate in the order, i.e suborder(next_plate) is actually next - // plate - int next_plate; - - // Redundant information (optimizes computation time) - // GL for galaxy - list : #galaxies X (variable) #chosen TF: gives - // chosen tf's for galaxy g - Ptable GL; - - // Cube[j][sp][id] : number of fibers of spectrometer sp and plate j - // that have the kind id - Cube kinds; - - // Table [j][p] giving number of unused fibers on this petal - Table unused; - - // List of nobs, redundant but optimizes, originally true goal - // List nobsv; - // List of nobs, redundant but optimizes, apparent goal, i.e. goal of - // category of this type, gets updated - // List nobsv_tmp; - - //// ----- Methods - - Assignment (const MTL & M, const Feat & F); - - ~Assignment (); - - void assign (int j, int k, int g, MTL & M, Plates & P, const FP & pp); - - void unassign (int j, int k, int g, MTL & M, Plates & P, - const FP & pp); - - int find_collision (int j, int k, int g, const FP & pp, const MTL & M, - const Plates & P, const Feat & F, - int col = -1) const; - - bool find_collision (int j, int k, int kn, int g, int gn, - const FP & pp, const MTL & M, const Plates & P, - const Feat & F, int col = -1) const; - - int is_collision (int j, int k, const FP & pp, const MTL & M, - const Plates & P, const Feat & F) const; - - // Verif mappings are right - void verif (const Plates & P, const MTL & M, const FP & pp, - const Feat & F) const; - - int is_assigned_jg (int j, int g) const; - - int is_assigned_jg (int j, int g, const MTL & M, const Feat & F) const; - - bool is_assigned_tf (int j, int k) const; - - // Number of assignments (changes) within plates begin to begin+size - int na (const Feat & F, int begin = 0, int size = -1) const; - - // Counts how many more times object should be observed. If tmp=true, - // return maximum for this kind (temporary information) - // if tmp=false we actually know the true type from the start - int nobs (int g, const MTL & M, const Feat & F, bool tmp = true) const; - - // Pairs (j,k) chosen by g, amongst size plates from begin - Plist chosen_tfs (int g, const Feat & F, int begin = 0) const; - - // Number of fibers assigned to the kind "kind" on the petal of (j,k). - // If pet=true, we don't take k but the petal p directly instead - int nkind (int j, int k, int kind, const MTL & M, const Plates & P, - const FP & pp, const Feat & F, bool pet = false) const; - - // Sublist of fibers assigned to a galaxy of type kind for (j,p) - List fibs_of_kind (int kind, int j, int pet, const MTL & M, - const FP & pp, const Feat & F) const; - - // not used - // Sort this list of fibers by decreasing density - List sort_fibs_dens (int j, const List & fibs, const MTL & M, - const Plates & P, const FP & pp, - const Feat & F) const; - - // Sublist of unassigned fibers for (j,p) - List fibs_unassigned (int j, int pet, const MTL & M, const FP & pp, - const Feat & F) const; - - // Used to compute results at the end - // gives total number of unused fibers - List unused_f (const Feat & F) const; - - // Unused fibers by petal - Table unused_fbp (const FP & pp, const Feat & F) const; - - // Get collision rate, j = plate number - float colrate (const FP & pp, const MTL & M, const Plates & P, - const Feat & F, int j = -1) const; - - // Know the number of remaining observations of g when the program is - // at the tile j, for pyplotTile - int nobs_time (int g, int j, const Gals & Secret, const MTL & M, - const Feat & F) const; - - // Number of unused fiber on the j'th plate - int unused_f (int j, const Feat & F) const; - - // not used - // Number of unassigned fibers of the petal corresponding to (j,k) - int unused_fbp (int j, int k, const FP & pp, const Feat & F) const; - - // not used - void update_nobsv_tmp (const Feat & F); -}; - -// collisions from looking at galaxy G1 with fiber positioner centered at 01 -// and etc calculated in mm on plate -bool collision (dpair O1, dpair G1, dpair O2, dpair G2, const Feat & F); - -// int fprio(int g, const Gals& G, const Feat& F, const Assignment& -// A);//priority of galaxy g -double plate_angle (double r_plate); - -// plate scale conversion -double plate_dist (const double theta); - -void xy2radec (double * ra, double * dec, double telra, double teldec, - double x, double y); - -struct onplate change_coords (const struct target & O, const struct plate & P); - -struct onplate radec2xy (const struct target & O, const struct plate & P); - -// Projection of g on j -dpair projection (int g, int j, const MTL & M, const Plates & P); - -// weighted (and only with remaining observation according to the moment in the -// survey), and doesn't take into account other kinds than QSO LRG ELG not used -int num_av_gals (int j, int k, const MTL & M, const Plates & P, const Feat & F, - const Assignment & A); - -int A_less_than_B (int year_A, int month_A, int day_A, int year_B, int month_B, - int day_B); - -// Pyplot ----------------------------------------------- - -class pyplot { - public: - polygon pol; - Slist text; - Dplist textpos; - pyplot (polygon p); - void addtext (dpair p, str s); - void plot_tile (str directory, int j, const Feat & F) const; -}; - - -#endif