<resource schema="dfbsspec">
  <macDef name="spectralBins">6.9E-7, 6.789E-7, 6.682E-7, 6.58E-7, 6.482E-7, 6.388E-7, 6.298E-7, 6.212E-7, 6.129E-7, 6.049E-7, 5.972E-7, 5.897E-7, 5.826E-7, 5.757E-7, 5.69E-7, 5.626E-7, 5.564E-7, 5.503E-7, 5.445E-7, 5.389E-7, 5.334E-7, 5.281E-7, 5.23E-7, 5.18E-7, 5.132E-7, 5.085E-7, 5.039E-7, 4.995E-7, 4.952E-7, 4.91E-7, 4.869E-7, 4.829E-7, 4.791E-7, 4.753E-7, 4.717E-7, 4.681E-7, 4.646E-7, 4.612E-7, 4.579E-7, 4.547E-7, 4.515E-7, 4.484E-7, 4.454E-7, 4.425E-7, 4.396E-7, 4.368E-7, 4.34E-7, 4.314E-7, 4.287E-7, 4.262E-7, 4.236E-7, 4.212E-7, 4.188E-7, 4.164E-7, 4.141E-7, 4.118E-7, 4.096E-7, 4.074E-7, 4.053E-7, 4.032E-7, 4.011E-7, 3.991E-7, 3.972E-7, 3.952E-7, 3.933E-7, 3.915E-7, 3.896E-7, 3.878E-7, 3.86E-7, 3.843E-7, 3.826E-7, 3.809E-7, 3.793E-7, 3.777E-7, 3.761E-7, 3.745E-7, 3.73E-7, 3.714E-7, 3.7E-7, 3.685E-7, 3.671E-7, 3.656E-7, 3.642E-7, 3.629E-7, 3.615E-7, 3.602E-7, 3.589E-7, 3.576E-7, 3.563E-7, 3.551E-7, 3.538E-7, 3.526E-7, 3.514E-7, 3.502E-7, 3.491E-7, 3.479E-7, 3.468E-7, 3.457E-7, 3.446E-7, 3.435E-7, 3.424E-7, 3.414E-7, 3.403E-7, 3.393E-7, 3.383E-7, 3.373E-7, 3.363E-7, 3.354E-7, 3.344E-7, 3.335E-7, 3.325E-7, 3.316E-7, 3.307E-7, 3.298E-7, 3.289E-7, 3.28E-7, 3.272E-7, 3.263E-7, 3.255E-7, 3.247E-7, 3.238E-7, 3.23E-7, 3.222E-7, 3.214E-7, 3.206E-7, 3.199E-7, 3.191E-7, 3.184E-7, 3.176E-7, 3.169E-7, 3.161E-7, 3.154E-7, 3.147E-7, 3.14E-7, 3.133E-7, 3.126E-7</macDef>

  <meta name="title">Digitized First Byurakan Survey (DFBS) Extracted Spectra</meta>
  <meta name="description" format="rst">
    The First Byurakan Survey (FBS) is the largest and the first systematic
    objective prism survey of the extragalactic sky. It covers 17,000 sq.deg.
    in the Northern sky together with a high galactic latitudes region in the
    Southern sky. The FBS has been carried out by B.E. Markarian, V.A.
    Lipovetski and J.A. Stepanian in 1965-1980 with the Byurakan Observatory
    102/132/213 cm (40"/52"/84") Schmidt telescope using 1.5 deg. prism. Each
    FBS plate contains low-dispersion spectra of some 15,000-20,000 objects;
    the whole survey consists of about 20,000,000 objects.

  </meta>

  <meta name="_longdoc" format="rst"><![CDATA[
    Usage Hints
    ===========

    Note that the spectra are not flux calibrated.  Indeed, they
    were scanned off of different emulsions, and only spectra from
    compatible emulsions should be compared.  The following emulsions
    occur in the database:

    =========  ============
      n         emulsion
    =========  ============
      334409    103aF
      18695     103aO
      3622      IF
      13555     IIAD
      2409058   IIAF
      16545     IIAF bkd
      3254370   IIF
      313287    IIF bkd
      7871      IIIAJ bkd
      6645      IIIF
      18967     IIIaF
      8122      IIaD
      3565737   IIaF
      6735      IIaO
      16755     OAF
      8794      ORWO CP-3
      8097      ZP-3
      23702     Zu-2
    =========  ============

    Upper- and lowercase versions of the emulsions are actually different
    (e.g., IIAD was produced in England, IIaD in the US).  Their properties
    are different enough to make mixing spectra for the different emulsions
    unwise.

    Also note the ``sp_class`` column.  Unless you take great precaution,
    you probably should only use spectra with ``sp_class='OK'``.

    Spectra can be retrieved in VOTable form (via SSA or the accref field
    from the TAP table), but it will usually be faster to directly pull them
    from the spectral and flux arrays.

    Actually, array indices in the flux arrays correspond to fixed wavelengths.
    In other words, the ``spectral`` column is constant in the database, except
    that because the ``flux`` arrays are of different length, the blue
    end of the spectral column is shortened.  The spectra always start
    at to 690 nm.  The blue end depends on how far some signal was suspected
    by the extraction machinery.


    Use Cases
    =========

    Locate Spectra by Features
    --------------------------

    While ADQL support for array operations is rather weak, you can subscript
    arrays.  Because of the fixed bins, you can therefore select by flux
    ratios (never use absolute numbers here; they are meaningless).  For
    instance, to select objects with a high (apparent) Halpha emission
    (656 nm, corresponding to array index 3), you might so something like::

      select * from dfbsspec.spectra
      where
        flux[3]/(flux[40]+flux[41]+flux[42])>30
        and sp_class='OK'

    Since the table needs to be sequentially scanned for this, it will
    take a minute or so.  Combine with an object selection (see below)
    or other criteria if possible.

    Get Average Spectra
    -------------------

    You cannot currently use the ADQL aggregate function AVG with arrays
    (which should be fixed at some time in the future).  Meanwhile, you can
    work around this with a clumsy construction like this (this query will
    give you average spectra by magnitude bin; don't run it just for fun,
    it'll take a while)::

      select round(magb) as bin, avg(flux[1]) as col1, avg(flux[2]) as col2,
        avg(flux[3]) as col3, avg(flux[4]) as col4, avg(flux[5]) as col5,
        avg(flux[6]) as col6, avg(flux[7]) as col7, avg(flux[8]) as col8,
        avg(flux[9]) as col9, avg(flux[10]) as col10, avg(flux[11]) as col11,
        avg(flux[12]) as col12, avg(flux[13]) as col13, avg(flux[14]) as col14,
        avg(flux[15]) as col15, avg(flux[16]) as col16, avg(flux[17]) as col17,
        avg(flux[18]) as col18, avg(flux[19]) as col19, avg(flux[20]) as col20,
        avg(flux[21]) as col21, avg(flux[22]) as col22, avg(flux[23]) as col23,
        avg(flux[24]) as col24, avg(flux[25]) as col25, avg(flux[26]) as col26,
        avg(flux[27]) as col27, avg(flux[28]) as col28, avg(flux[29]) as col29,
        avg(flux[30]) as col30, avg(flux[31]) as col31, avg(flux[32]) as col32,
        avg(flux[33]) as col33, avg(flux[34]) as col34, avg(flux[35]) as col35,
        avg(flux[36]) as col36, avg(flux[37]) as col37, avg(flux[38]) as col38,
        avg(flux[39]) as col39, avg(flux[40]) as col40, avg(flux[41]) as col41,
        avg(flux[42]) as col42, avg(flux[43]) as col43, avg(flux[44]) as col44,
        avg(flux[45]) as col45, avg(flux[46]) as col46, avg(flux[47]) as col47,
        avg(flux[48]) as col48, avg(flux[49]) as col49, avg(flux[50]) as col50,
        avg(flux[51]) as col51, avg(flux[52]) as col52, avg(flux[53]) as col53,
        avg(flux[54]) as col54, avg(flux[55]) as col55, avg(flux[56]) as col56,
        avg(flux[57]) as col57, avg(flux[58]) as col58, avg(flux[59]) as col59
      from dfbsspec.spectra
      where sp_class='OK'
      group by bin

    To map ``col<n>`` to wavelenghts, see the contents of (any) ``spectral``
    column.

    Build Templates
    ---------------

    To compute an average spectrum for a class of objects, we suggest to
    pull positions of such objects from SIMBAD and then fetch the associate
    spectra from this database.  Since the response function of the
    photographic plates had a strong magnitude dependence, restrict the
    objects to a small magnitude range, for instance::

        select
            otype, ra, dec, flux
        from basic
        join flux
        on (oid=oidref)
        where
            otype='HS*'
            and dec>-15
            and filter='G'
            and flux between 12.5 and 13.5

    (to be executed on SIMBAD's TAP service, see also `SIMBAD object types`_).

    .. _SIMBAD object types: http://simbad.u-strasbg.fr/simbad/sim-display?data=otypes

    With the resulting table, go do this service and execute a query like::

      SELECT
      specid, spectral, flux
      FROM dfbsspec.spectra AS db
      JOIN TAP_UPLOAD.t1 AS tc
      ON DISTANCE(tc.ra, tc.dec, db.ra, db.dec)<5./3600.
      WHERE sp_class='OK'

    (adjust t1 according to your client's rules; in TOPCAT, that's t plus
    the table number from the control window).

    History of this Data Collection
    ===============================

    The original aim of the First Byurakan Survey
    was to search for galaxies with UV excess (:bibcode:`1986ApJS...62..751M`,
    Markarian et al. 1989,1997- catalogue No. VII/172 at CDS). Successively,
    the amount of spectral information contained in the plates allowed the
    development of several other projects concerning the spectral
    classification of Seyfert Galaxies (Weedman and Kachikian 1971), the first
    definition of starburst galaxies (Weedman 1977 ), the discovery and
    investigation of blue stellar objects (Abrahamian and Mickaelian, 1996,
    Mickaelian et al 2001, 2002, CDS catalogue No II/223) and a survey for
    late-type stars (Gigoyan et al. 2002). All these results were obtained by
    eye inspection of the plates performed with the aid of a microscope at the
    Byurakan Observatory. The number and classes of new objects discovered FBS
    made clear the need of open access to FBS for the entire astronomical
    community.
  ]]></meta>

  <meta name="creationDate">2017-11-28T10:50:00Z</meta>
  <meta name="schema-rank">100</meta>

  <meta name="subject">spectroscopy</meta>
  <meta name="subject">surveys</meta>
  <meta name="subject">active-galactic-nuclei</meta>

  <meta name="creator">Markarian, B.E.</meta>
  <meta name="instrument">Byurakan 1m Schmidt</meta>
  <meta name="facility">Byurakan Astrophysical Observatory BAO</meta>

  <meta name="source">2007A&amp;A...464.1177M</meta>
  <meta name="contentLevel">Research</meta>
  <meta name="type">Archive</meta>

  <meta name="coverage">
    <meta name="waveband">Optical</meta>
  </meta>

  <table id="raw_spectra" onDisk="true" adql="true">
     <mixin>//products#table</mixin>
     <mixin>//scs#q3cindex</mixin><mixin>//scs#pgs-pos-index</mixin>
    <meta name="description">
      Raw metadata for the spectra, to be combined with image
      metadata like date_obs and friends for a complete spectrum
      descriptions.  This also contains spectral and flux points
      in array-valued columns.
    </meta>


    <primary>specid</primary>
    <index columns="plate"/>
    <index columns="accref"/>
    <index columns="pub_did"/>
    <index columns="specid"/>
    <index columns="lam_min"/>

    <column name="specid" type="text"
      ucd="meta.id;meta.main"
      tablehead="ID"
      description="Identifier of the spectrum built from the plate identifier,
        a -, and the object position as in objectid."
      verbLevel="25"/>
    <column name="plate" type="text"
      ucd=""
      tablehead="Src. Plate"
      description="Number of the plate this spectrum was extracted
        from.  Technically, this is a foreign key into dfbs.plates."
      verbLevel="1"/>
    <column name="objectid" type="text"
      ucd="meta.id"
      tablehead="Obj."
      description="Synthetic object id assigned by DFBS."
      verbLevel="1"/>
    <column name="ra" type="double precision"
      unit="deg" ucd="pos.eq.ra;meta.main"
      tablehead="RA"
      description="ICRS RA of the source of this spectrum."
      verbLevel="1"/>
    <column name="dec" type="double precision"
      unit="deg" ucd="pos.eq.dec;meta.main"
      tablehead="Dec"
      description="ICRS Dec of the source of this spectrum."
      verbLevel="1"/>
    <column name="pos" type="spoint"
      ucd="pos.eq"
      tablehead="Pos"
      description="The object position as s pgsphere spoint."
      verbLevel="30"/>

    <column name="sp_class" type="text"
      ucd="meta.code.qual"
      tablehead="Sp. Class"
      description="Quality indicator: OK of undisturbed spectra of sufficiently
        bright objects, NL if disturbers are nearby, U for objects
        unclassifiable because of lack of signal."
      verbLevel="25"/>

    <column name="flux" type="real[]"
      unit="" ucd="phot.flux.density;em.wl"
      tablehead="Flux[]"
      description="Flux points of the extracted spectrum (arbitrary units)"
      verbLevel="30"/>

    <column name="magb"
      unit="mag" ucd="phot.mag;em.opt.B"
      tablehead="mag. B"
      description="Source object magnitude in Johnson B"
      verbLevel="15"/>
    <column name="magr"
      unit="mag" ucd="phot.mag;em.opt.R"
      tablehead="mag. R"
      description="Source object magnitude in Johnson R"
      verbLevel="15"/>

    <column name="snr"
      ucd="stat.snr"
      tablehead="SNR"
      description="Estimated signal-to-noise ratio for this spectrum."
      verbLevel="25"/>
    <column name="lam_min"
      unit="m" ucd="em.wl;stat.min"
      tablehead="λ_min"
      description="Minimal wavelength in this spectrum (the longest
        wavelength is always 690 nm)."
      verbLevel="15"/>

    <column name="sky"
      ucd="instr.skyLevel"
      tablehead="Sky"
      description="Sky background estimation from the scan (uncalibrated)."
      verbLevel="25"/>
    <column name="px_x"
      unit="pixel" ucd="pos.cartesian.x;instr"
      tablehead="X"
      description="Location of the spectrum on the plate scan, x coordinate."
      verbLevel="25"/>
    <column name="px_y"
      unit="pixel" ucd="pos.cartesian.y;instr"
      tablehead="Y"
      description="Location of the spectrum on the plate scan, y coordinate."
      verbLevel="25"/>
    <column name="pos_ang"
      unit="deg" ucd="pos.posAng"
      tablehead="P.A."
      description="Position angle of the spectrum on the plate, north over
        east."
      verbLevel="25"/>
    <column name="px_length"
      tablehead="#"
      description="Number of points in this spectrum"
      verbLevel="25"/>

    <column name="pub_did" type="text"
      ucd="meta.ref.url"
      tablehead="Publisher DID"
      description="Dataset identifier assigned by the publisher."
      verbLevel="25"/>
  </table>

  <data id="import">
    <recreateAfter>make_ssa_view</recreateAfter>
    <recreateAfter>make_tap_view</recreateAfter>
    <sources pattern="data/*.sql.gz"/>
    <!-- this parses from the SQL dump we got from Italy.  We
    	trust all the fbs_* tables have the same structure. -->
    <embeddedGrammar notify="True">
      <iterator>
        <setup>
          <code><![CDATA[
            import gzip
            import re
            import numpy

            # see README for plate id disambiguation
            DECRANGES_FOR_PLATEID_DEDUP = {
              "fbs0326": (25, 35),
              "fbs0449": (25, 35),
              "fbs0996": (42, 54)}

            def parseSpectraFromDump(inputLine):
              """this assumes the schema

              `id` int(11) NOT NULL AUTO_INCREMENT,
              `nome` varchar(55) DEFAULT NULL,
              `ra1` varchar(20) DEFAULT NULL,
              `dec1` varchar(20) DEFAULT NULL,
              `ra2` double DEFAULT '0',
              `dec2` double DEFAULT '0',
              `magB` varchar(20) DEFAULT NULL,
              `magR` varchar(20) DEFAULT NULL,
              `Lun` varchar(20) DEFAULT NULL,
              `redBord` varchar(20) DEFAULT NULL,
              `sn` varchar(20) DEFAULT NULL,
              `x` int(11) DEFAULT NULL,
              `y` int(11) DEFAULT NULL,
              `angolo` varchar(20) DEFAULT NULL,
              `ell` varchar(20) DEFAULT NULL,
              `sky` varchar(20) DEFAULT NULL,
              `profilo` text,
              `classe` varchar(20) DEFAULT NULL,

              throughout.  We also hope there are no literals with commas
              or parentheses in.  If there are, this stuff should exception
              out.
              """
              # we pull the plate name from the table name by
              # cutting off everything after an underscore from the
              # table name.  Let's see if we get away with this.
              plate = re.search("`([^`]*)`", inputLine
                ).group(1).split("_")[0]

              # pull out the first declination so we know where
              # we're looking; this is so we can fix bad plate
              # ids (see README)
              dec = float(
                re.search(r"\([^,]*,[^,]*,[^,]*,[^,]*,[^,]*,([^,]*)",
                  inputLine).group(1))
              if plate in DECRANGES_FOR_PLATEID_DEDUP:
                lowerDec, upperDec = DECRANGES_FOR_PLATEID_DEDUP[plate]
                if lowerDec<dec<upperDec:
                  plate = plate+"a"

              # now strip off everything up to the first opening
              # and after the last closing paren -- after that, we
              # get the records by simple splitting
              inputLine = inputLine[
                inputLine.index('('):inputLine.rindex(')')]
              for rec in inputLine.split('),('):
                (_, objectid, _, _, ra, dec, magb, magr, lun,
                  redBord, snr, px_x, px_y, pos_ang, ell, sky, fluxes, sp_class
                  ) = [s.strip("'") for s in rec.split(",")]
                yield locals()
          ]]></code>
        </setup>
        <code>
          # The spectra are in one table per source plate, and
          # the dump has the values of one such plate in one line.
          # So, I look for such lines and then parse from there
          with gzip.open(self.sourceToken) as f:
            for line in f:
              if line.startswith(b"INSERT INTO `fbs"):
                for row in parseSpectraFromDump(line.decode("ascii")):
                  yield row
        </code>
      </iterator>

      <rowfilter procDef="//products#define">
        <bind name="table">"\schema.spectra"</bind>
        <bind key="accref">"\rdId/%s-%s"%(@plate, @objectid[5:])</bind>
        <bind name="path">makeAbsoluteURL(
          "\rdId/sdl/dlget?ID="+urllib.parse.quote("\rdId/%s-%s"%(
            @plate, @objectid[5:])))</bind>
        <bind name="mime">"application/x-votable+xml"</bind>
        <bind name="preview_mime">"image/png"</bind>
        <bind name="preview">makeAbsoluteURL("\rdId/preview/qp/%s-%s"%(
          @plate, @objectid[5:]))</bind>
        <bind name="fsize">20000</bind>
      </rowfilter>
    </embeddedGrammar>

    <make table="raw_spectra">
      <rowmaker idmaps="*">
        <!-- redBord is an index to where the flux spectrum starts.
        redBord+2 is the 690 nm bin -->
        <var key="flux">[float(item or 'nan')
          for item in @fluxes.split("#")[int(@redBord)+1:]]</var>
        <!-- the float RA is in decimal hours.  No joke. -->
        <var key="ra">float(@ra)/24.*360</var>
        <var key="dec">float(@dec)</var>
        <var key="specid">@plate+"-"+@objectid[5:]</var>

        <apply>
          <setup>
            <par name="bins">[\spectralBins]</par>
          </setup>
          <code>
            try:
              @lam_min = bins[len(@flux)-1]
            except IndexError:
              @lam_min = bins[-1]
          </code>
        </apply>
        <map key="pos">pgsphere.SPoint.fromDegrees(@ra, @dec)</map>
        <map key="pub_did"
          >'ivo://\getConfig{ivoa}{authority}/~?\rdId/'+@specid</map>

        <map key="px_length">len(@flux)</map>
      </rowmaker>
    </make>
  </data>

  <table id="ssa" onDisk="true" namePath="raw_spectra">
    <meta name="description">A view providing standard SSA metadata for
      DBFS metadata in \schema.spectra</meta>
    <property name="forceStats">present</property>
    <mixin
      fluxUnit=" "
      fluxUCD="phot.flux.density"
      spectralUnit="m">//ssap#mixc</mixin>
    <mixin>//ssap#simpleCoverage</mixin>
    <mixin
      ra="ra"
      dec="dec"
      t_min="t_min"
      t_max="t_max"
      >//obscore#publishSSAPMIXC</mixin>
    <meta name="_associatedDatalinkService">
      <meta name="serviceId">sdl</meta>
      <meta name="idColumn">ssa_pubDID</meta>
    </meta>

    <column original="magb"/>
    <column original="magr"/>
    <column original="plate"/>
    <column original="ra"/>
    <column original="dec"/>

    <column name="t_min" type="double precision" hidden="True"/>
    <column name="t_max" type="double precision" hidden="True"/>

    <viewStatement>
    CREATE VIEW \curtable AS (
      SELECT
          accref, owner, embargo, mime, accsize,
          objectid || ' spectrum from ' || plate AS ssa_dstitle,
          NULL::TEXT AS ssa_creatorDID,
          pub_did::text AS ssa_pubDID,
          NULL::TIMESTAMP AS ssa_cdate,
          '2018-09-01'::TIMESTAMP AS ssa_pdate,
          emulsion AS ssa_bandpass,
          '1.0'::TEXT AS ssa_cversion,
          NULL::TEXT AS ssa_targname,
          NULL::TEXT AS ssa_targclass,
          NULL::REAL AS ssa_redshift,
          NULL::spoint AS ssa_targetpos,
          snr AS ssa_snr,
          pos AS ssa_location,
          2/3600.::REAL AS ssa_aperture,
          epoch AS ssa_dateObs,
          exptime AS ssa_timeExt,
          (lam_min+690e-9)/2. AS ssa_specmid,
          690e-9-lam_min AS ssa_specext,
          lam_min AS ssa_specstart,
          690e-9 AS ssa_specend,
          px_length::INTEGER AS ssa_length,
          'spectrum'::TEXT AS ssa_dstype,
          'BAO'::TEXT AS ssa_publisher,
          'Markarian et al'::TEXT AS ssa_creator,
          'DFBS spectra'::TEXT AS ssa_collection,
          'Byurakan 1m Schmidt'::TEXT AS ssa_instrument,
          'survey'::TEXT AS ssa_datasource,
          'archival'::TEXT AS ssa_creationtype,
          '2007A&amp;A...464.1177M'::TEXT AS ssa_reference,
          NULL::REAL AS ssa_fluxStatError,
          NULL::REAL AS ssa_fluxSysError,
          'UNCALIBRATED'::TEXT AS ssa_fluxcalib,
          50e-10::REAL AS ssa_binSize,
          NULL::REAL AS ssa_spectStatError,
          NULL::REAL AS ssa_spectSysError,
          'ABSOLUTE'::TEXT AS ssa_speccalib,
          50e-10::REAL AS ssa_specres,
          NULL::spoly AS ssa_region,
          magb, magr, plate, ra, dec, t_min, t_max
        FROM \schema.raw_spectra
        LEFT OUTER JOIN \schema.platemeta
        ON (plateid=plate)
    )
    </viewStatement>
    <FEED source="//procs#declare-indexes-from" sourceTables="raw_spectra"/>
  </table>

  <coverage>
    <updater sourceTable="ssa"/>
    <temporal>39165 44374</temporal>
    <spectral>2.879e-19 6.355e-19</spectral>
  </coverage>

  <data id="make_ssa_view" auto="False">
    <make table="ssa"/>
  </data>

  <table id="platemeta" onDisk="True" primary="plateid"
      adql="hidden">
    <meta name="description">Metadata for the plates making up the
    Byurakan spectral surveys, obtained from the WFPDB.</meta>
    <index columns="epoch"/>
    <index columns="t_min"/>
    <index columns="t_max"/>

    <column name="plateid" type="text"
      ucd="meta.id;meta.main"
      tablehead="Plate"
      description="Identifier of the plate; this is 'fbs' plus the plate
        number."
      verbLevel="1"/>
    <column name="epoch" type="double precision"
      unit="d" ucd="time.epoch"
      tablehead="Date Obs."
      description="Date of observation from WFPDB (this probably does not
        include the time)."
      verbLevel="1"/>
    <column name="exptime"
      unit="s" ucd="time.duration;obs.exposure"
      tablehead="Exp. Time"
      description="Exposure time from WFPDB."
      verbLevel="1"/>
    <column original="//obscore#ObsCore.t_min"/>
    <column original="//obscore#ObsCore.t_max"/>

    <column name="emulsion" type="text"
      ucd="instr.plate.emulsion"
      tablehead="Emulsion"
      description="Emulsion used in this plate from WFPDB."
      verbLevel="1"/>
    <column name="ra_center"
      ucd="pos.eq.ra" unit="deg"
      tablehead="Center RA"
      description="Center of plate in RA (ICRS)"
      verbLevel="1"/>
    <column name="dec_center"
      ucd="pos.eq.dec" unit="deg"
      tablehead="Center Dec"
      description="Center of plate in Dec (ICRS)"
      verbLevel="1"/>
  </table>

  <data id="import_platemeta">
    <!-- we pull data from the GAVO DC's wfpdb mirror.  It might pay
      to re-run this now and then as WFPDB data gets updated.. -->
    <recreateAfter>make_ssa_view</recreateAfter>
    <recreateAfter>make_tap_view</recreateAfter>
    <sources item="http://dc.g-vo.org/tap/sync"/>
    <embeddedGrammar>
      <iterator>
        <code>
          from urllib.parse import urlencode
          from gavo import votable
          from gavo.stc import jYearToDateTime, dateTimeToMJD

          f = utils.urlopenRemote(self.sourceToken, data=urlencode({
            "LANG": "ADQL",
            "QUERY": "select object as plateid, epoch, exptime, emulsion,"
              " raj2000, dej2000"
              " from wfpdb.main"
              " where object is not null and object!=''"
              "   and instr_id='BYU102A'"
              "   and method='objective prism'"}))

          data, metadata = votable.load(f)
          for row in metadata.iterDicts(data):

            # HACK: duplicates in WFPDB.  See README
            if row["plateid"]=="NPS":
              continue
            if row["plateid"]=="FBS 0966" and int(row["epoch"])==1974:
              row["plateid"] = "FBS 0966a"
            if row["plateid"]=="FBS 0326" and row["epoch"]>1971.05:
              row["plateid"] = "FBS 0326a"
            if row["plateid"]=="FBS 0449" and row["epoch"]>1971.38:
              row["plateid"] = "FBS 0449a"


            row["epoch"] = dateTimeToMJD(jYearToDateTime(row["epoch"]))
            row["plateid"] = row["plateid"].replace("FBS ", "fbs")
            row["ra_center"] = row["raj2000"]
            row["dec_center"] = row["dej2000"]
            yield row
        </code>
      </iterator>
    </embeddedGrammar>

    <make table="platemeta">
      <rowmaker idmaps="*">
        <map key="t_min" nullExcs="TypeError">@epoch-@exptime/43200</map>
        <map key="t_max" nullExcs="TypeError">@epoch+@exptime/43200</map>
      </rowmaker>
    </make>
  </data>


  <table id="spectra" onDisk="True" adql="True">
    <meta name="description">This table contains basic metadata as well
      as the spectra from the Digital First Byurakan Survey (DFBS).
    </meta>
    <meta name="table-rank">1</meta>

    <publish sets="ivo_managed,local"/>

    <LOOP listItems="accref plate specid ra dec pos sp_class px_length
        flux magb magr snr lam_min px_x px_y pos_ang">
      <events>
        <column original="raw_spectra.\item"/>
      </events>
    </LOOP>
    <LOOP listItems="epoch exptime emulsion">
      <events>
        <column original="platemeta.\item"/>
      </events>
    </LOOP>

    <column name="spectral" type="real[]"
      unit="m" ucd="em.wl"
      tablehead="Spectral[]"
      description="Spectral points of the extracted spectrum (wavelengths)
        as an array (the points are the same for all spectra; the array
        in this column is cropped at the blue end to match the length of flux)."
      verbLevel="30"/>
    <column name="cutout_link" type="text"
    	ucd="meta.ref.url"
    	tablehead="Image"
    	description="Cutout of the image this spectrum was extracted from"
    	verbLevel="15"/>

    <viewStatement>
      CREATE VIEW \curtable AS (
        SELECT \colNames
        FROM (
          SELECT
            a.*,
            b.*,
            ('{\spectralBins}'::float[])[1:array_length(a.flux, 1)] AS spectral,
            '\getConfig{web}{serverURL}/dfbsspec/q/cutout/qp/'
            	|| specid as cutout_link
          FROM
            \schema.raw_spectra as a
            JOIN \schema.platemeta as b
            ON (plate=plateid)) AS t)
    </viewStatement>
    <FEED source="//procs#declare-indexes-from"
      sourceTables="raw_spectra platemeta"/>
  </table>

  <data id="make_tap_view">
    <make table="spectra"/>
  </data>

  <table id="spectrum">
    <mixin ssaTable="ssa"
      fluxDescription="Relative Flux"
      spectralDescription="Wavelength"
      >//ssap#sdm-instance</mixin>
  </table>

  <data id="build_sdm_data" auto="False">
    <embeddedGrammar>
      <iterator>
        <code>
          with base.getTableConn() as conn:
            res = list(conn.query(
              "select spectral, flux from dfbsspec.spectra"
              "  where accref=%(accref)s",
              {"accref": self.sourceToken["accref"]}))[0]

          for lam, flx in zip(*res):
            yield {"spectral": lam, "flux": flx}
        </code>
      </iterator>
    </embeddedGrammar>
    <make table="spectrum">
      <parmaker>
        <apply procDef="//ssap#feedSSAToSDM"/>
      </parmaker>
    </make>
  </data>

  <service id="sdl" allowed="dlget,dlmeta,static">
    <meta name="title">DFBS Datalink Service</meta>

    <property name="staticData">data</property>

    <datalinkCore>
      <descriptorGenerator procDef="//soda#sdm_genDesc">
        <bind name="ssaTD">"\rdId#ssa"</bind>
      </descriptorGenerator>
      <dataFunction procDef="//soda#sdm_genData">
        <bind name="builder">"\rdId#build_sdm_data"</bind>
      </dataFunction>
      <FEED source="//soda#sdm_plainfluxcalib"/>
      <FEED source="//soda#sdm_format"/>

      <metaMaker semantics="#progenitor">
        <code>
          if descriptor.pubDID is None:
            return

          specId = descriptor.pubDID.split("/")[-1]
          yield descriptor.makeLink(
            '\getConfig{web}{serverURL}/dfbsspec/q/cutout/qp/'+specId,
            contentType="application/fits",
            contentLength=200*200*16,
            description="Cutout of the objective prism spectrum this"
              " was generated from.")
        </code>
      </metaMaker>
    </datalinkCore>
  </service>

  <service id="web">
    <meta name="title">Digitized First Byurakan Survey Browser Interface</meta>
    <dbCore queriedTable="ssa">
      <condDesc buildFrom="ssa_location"/>
      <condDesc buildFrom="magb"/>
    </dbCore>
    <outputTable
      autoCols="accref,accsize,ssa_location,ssa_dstitle,magr,magb, ssa_snr"/>
  </service>

  <service id="getssa" allowed="ssap.xml,form">
    <meta name="shortName">DFBS SSAP</meta>
    <meta name="title">Digitized First Byurakan Survey (DFBS) Spectra
      Query Service</meta>
    <meta name="ssap.dataSource">pointed</meta>
    <meta name="ssap.testQuery">MAXREC=1</meta>
    <meta name="ssap.creationType">archival</meta>
    <meta name="ssap.complianceLevel">query</meta>

    <publish sets="ivo_managed" render="ssap.xml"/>
    <publish sets="ivo_managed,local" render="form" service="web"/>

    <ssapCore queriedTable="ssa">
      <FEED source="//ssap#hcd_condDescs"/>
    </ssapCore>
  </service>

  <service id="preview" allowed="qp">
    <meta name="title">DFBS spectra preview maker</meta>
    <property name="queryField">specid</property>
    <pythonCore>
      <inputTable>
        <inputKey name="specid" type="text" required="True"
          description="ID of the spectrum to produce a preview for"/>
      </inputTable>
      <coreProc>
        <setup>
          <code>
            from gavo.helpers.processing import SpectralPreviewMaker
            from gavo import svcs
          </code>
        </setup>
        <code>
          with base.getTableConn() as conn:
            res = list(conn.query("SELECT spectral, flux"
              " FROM \schema.spectra"
              " WHERE specid=%(specid)s",
              inputTable.args))

          if not res:
            raise svcs.UnknownURI("No such spectrum known here")

          return ("image/png", SpectralPreviewMaker.get2DPlot(
            list(zip(res[0][0], res[0][1])), linear=True))
        </code>
      </coreProc>
    </pythonCore>
  </service>

  <service id="cutout" allowed="qp">
    <!-- This uses the plates from dfbs/q and will break if they're
    not present -->
    <meta name="title">DFBS spectra plate cutout service</meta>
    <property name="queryField">specid</property>
    <pythonCore>
      <inputTable>
        <inputKey name="specid" type="text" required="True"
          description="ID of the spectrum to generate a cutout for"/>
      </inputTable>
      <coreProc>
        <setup>
          <code>
            from gavo import svcs
          </code>
        </setup>
        <code>
          with base.getTableConn() as conn:
            res = list(conn.query(
              "SELECT plate, pos, px_length, pos_ang"
              " FROM \schema.raw_spectra"
              " WHERE specid=%(specid)s",
              inputTable.args))
          if not res:
            raise svcs.UnknownURI("No such spectrum known here")

          plate, pos, px_length, pos_ang = res[0]
          x, y = pos.x/utils.DEG, pos.y/utils.DEG,
          pos_ang = pos_ang*utils.DEG
          w = 0.01 # degrees
          h = 0.05 # degrees
          h0 = 0.01 # degrees

          raise  svcs.Found(
            "dfbs/q/dl/dlget?ID=plate/%s"
            "&amp;POLYGON=%s%%20%s%%20%s%%20%s%%20%s%%20%s%%20%s%%20%s"%(
              plate,
              x-h0*math.cos(pos_ang)-w*math.sin(pos_ang),
              y+h0*math.sin(pos_ang)-w*math.cos(pos_ang),
              x-h0*math.cos(pos_ang)+w*math.sin(pos_ang),
              y+h0*math.sin(pos_ang)+w*math.cos(pos_ang),
              x+h*math.cos(pos_ang)-w*math.sin(pos_ang),
              y-h*math.sin(pos_ang)-w*math.cos(pos_ang),
              x+h*math.cos(pos_ang)+w*math.sin(pos_ang),
              y-h*math.sin(pos_ang)+w*math.cos(pos_ang)))
        </code>
      </coreProc>
    </pythonCore>
  </service>

  <regSuite title="DFBS regression">
    <regTest title="Spectra metadata plausible via SSA">
      <url REQUEST="queryData" POS="211.068,44.899395"
        TIME="1969-07-01/1969-07-31"
        SIZE="0.001">getssa/ssap.xml</url>
      <code>
        row = self.getFirstVOTableRow()
        self.assertEqual(row['ssa_location'].asSODA(),	
          '211.0680249982 44.899394444')
        self.assertEqual(row["ssa_dstitle"],
          'DFBSJ140416.32+445357.8 spectrum from fbs0017')
        self.assertEqual(row["ssa_bandpass"], "IIAF bkd")
        self.assertEqual(row["ssa_length"], 112)
        self.assertAlmostEqual(row["ssa_specstart"], 3.316E-7)
        self.assertAlmostEqual(row["ssa_dateObs"], 40407, places=5)
      </code>
    </regTest>

    <regTest title="DFBS previews present">
      <url httpHonorRedirects="True">/getproduct/dfbsspec/q/fbs0017-141024.11+445238.4?preview=True</url>
      <code>
        self.assertHasStrings("PNG", "IDATx")
      </code>
    </regTest>

    <regTest title="Datalink dataset generation works">
      <url ID="dfbsspec/q/fbs0017-140416.32+445357.8"
        >sdl/dlget</url>
      <code>
        self.assertHasStrings('utype="spec:Spectrum"', 'name="citation"',
          'value="UNCALIBRATED"')
        rows = self.getVOTableRows()
        self.assertAlmostEqual(rows[-1]["spectral"], 3.316e-07)
        self.assertAlmostEqual(rows[-1]["flux"], -5.02)
      </code>
    </regTest>

    <regTest title="DFBS metadata has progenitor link">
      <url ID="dfbsspec/q/fbs0017-140416.32+445357.8"
        >sdl/dlmeta</url>
      <code>
        for row in self.getVOTableRows():
          if row["semantics"]=="#progenitor":
            break
        else:
          self.assertFalse("No #progenitor link found.")

        self.assertEqual(row["content_type"], "application/fits")
        self.assertTrue(row["access_url"].endswith(
          "dfbsspec/q/cutout/qp/fbs0017-140416.32+445357.8"))
      </code>
    </regTest>


    <regTest title="spectra TAP table present">
      <url parSet="TAP" QUERY="SELECT * FROM dfbsspec.spectra
        WHERE specid='fbs0018-144128.14+453624.1'"
        >/tap/sync</url>
      <code>
        rows = self.getVOTableRows()
        self.assertEqual(len(rows), 1)
        row = rows[0]
        self.assertAlmostEqual(row["lam_min"],  3.2060000e-07)
        self.assertAlmostEqual(row["dec"],  45.606705555556)
        self.assertEqual(row["emulsion"],  "IIAF bkd")
        self.assertAlmostEqual(row["flux"][2], 16.26, 5)
        self.assertAlmostEqual(row["spectral"][2], 6.682e-7)
        self.assertEqual(len(row["spectral"]), len(row["flux"]))
      </code>
    </regTest>

    <regTest title="Postage stamp redirect works">
      <url httpHonorRedirects="True"
        >cutout/qp/fbs0017-140416.32+445357.8</url>
      <code>
        self.assertHasStrings("DATEORIG= '1969-07-05'",
          "NAXIS2  =                   70",
          b"\\x06\\xd5\\x06\\x49\\x06\\x49")
      </code>
    </regTest>
  </regSuite>

  <regSuite title="DFBS DaCHS Regression">
    <regTest title="Sums of different-length arrays padded with NULLs">
      <url parSet="TAP" QUERY="WITH sample AS (
        SELECT specid, spectral FROM dfbsspec.spectra
        WHERE specid IN ('fbs0017-141621.86+482141.3',
          'fbs0017-141616.00+482534.2'))
        SELECT a.specid || '-' || b.specid as id,
          a.spectral+b.spectral as ss
        FROM sample as a JOIN sample as b
        ON (a.specid!=b.specid)">/tap/sync</url>
      <code>
        row = self.getFirstVOTableRow(rejectExtras=False)
        self.assertEqual(len(row["ss"]), 130)
        allNULL = row["ss"][-6:]
        for val in allNULL:
          self.assertTrue(val is None)
      </code>
    </regTest>
  </regSuite>
</resource>
<!-- vim:et:sta:sw=2
-->
