Package {skyscapeR}


Type: Package
Title: Data Analysis and Visualization for Skyscape Archaeology
Version: 2.0.0
Description: Investigate how archaeological sites and structures relate to the landscape and sky. Reduce field measurements, reconstruct local horizons from surveys and elevation models, and propagate measurement uncertainty into distributions of astronomical declination. Explore celestial positions, visibility and seasonal events at modern and prehistoric epochs, visualise the sky above a site horizon, and compare orientation distributions with random or specified null models (Silva 2020 <doi:10.1016/j.jas.2020.105138>, Silva and Lomsdalen 2025 <doi:10.1007/s12520-025-02208-4>).
URL: https://github.com/stonexsky/skyscapeR, https://stonexsky.github.io/skyscapeR/
BugReports: https://github.com/stonexsky/skyscapeR/issues
Depends: R (≥ 4.1), swephR
Imports: parallel, methods, oce (≥ 1.8-4), utils, tools, stats, graphics, grDevices, zoo
Additional_repositories: https://rstub.r-universe.dev
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
Copyright: See inst/COPYRIGHTS (COPYRIGHTS in the installed package) for bundled data attribution and licence notices.
Encoding: UTF-8
LazyData: true
LazyDataCompression: xz
Suggests: swephRdata, terra (≥ 1.7-65), xml2, png, httr2 (≥ 1.0.0), knitr, rmarkdown, readxl
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-28 12:38:25 UTC; agent
Author: Fabio Silva [aut, cre], Billy Finnimore [ctb], Victor Reijs [ctb], Rita Gautschy [ctb]
Maintainer: Fabio Silva <fsilva@stonexsky.com>
Repository: CRAN
Date/Publication: 2026-12-01 23:20:09 UTC

skyscapeR: Data Analysis and Visualization for Skyscape Archaeology

Description

Analyse the directions of archaeological structures in relation to the local horizon and to proposed celestial or terrestrial targets. The package supports reduction of field measurements, coordinate transformation, visibility modelling and simulation-based significance tests.

Details

For a worked example from field measurements through to a multi-site test, open vignette("skyscapeR", package = "skyscapeR"). Site coordinates are latitude and longitude in decimal degrees (north and east positive), followed by elevation in metres where required. True bearings are clockwise from north.

Recommended astronomical data

Install swephRdata if you need astronomical positions and do not already have covering Swiss Ephemeris files. Solar, lunar, planetary and fixed-star positions, and events derived from them, require Swiss Ephemeris files covering the requested body and epoch. This applies to modern and prehistoric dates. Install once, then restart R:

install.packages("swephRdata", repos = "https://rstub.r-universe.dev", type = "source")

Alternatively, set SE_EPHE_PATH to existing Swiss Ephemeris data directories before loading skyscapeR. The bundled star catalogue supplies stellar identifiers; it cannot replace the planetary data used for stellar positions. Missing coverage stops the calculation with installation instructions. Users can work with measured horizons, calendar conversions and orientation statistics without these files.

How do I reduce a field observation to a true bearing?

Convert degrees, minutes and seconds with ten. For a compass survey, estimate magnetic declination with mag.dec and apply the correction with reduct.compass. For a solar sight, sunAz gives the solar bearing and reduct.theodolite reduces the instrument readings. Display the corrected bearings with plotAzimuth.

How do I obtain, inspect and export a site horizon?

Build or import. Use createHor for survey bearings or a DEM, importPanorama for a sky-masked photograph and importPeakFinder for a PeakFinder landscape. For HeyWhatsThat, request a panorama with createHWT or retrieve one by ID with downloadHWT.

Inspect or share. Add reconstructed structures with horFeature, plot the horizon, or read its altitude at a bearing with hor2alt. Use exportPanorama for an equirectangular PNG or exportStellarium for a landscape archive. To move an image-backed horizon, keep the PNG with the saved object and reconnect it with relinkHor.

Which declinations does a structure face, given measurement uncertainty?

For a single sightline, use az2dec with the site and horizon altitude. For uncertain bearings, construct distributions with az.pdf and transform them with coordtrans. Use dec.pdf when the measurements are already in declination. Inspect individual curves with plot(pdf), sum them with spd and display the result with plot(summed). Use hpdi to identify the highest-density intervals and plotBars to display orientation intervals against candidate declinations.

Could the observed pattern arise under a null hypothesis?

Use randomTest for uniformly random azimuths and modelTest for a specified distribution of azimuths or declinations. Inspect the global test and local intervals with print(fit) and plot(fit). For independent structures with a prespecified probability of a hit, bernoulli.trial gives an exact-count or upper-tail probability. pval2stars formats a probability for display.

Which celestial targets fit the sightline and epoch?

Screen a declination interval and year range with findTargets. For solar limits use jS and dS at the June and December solstices and eq at the equinox. spatial.equinox uses the local horizon; zenith and antizenith give the overhead and opposite solar limits. For northern and southern lunar standstill limits use nMjLX and sMjLX (major) or nmnLX and smnLX (minor). obliquity supplies the epoch-dependent tilt and parallax.corr the approximate site correction. planet.extremes estimates planetary limits. Resolve stellar names with star.names and obtain coordinates with star. Prepare targets for plotting with skyObject.

When and where could an observer see a celestial event?

Use body.position for coordinates at an instant, orbit for a path and riseset for crossings of the local horizon. solar.date finds dates when the Sun reaches a specified declination. Use moonphase for lunar illumination, EFM for equinoctial full moons and CC for solstitial crescent crossovers. Model seasonal stellar visibility with star.phases and display the seasons with plot(phases). Use sketchSky or stellariumSky for a horizon plot, step through time with skyStep or use planisphere for a wider view. constellations supplies the constellation line segments.

How do I specify historical dates and observing conditions?

Inspect or set the session defaults with skyscapeR.vars. Assemble a timestamp with timestring, convert it to a UT Julian date with time2jd and convert back with jd2time. Use BC.AD to label an astronomical year and long.date to format a month and day. Year zero is 1 BC. Supply the intended calendar and an explicit UTC or fixed offset for dates before 1900.

Which datasets can I use for a worked analysis?

Pair malta_entrances with malta_horizons to connect temple entrance bearings with DEM-derived site horizons. To follow a single sightline and compare groups of Maltese temples, open vignette("skyscapeR", package = "skyscapeR").

Console output

Set verbose = FALSE on functions that offer it to silence routine updates. For a quiet session, set options(skyscapeR.verbose = FALSE). Warnings and errors remain visible. Progress bars normally appear in interactive sessions; DEM tracing also accepts an explicit progress switch. Use print(fit) for significance results in the console or a report.

Recording an analysis

Preserve original measurements, horizon profiles, feature layers and external PNG files with the analysis script. Record the package and ephemeris versions, calendar, timezone, refraction, uncertainty model, grid settings and simulation seed. Refine numerical sampling and compare representative cases using matched conventions. When interpreting a reconstruction, distinguish predicted events from visibility under local observing conditions. See EFM, CC and star.phases for the astronomical selection and empirical visibility assumptions.

Updating older scripts

The README migration guide identifies analyses and figures to rerun. Saved results retain their original numbers until recalculated. skyObject is the primary target constructor; sky.objects remains a compatibility alias. The README migration guide documents the removal of retired functions, including sigTest() and curvigram().

Author(s)

Fabio Silva (fsilva@stonexsky.com). Contributors: Billy Finnimore, Victor Reijs and Rita Gautschy.

See Also

skyscapeR.vars, createHor, az.pdf, dec.pdf, coordtrans, randomTest, modelTest


Convert an astronomical year to a BC or AD label

Description

Label an astronomical year in historical BC or AD notation when reporting an epoch.

Usage

BC.AD(year)

Arguments

year

Numeric astronomical year or vector of years. Year zero is 1 BC. Historical labels such as "3700 BC" are accepted by astroYear.

Details

Astronomical dating includes a year zero, whereas historical BC and AD labels run directly from 1 BC to AD 1. Positive years retain their number and receive AD. For zero or a negative year, subtract the astronomical year from one and append BC. The conversion works element by element and changes only the label, not the calendar or instant.

Value

Character labels for astronomical years. Year 0 is 1 BC and year -1 is 2 BC.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

time2jd, jd2time, timestring, long.date

Examples

BC.AD(100)
BC.AD(0)
BC.AD(-1)
BC.AD(-99)
BC.AD(-100)

Crescent crossovers of the Sun and Moon

Description

Identify the first observable seasonal reversal in the relative rising or setting positions of the Sun and a lunar crescent. These events can be compared with archaeological orientations and need not occur close to a solstice.

Usage

CC(
  year,
  loc,
  season = "winter",
  crescent = "first",
  simulation = "SIM1",
  timezone = skyscapeR.env$timezone,
  calendar = skyscapeR.env$calendar,
  refraction = skyscapeR.env$refraction,
  atm = skyscapeR.env$atm,
  temp = skyscapeR.env$temp
)

Arguments

year

One integer year, two ascending endpoints, or a vector of years. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude, longitude and elevation (degrees, degrees, metres), or a skyscapeR.horizon object.

season

Either "winter" (default) or "summer".

crescent

Either "first" (default, waxing/set) or "last" (waning/rise).

simulation

"SIM1" (default) or "SIM2"; see Details.

timezone

Output and observing-day timezone. Defaults to package settings. Use UTC or a fixed offset before 1900.

calendar

"G" for Gregorian or "J" for Julian dates. Defaults to package settings.

refraction

Logical; use atmospheric refraction. Defaults to package settings.

atm

Atmospheric pressure in mbar. Defaults to package settings.

temp

Air temperature in degrees Celsius. Defaults to package settings.

Details

Crescent crossovers describe a change in the relative horizon positions of the luminaries across successive lunations. First (waxing) crescents are compared at sunset and moonset; last (waning) crescents at sunrise and moonrise. The method follows Silva and Pimenta (2012), sections 2.1–2.2. Seasons use the paper's northern-hemisphere names: summer means the June-solstice crossover, winter the December-solstice crossover, also for southern-hemisphere locations.

For each conjunction, days are searched forwards for the first crescent and backwards for the last crescent. Visibility is evaluated at sunset or sunrise, respectively, using Caldwell and Laney's criterion: lower-limb lunar altitude plus one third of the Sun–Moon angular separation must be at least 11.3 degrees. The lower-limb altitude is topocentric. The arc of light is the geocentric Sun–Moon separation, as explicitly defined by Caldwell and Laney; it excludes atmospheric refraction. The lower limb is calculated from the instantaneous lunar distance and a lunar radius of 1737.4 km. With refraction enabled, the centre altitude is apparent and the angular radius is subtracted from it. This is an empirical visibility prediction, not a guarantee under actual weather or extinction.

SIM1 tests only the first qualifying evening or last qualifying morning of each lunation. SIM2 also tests the following evening or preceding morning, respectively. The original visibility day is preferred if it already meets the crossover condition. Dates are searched within eight civil days of conjunction and must remain crescent (elongation below 90 degrees).

Each body's own centre-disc horizon event supplies its azimuth. The shortest signed difference Moon minus Sun is negative after a June crossover and positive after a December crossover, for both event types, with bearings clockwise from north. The starting conjunction is two lunations before the last conjunction at or before the solstice (the beginning of the lunation containing it). This can start nearly three synodic months before the solstice; it is not equivalent to starting at the first conjunction after solstice minus two synodic months. From there, successive lunations are searched for the first eligible crescent with the required strict ordering; exact equality does not qualify. The preceding eligible difference is retained for inspection but is not an additional selection condition in the published algorithm. Missing lunations are skipped. Conjunctions are searched until 150 days after the solstice; failure gives NA. Later qualifying lunations are counted in diagnostics but do not replace the first. Observations may fall in the next calendar year.

A coordinate vector uses a zero-altitude astronomical horizon. A horizon object uses its horizon for both rise/set events and a separate lower-limb clearance check at the visibility assessment. The visibility formula still uses altitude above the astronomical horizontal, not altitude above the terrain. This horizon extension was not calibrated in the original paper. Events use the existing centre-disc convention of riseset, including for the Sun.

Swiss Ephemeris supplies apparent astronomical positions (light-time and aberration corrections), with atmospheric refraction controlled separately. Returned declinations are geocentric and without atmospheric refraction, as in Figure 4 of the paper. Individual event selections do not yet reproduce every original simulation. The starting-window convention and differences in the 40-degree N series remain under validation. Agreement of a smoothed distribution does not imply agreement of every year's selected crescent. Inspect the returned dates, visibility margins and azimuth differences before interpreting a particular event; the cause of all discrepancies is not established. Years use astronomical numbering (0 is 1 BCE). Two ascending year endpoints expand inclusively; longer vectors are evaluated as supplied. The year labels the Gregorian year of the solstice, so a selected observation may occur in an adjacent calendar year. The calendar argument controls date display and civil-day parsing. No PNG or copy of the input horizon is stored in the output.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A list with Event, paired Moon and Sun data frames (year, date, time, azimuth, declination, UT Julian date), and a diagnostics data frame. Diagnostics include status, solstice and conjunction JDs, visibility-assessment JD, illuminated fraction, lower-limb altitude, elongation, visibility margin, signed azimuth difference, preceding difference, number of qualifying lunations, and day offset (0 for SIM1's day, 1 for SIM2's additional day). All angles are degrees. Missing results retain the requested year, use NA for observations and issue a warning. settings records conventions.

Comparison with the original simulations

For SIM1, 5,024 of 5,136 events in the supplied 1620–2047 series at latitudes 0, 60 N and 60 S agree within 0.02 degrees in lunar declination. This comparison uses a level horizon, longitude 0, elevation 400 m, UTC, Gregorian dates, refraction, pressure 1013.25 mbar and temperature 15 degrees Celsius. The original 40-degree N series has additional systematic offsets. Of the 112 discrepancies outside that series, inferred matching dates suggest differences in the lunation search window and first/last crescent selection. Some lie close to the visibility threshold. Alternative window and solar-limb conventions improve some cases but disrupt others that already agree, so no replacement convention has been adopted. The exact original settings remain unresolved; the paper does not specify all atmospheric inputs. Inspect the diagnostics before interpreting individual events. Agreement with simulation tables is not independent observational validation, and these SIM1 counts do not establish the accuracy of SIM2.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific validation

A07 examines independent crossover selection and sensitivity to the illumination cutoff. A07 scientific validation.

Scientific checks

References

Silva, F. and Pimenta, F. (2012). The Crossover of the Sun and the Moon. Journal for the History of Astronomy 43(2), 191–208. doi:10.1177/002182861204300204.

Caldwell, J. and Laney, C. D. (2001). First visibility of the lunar crescent. African Skies 5, 15–23. The authors' online version defines dalt and arcl: https://astronomycenter.net/pdf/saao_2001.pdf.

See Also

EFM, moonphase, riseset, body.position, createHor

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  CC(year=2026, loc=c(40, 0, 400), timezone="UTC")
  ## Not run: 
  CC(year=c(2000, 2018), loc=c(40, 0, 400), season="summer", crescent="last",
  simulation="SIM2", timezone="UTC")
  CC(year=-2999, loc=c(40, 0, 400), timezone="UTC")
  
## End(Not run)
}

Find equinoctial full moonrises and moonsets

Description

Identify the near-full Moon whose rising or setting position crosses that of the Sun around the spring or autumn equinox.

Usage

EFM(
  year,
  loc,
  season = "spring",
  rise = TRUE,
  min.phase = 0.99,
  timezone,
  calendar,
  refraction,
  atm,
  temp
)

Arguments

year

Astronomical year or years. Can be either a single value (the year), Historical labels such as "3700 BC" are accepted by astroYear. two values (range of years), or a vector of years.

loc

This can be either a skyscapeR.horizon object, or a vector with the latitude, longitude and elevation of the site, in this order.

season

Either 'spring' or 'autumn'. Default is 'spring'.

rise

Logical to choose whether to calculate Equinoctial Full Moon rises or sets. Defaults to TRUE.

min.phase

Minimum illuminated fraction of the Moon, from 0 to 1. The default 0.99 means 99 percent illumination.

timezone

Timezone for civil timestamps. Use UTC or a fixed offset for dates before 1900. See time2jd for named zones and offsets.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

Details

Silva and Pimenta (2012) identify the crossover by the first near-full Moon on the seasonal side of the Sun. Spring and autumn refer to the March and September equinoxes. At spring moonrise the lunar azimuth must exceed the solar azimuth, and at spring moonset it must be smaller. Autumn reverses both inequalities. Bearings are topocentric, clockwise from north.

The search runs chronologically from 60 days before to 65 days after the astronomical equinox. Moonrise is paired with the first sunrise on the same local civil date. Moonset is paired with the most recent sunset before it, considering the first solar centre crossing on the current and preceding local civil dates. A candidate without such a sunset is skipped. Local-day boundaries account for timezone changes, including daylight saving time. A coordinate vector specifies a level horizon. A horizon object supplies the horizon for both bodies. Illumination is tested at the lunar event itself. A date qualifies as soon as the illumination and strict bearing conditions both hold. A lower illumination threshold can select an earlier lunation. If no date qualifies the function reports the year and event and stops.

Dates and clock times use the supplied timezone and calendar. Changing the timezone can change which events share a civil date. Declinations use the package coordinate setting (topocentric by default). For comparison with Figure 3 of Silva and Pimenta, request geocentric declinations with skyscapeR.vars(dec="geo"). Event selection uses topocentric bearings in either output frame.

Value

A list with an Event label and Moon and Sun data frames. Each row gives year, date, time, azimuth and declination for the selected rising or setting event. Angles are in degrees.

Comparison with the original simulations

With the corrected preceding-sunset pairing, 2,562 of 2,568 moonsets in the supplied 1620–2047 series at latitudes 0, 60 N and 60 S agree within 0.02 degrees in lunar declination. The comparison uses a level horizon, longitude 0, elevation 400 m, UTC, Gregorian dates, geocentric declinations, refraction, pressure 1013.25 mbar, temperature 15 degrees Celsius and the default illumination threshold. Five remaining cases lie just above the 0.99 illumination boundary; one lies about 0.002 degrees beyond the azimuth crossover boundary. The original series selects the following morning in each case. Thresholds have not been tuned to reproduce those selections.

The original 40-degree N series retains systematic coordinate differences. Diagnostic comparisons suggest a different coordinate-conversion or timing convention, but the original settings have not been established. Agreement with these simulation tables is not independent observational validation. The paper does not specify all atmospheric settings; the values above describe this comparison, not confirmed settings of the original simulations.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Scope of the event model

The illumination fraction is a selection criterion, not a naked-eye detection model. The calculation does not include weather, sky brightness or extinction. It uses centre crossings rather than the first appearance of the upper limb. Only the first qualifying event is returned, so changes in illumination threshold, civil-day convention or horizon can change the selected lunation. Remaining differences from the original simulations are described above. Numerical precision does not establish agreement with a published distribution. Preserve all inputs when comparing series.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific validation

A07 examines independent crossover selection and sensitivity to the illumination cutoff. A07 scientific validation.

Scientific checks

References

Silva, F. and Pimenta, F. (2012). The Crossover of the Sun and the Moon. Journal for the History of Astronomy 43. doi:10.1177/002182861204300204.

See Also

CC, spatial.equinox, zenith, antizenith, solar.date, findTargets, planet.extremes

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Spring Full Moon at latitude 35 degrees north in the year 2018
  EFM(year=2018, loc=c(35,-8,100))
  
  # Autumn Full Moons over a 3 year period
  ## Not run: 
  EFM(season='autumn', year=c(2018,2020), loc=c(35,-8,100))
  
## End(Not run)
}

Estimate solar declination at the anti-zenith

Description

Determine the solar declination associated with the point directly beneath an observer, where the Sun can attain that declination.

Usage

antizenith(
  loc,
  parallax = 0.00224,
  altitude = -90,
  year = skyscapeR.env$cur.year
)

Arguments

loc

This can be either the latitude of the location, or a skyscapeR.horizon object.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

altitude

Altitude used in the approximate parallax correction. Defaults to -90 degrees.

year

Astronomical year used to determine the tropical latitude limit.

Details

The direction opposite the zenith corresponds geometrically to minus the site latitude. The function checks the latitude against the obliquity of the requested epoch. At the geometric anti-zenith the altitude is minus 90 degrees and parallax vanishes. An explicitly supplied altitude invokes the approximate correction at that altitude. It returns NULL outside that band. This is a target declination for comparison with orientations, not an observable solar transit below ground.

Value

Solar declination in degrees with the requested parallax correction, or NULL when the latitude falls outside the solstitial limits used by the function.

Validation

A05 verified the geometric anti-zenith declination and tropical-boundary eligibility at two epochs. See the A05 check in the technical manual.

Scientific checks

See Also

jS, dS, eq, zenith, spatial.equinox, parallax.corr

Examples

# Anti-zenith sun declination for Mexico City:
antizenith(19.419)

# The same location supplied as a horizon object:
hor <- createHor(c(0,90,180,270,360), c(0,2,1,3,0),
                 loc=c(19.419,-99.133,2240))
antizenith(hor)

# There is no anti-zenith solar phenomenon in London:
antizenith(51.507)

Convert a historical year to astronomical numbering

Description

Specify the epoch of an observation with historical era labels.

Usage

astroYear(x)

Arguments

x

Numeric astronomical years, character integer years, or historical labels.

Details

Astronomical years include zero. Historical BC or BCE years convert by subtracting the historical year from one. AD and CE years keep their value. Era labels are case-insensitive and follow a positive whole year.

Value

Numeric astronomical years in input order.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

BC.AD, timestring

Examples

astroYear(c("3700 BC", "1 BCE", "1 AD", "2026 CE"))

Represent measured azimuths as probability densities

Description

Represent uncertainty in a measured orientation before comparing it with other bearings or transforming it to declination.

Usage

az.pdf(
  az,
  unc = NULL,
  pdf = "normal",
  name,
  .res = 0.01,
  .cutoff = 1e-05,
  verbose = TRUE,
  taper = NULL,
  survey.sd = 0.5,
  lower = NULL,
  upper = NULL
)

Arguments

az

True bearings clockwise from north, in degrees. For triangular, the preferred bearing (mode).

unc

One width or one per observation. Standard deviation for normal, outer half-width for uniform, Epanechnikov or symmetric triangular, and core half-width for tapered uniform or uniform convolved with normal. Omit when supplying triangular limits. See 'Choosing a measurement model'.

pdf

One measurement family per call. See 'Choosing a measurement model' for all six names. The default is "normal". The historical abbreviations "n" and "u" are accepted and names are case-insensitive.

name

Optional labels in the same order as the measurements.

.res

Spacing of the output bearing grid in degrees. Default 0.01.

.cutoff

Minimum density retained on the output grid. Default 1e-5.

verbose

Logical. Display progress or informational messages. Default TRUE.

taper

Outer extension on each side of a tapered uniform core, in degrees. Required for "tapered_uniform". Zero gives a uniform density.

survey.sd

Standard deviation of independent bearing or declination error, in degrees, for "uniform_normal". Defaults to 0.5 degrees per observation. Zero gives a uniform density.

lower, upper

The two bounding directions of a triangular model, in degrees. Supply both and omit unc. Each bound, taper and survey.sd may be a scalar or a vector in measurement order.

Details

Azimuth is circular. Curves wrap across north before the density-height cutoff is applied. For an asymmetric triangle, the clockwise arc from lower to upper must include az and be shorter than a full turn. For example, limits 358 and 3 enclose a mode of 0. For the four new families, the field interval (including both cosine tapers, if used) spans at most one turn. An aperture convolved with Gaussian survey error can still have tails across the full circle. The grid starts at zero and ends before 360. Each measurement is retained separately. Trimming does not renormalise the stored ordinates. Choose a grid fine enough to resolve the narrowest shoulder.

Value

A skyscapeR.pdf list. The data component contains one data frame per measurement, in input order, with azimuth x in degrees and density y. The metadata record the measurements, names, uncertainties, distribution type and numerical settings.

Choosing a measurement model

All widths and limits are in degrees. Choose the family from the evidence for the sightline and the survey. The examples below refer to a doorway spanning 88 to 92 degrees as seen from the observing position.

"normal"

A central estimate with symmetric, approximately Gaussian error. unc is one standard deviation. Bearings farther from the centre remain possible. Use this for repeated readings or a survey error model that supplies a standard deviation. At a centre of 90 and unc=1, about 95.45 percent of the unwrapped probability lies between 88 and 92.

"uniform"

Every sightline within the stated limits receives equal weight. The density is zero beyond them. unc is the half-width, so az=90, unc=2 gives an opening from 88 to 92. Use this when the two edges are defensible limits and no direction within the opening is preferred.

"epanechnikov"

A preferred central axis with firm limits. Density decreases parabolically to zero at the limits and is zero beyond them. unc is the outer half-width. Use unc=2 when bearings closer to 90 are more plausible and 88 and 92 are the limiting sightlines.

"tapered_uniform"

An equally plausible core with approximate edges. unc gives the core half-width. taper is the additional width on EACH side over which a half-cosine falls smoothly to zero. With unc=2, taper=0.5, the whole 88–92 interval, including its edges, has the same density. The outer limits are 87.5 and 92.5. About 11.1 percent of the mass lies outside the core. Use this when field evidence supports a finite margin beyond both recorded edges.

"triangular"

A preferred bearing (the mode) and defensible limits. Density falls linearly from the mode to each outer limit. Use this when one side of a reconstructed axis is less certain. For example, az=90, lower=89, upper=93 allows a longer tail towards higher bearings. The mode may be at either limit for a one-sided triangle. Supplying only unc gives a symmetric triangle with that half-width.

"uniform_normal"

An equally weighted opening whose measured bearing has an independent, additive, zero-mean Gaussian error. unc is the opening half-width and survey.sd is the standard deviation of that error. The default is 0.5 degrees. Supply a survey-specific estimate when available. The convolution rounds the profile on both sides of each nominal edge and has tails beyond it. With unc=2, survey.sd=0.2, about 4.0 percent of the mass lies outside 88–92. Use this when the angular opening and the error in its bearing can be estimated separately.

A standard deviation, an outer half-width and a core half-width express different field judgements. For example, passing 2 as a normal standard deviation gives a much wider model than interpreting 88 and 92 as two standard deviations from 90. Six density profiles and a close-up of the two softened edges at 92 degrees.

Validation

The 2.0.9011 family checks cover analytic profiles, circular rotation, soft-edge limits and simulation reuse. Build 2.0.9006 passed all 173 original D01 assertions, including 0.005-degree samples across north and the broad-width periodic density cases. See D01 validation in the technical manual.

Scientific checks

References

Silva, F (2020) A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology Journal of Archaeological Science 118, 105138. doi:10.1016/j.jas.2020.105138

See Also

coordtrans, spd, hpdi, randomTest, dec.pdf, modelTest

Examples

opening <- az.pdf(90, 2, pdf="uniform")
axis <- az.pdf(90, 1, pdf="normal")
bounded <- az.pdf(90, 2, pdf="epanechnikov")
soft <- az.pdf(90, 2, pdf="tapered_uniform", taper=0.5)
skew <- az.pdf(90, pdf="triangular", lower=89, upper=93)
surveyed <- az.pdf(90, 2, pdf="uniform_normal") # survey SD defaults to 0.5 degrees
precise <- az.pdf(90, 2, pdf="uniform_normal", survey.sd=0.2)
north <- az.pdf(0, pdf="triangular", lower=358, upper=3)
plot(surveyed)

Convert azimuth and altitude to declination

Description

Find the celestial declination corresponding to a terrestrial sightline at a known latitude and horizon altitude.

Usage

az2dec(
  az,
  loc,
  alt,
  refraction = skyscapeR.env$refraction,
  atm = skyscapeR.env$atm,
  temp = skyscapeR.env$temp
)

Arguments

az

True bearing or vector of bearings in degrees clockwise from north.

loc

One latitude or one per bearing (degrees north), a site matrix with one row per bearing (latitude, longitude and optional elevation), a shared horizon or a list of horizons in measurement order.

alt

Horizon altitude in degrees, shared or one per bearing. Omit when supplying horizons to interpolate altitude at each bearing with hor2alt.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

Details

The same true bearing can indicate different declinations when the observer or horizon changes. Supply angular altitude directly or interpolate it from one shared horizon or one horizon per observation. Numeric latitude inputs imply zero longitude and elevation; a location matrix can include both. When refraction is enabled, the function adjusts the input altitude using pressure, temperature and elevation, then calls the inverse Swiss Ephemeris horizontal transformation. Bearings are clockwise from north; the routine shifts them to the engine convention and rounds the returned declinations using the input bearing representation.

Value

Numeric declination in degrees for the supplied azimuth and altitude values.

Scientific checks

See Also

swe_azalt_rev, hor2alt

Examples

dec <- az2dec(az=92, loc=35, alt=2)

dec <- az2dec(az=c(92,89,102), loc=35, alt=c(0,2,4))

# flat horizon with 2 degrees of altitude
hor <- createHor(az=c(0,360), alt=c(2,2), loc=c(35,-8,25))
dec <- az2dec(92, loc=hor)

# Can also be used for an array of azimuths:
decs <- az2dec(az=c(87,92,110), loc=hor)

Calculate binomial probabilities for aligned structures

Description

Assess how often a specified number of independent structures would face a target by chance, given the chance for one structure.

Usage

bernoulli.trial(n, p, r, type = "tail")

Arguments

n

Total number of structures: a single finite nonnegative integer.

p

Target probability: a single finite number between 0 and 1.

r

Number of hits: a single finite integer between 0 and n.

type

Either "single" for exactly r hits or "tail" for at least r hits (the default).

Details

Define a hit and the per-structure chance of a hit before counting the orientations. A single-count probability answers how often exactly that count arises; the upper tail answers how often a count at least that large arises.

The binomial model assumes independent structures with the same target probability p. The upper-tail probability is a one-sided p-value under this model. Calculations use stats::dbinom and stats::pbinom, avoiding factorial overflow and subtraction from 1. At least zero hits has probability 1. With zero structures, zero hits has probability 1 for either type. Inputs are scalar; invalid inputs error.

Value

A numeric probability between 0 and 1.

Validation

Exact and upper-tail probabilities agreed with independent binomial calculations for the tested counts up to 1,000, including zero hits. See S03 validation in the technical manual.

Scientific checks

References

Ruggles, C (1999) Astronomy in Prehistoric Britain and Ireland. Yale University Press.

See Also

randomTest, modelTest

Examples

# At least 10 out of 30 structures, with targets covering 20% of the horizon:
bernoulli.trial(30, 0.2, 10)
# Exactly 10 hits:
bernoulli.trial(30, 0.2, 10, type="single")
bernoulli.trial(30, 0.2, 0) # Always 1
bernoulli.trial(1000, 0.2, 250) # No factorial overflow

Find the equatorial and horizontal position of a celestial body

Description

Locate a Solar System body in equatorial coordinates at a specified instant, or determine where it appears in the observer's sky.

Usage

body.position(
  time,
  obj = "sun",
  loc = NULL,
  timezone,
  calendar,
  dec,
  refraction,
  atm,
  temp,
  verbose = T
)

Arguments

time

Either a string containing the date and time in the format "YYYY/MM/DD HH:MM:SS" (see timestring), or a numeric containing the julian date (see time2jd).

obj

String containing name of the solar system body of interest. Can be any of the planets (inc. Pluto), the Moon, the Sun or the Ecliptic. Defaults to 'sun'.

loc

Observer location: a numeric vector containing latitude and longitude in degrees and elevation in metres, in that order, or a skyscapeR.horizon object whose metadata supplies those coordinates. Required for topocentric coordinates and for horizontal output in either frame. With no location, only geocentric equatorial coordinates are returned.

timezone

Timezone for civil timestamps. Use UTC or a fixed offset for dates before 1900. See time2jd for named zones and offsets.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

dec

Output declination: geo for the geocentric, or topo for the topocentric frame of reference. If not given the value set by skyscapeR.vars will be used instead.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

verbose

Logical. Display progress or informational messages. Default TRUE.

Details

An alignment comparison needs an epoch, a reference frame and, for a local sightline, a site. Character times are converted to UT Julian dates using the selected calendar and timezone; numeric times are already UT Julian dates. Swiss Ephemeris supplies right ascension and declination. Without a site the function uses the geocentric frame. With a site it can use a topocentric position and convert to local azimuth and altitude. A vector of times is evaluated one instant at a time and returned in input order.

Only the horizon object's location is used; its altitude profile is not used to determine whether the body is visible above the terrain. With a location, horizontal altitude is apparent when refraction is TRUE and geometric when FALSE. Azimuth is measured clockwise from north.

The Swiss Ephemeris manual documents planetary coordinates and reference frames.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A list containing an equatorial data frame with columns RA and Dec, in degrees. When loc is supplied, the list also contains a horizontal data frame with columns az and alt, in degrees. Each data frame has one row per input time.

Validation

In A02, file-backed geocentric directions for ten bodies agreed with their matching JPL parent to within 0.0065 arcseconds across 1,080 comparisons. At the sampled prehistoric epochs the public topocentric convention differed from JPL Horizons by up to 0.70 degrees in local sky direction at a specified instant. See the A02 study in the skyscapeR technical manual.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

References

Astrodienst. Swiss Ephemeris programmer's manual. https://www.astro.com/swisseph/swephprg.htm.

See Also

swe_calc_ut, timestring, time2jd

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Position of the sun at noon GMT on Christmas day 2018:
  body.position(obj='sun', time='2018/12/25 12:00:00', timezone='GMT')
  
  # Declination of the moon at same time
  body.position(obj='moon', time='2018/12/25 12:00:00', timezone='GMT')$equatorial$Dec
  
  # Geometric position using a horizon object's observer location:
  hor <- createHor(az=c(0,360), alt=c(2,2), loc=c(51.5,-0.1,25))
  body.position(obj='sun', time='2018/12/25 12:00:00', timezone='UTC',
  loc=hor, refraction=FALSE)$horizontal
}

Line segments for drawing Western and Chinese constellations

Description

Identify the line segments used to represent Western and Chinese constellations in a reconstruction of the sky.

Usage

data(constellations)

Format

A data frame with 434 rows and six columns.

set

Sky-culture identifier. Use "modern" (88 rows), "chinese" (318 rows), or "chinese_mansions" (28 rows).

name1

Full constellation name.

name2

Western abbreviation or stable Chinese identifier (CHN001 to CHN318).

name3

Chinese pinyin; missing for Western records.

name4

Repeated CHN identifier for Chinese records; missing for Western records.

HIP

Space-separated Hipparcos identifiers. Each successive pair gives the two endpoints of one line segment.

Details

The segment list supplies a drawing convention for overlaying figures on a sky sketch or planisphere. Within a row, read successive pairs of Hipparcos identifiers as separate lines. Identifiers are endpoints, not a polygon to join sequentially or a boundary on the celestial sphere. Epoch and observer location enter when the stars are plotted.

All 88 ordered lists of Hipparcos line endpoints match the Western constellation line file distributed with Stellarium 0.22.2. This comparison identifies the drawing convention used here. Credit: Stellarium's team. The upstream Western sky culture specifies CC BY-SA 4.0 International Public License + Free Art License. The line endpoints are unchanged and repackaged as an R data frame. See the installed COPYRIGHTS file for sources and licence links.

The Chinese records preserve all 318 entries in Stellarium 0.22.2's Chinese line file: 312 have segments (including 57 single-star figures), and six have no segments. Empty HIP fields are skipped; repeated endpoints mark a single star with a small ring. The 28 mansion rows are duplicated as a separately selectable set, ordered from Horn through Chariot. These are asterism figures, not mansion sectors. Selecting both sets does not draw duplicate figures.

English names and Chinese pinyin are retained from upstream. Pinyin without tones is ambiguous: use CHN identifiers or subset by set and English name. Credit: Karrie Berglund, Sun Shuwei and Stellarium contributors; Chinese data are CC BY-SA 4.0. The tradition follows later imperial catalogues as described by upstream, including Yi Shitong's Chinese and Western Contrast Star Chart and Catalogue 1950.0. It is not a reconstruction for every historical epoch.

All Chinese endpoints resolve in the bundled stellar catalogue. The 2026-11-04 supplement uses SIMBAD ICRS/J2000 astrometry, with missing V magnitudes from Hipparcos via VizieR. Five unavailable radial velocities are stored as zero placeholders, not measured zeros; HIP 108797 uses Hipparcos 2007 proper motion and parallax from SIMBAD's measurement tables. Binary/system identifications and long-epoch extrapolation retain the limitations of those source measurements. The installed ephemeris file star-supplement-2026-11-04.csv records per-field references and assumptions.

References

Stellarium 0.22.2. Western constellation lines. https://github.com/Stellarium/stellarium/blob/v0.22.2/skycultures/western/constellationship.fab. Chinese source: https://github.com/Stellarium/stellarium/tree/v0.22.2/skycultures/chinese.

See Also

sketchSky, importConstellations, star.names

Examples

data(constellations)
constellations[constellations$name2 == "Ori", c("name1", "HIP")]
subset(constellations, set == "chinese_mansions", select = c(name1, name2))
system.file("ephemeris", "star-supplement-2026-11-04.csv", package = "skyscapeR")

Transform azimuth densities into declination densities

Description

Estimate which declinations a measured bearing could indicate after allowing for uncertainty in both direction and horizon altitude.

Usage

coordtrans(
  pdf,
  hor,
  xrange,
  .res = 0.1,
  .prec = 0.1,
  .output.res = 0.01,
  verbose = TRUE
)

Arguments

pdf

A skyscapeR.pdf object created with az.pdf or a skyscapeR.spd object created with spd

hor

A shared skyscapeR.horizon or, for individual azimuth PDFs, a list of horizons in measurement order.

xrange

Array of values (min and max) for SPD when transforming a skyscapeR.spd object.

.res

Spacing of the declination calculation grid, in degrees. Default 0.1.

.prec

Azimuth integration spacing, in degrees. Default 0.1. Previously ignored; smaller values increase integration work. Must not exceed 540.

.output.res

Spacing of the returned declination grid, in degrees. Default 0.01. Coarser spacing reduces output size. All spacings must be positive finite scalars, and the returned grid must contain at least two points.

verbose

Logical. Display progress or informational messages. Default TRUE.

Details

A sightline has a distribution of possible bearings, and each bearing samples a potentially different part of the horizon. For every sampled bearing the function interpolates horizon altitude and uncertainty, maps an altitude range to declination and approximates the conditional declination distribution by a Gaussian. It weights that distribution by the azimuth density and integrates the product by the trapezoidal rule. All six az.pdf families supply these bearing weights. The Gaussian approximation here describes uncertainty in horizon altitude at a fixed bearing. An asymmetric or bounded bearing model can therefore produce a declination curve with a different shape or several peaks. A shared horizon can serve several observations, or a supplied list can represent their individual sites.

Density values are calculated at declination spacing .res, then linearly interpolated onto a grid with spacing .output.res. The upper calculation bound is evaluated explicitly if the step does not land on it, avoiding extrapolation at the tail. Linear interpolation preserves nonnegative calculated densities and avoids cubic-spline overshoot. Individual PDF outputs retain their existing area normalisation; SPD outputs retain their existing unnormalised transformation behaviour. Coarse calculation spacing can still miss narrow peaks; interpolation does not replace a resolution-convergence check. Azimuth integration uses a separate grid from -90 to 450 degrees with step .prec. For a distribution split across north, integration uses contiguous bearings around zero at the same spacing. The output grid starts at the lower bound and ends at the last full step within the upper bound. Refine the calculation grid to check that narrow features are resolved. Set atmospheric refraction, pressure and temperature with skyscapeR.vars before transforming. The values used are recorded in the returned PDF or SPD. All three spacings are stored in metadata$param. For a specified azimuth null tested in declination, use modelTest with azimuth inputs and hor. It repeats this individual transformation for each observed and simulated density; a direct declination model instead shifts or reconstructs declination densities.

The Gaussian uncertainty approximation uses the midpoint of declinations obtained at horizon altitude plus/minus four altitude standard deviations, with standard deviation equal to the absolute endpoint separation divided by eight. Reversed bounds are supported. Horizon uncertainties must be finite and nonnegative, and the profile must cover all input azimuths. For positive altitude uncertainties, direct quadrature is used if either transformed four-sigma endpoint reaches an absolute declination of 80 degrees or the endpoints coincide. It integrates the spherical transformation at 256 normal altitude quantiles. Bearing spacing is at most 0.025 degrees on this route and on skyline sections steeper than one degree of height per degree of bearing. The transform uses unrounded declinations internally. A zero altitude uncertainty remains unsupported. Nonfinite transformed bounds/densities and PDF outputs with no positive finite area also error. Positive but very narrow widths still require convergence checks; no minimum uncertainty is imposed.

Keeping the inputs. Save the original azimuth distributions and horizons in measurement order if you plan to draw the transformation curves or run a declination test. The result stores the numerical distributions and settings. The names in metadata$source.labels describe the inputs but cannot reconstruct them. See plot.skyscapeR.pdf and randomTest.

Value

A skyscapeR.pdf object for PDF input, or a skyscapeR.spd object for SPD input. Both contain metadata and data. PDF data are a list of data frames with declination x and density y; SPD data are a single such data frame. Metadata include the coordinate type, transformation settings, format version and descriptive source labels.

Validation

See the study of spherical propagation below.

For a partial photograph the stored positive bearing density must lie within its photographed sector. H07 verified agreement with a complete skyline on the covered north-crossing cases and rejection of uncovered densities. See the H07 check in the technical manual.

Scientific checks

References

Silva, F (2020) A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology Journal of Archaeological Science 118, 105138. doi:10.1016/j.jas.2020.105138

See Also

az.pdf, spd, hpdi, randomTest, dec.pdf, modelTest

Examples

Az <- az.pdf(az=c(87,93,90,110), unc=3)
hor <- createHor(az=c(0,360), alt=c(0,0), loc=c(35,-8,25)) # flat horizon
Dec <- coordtrans(Az, hor)
head(Dec$data[[1]])
Dec$metadata$source.labels
# Reduce stored output size without changing the calculation spacing:
Dec.coarse <- coordtrans(Az, hor, .output.res=0.1)
Dec.coarse$metadata$param

Request a HeyWhatsThat panorama and retrieve its horizon

Description

Request a terrain-derived horizon for an observing site when comparing orientations with possible rising or setting directions.

Usage

createHWT(
  lat,
  lon,
  name,
  elevation = 1.6,
  src = "skyscapeR",
  max.wait = 600,
  verbose = TRUE
)

Arguments

lat

The latitude of the location.

lon

The longitude of the location.

name

Name assigned to the returned horizon profile.

elevation

The elevation of the observer above ground level in meters. Default is 1.6 meters (eye level).

src

Request source ID for HeyWhatsThat. Default is 'skyscapeR'. Only change this if you have been given a source ID by the creator of HeyWhatsThat.

max.wait

Maximum seconds to wait for panorama readiness after submission. Default 600.

verbose

Logical switch to control output. Default is TRUE.

Details

A digital horizon supplies estimated angular obstruction around the site. The optional httr2 package submits one HTTPS request for a panorama. Once the service returns its identifier, the function waits two minutes before the first readiness check, then polls at intervals of up to 15 seconds. The polling deadline defaults to 600 seconds. If the wait expires, use the identifier with downloadHWT once the panorama is ready. Individual requests have a timeout of at most 30 seconds. The initial submission and final download are separate from the polling time allowance. Once ready, the profile is downloaded and assigned the supplied name. Terrain-derived profiles need field verification where vegetation or structures affect visibility.

Value

A skyscapeR.horizon object for the requested panorama, as returned by downloadHWT. This function submits a remote request and waits for the calculated profile.

Scientific checks

References

HeyWhatsThat.com

See Also

downloadHWT

Examples

## Not run: 
# Create and retrieve horizon data for the London Mithraeum:
hor <- createHWT(lat=ten(51,30,45), lon=ten("-0:5:26.1"), name='London Mithraeum')

## End(Not run)

Construct a site horizon from measurements or an elevation model

Description

Build a continuous horizon profile from measurements of horizon altitude at known bearings around a site, or predict the horizon and visible terrain from a DEM.

Usage

createHor(
  az,
  alt,
  loc,
  dem = NULL,
  loc.crs = NULL,
  name = "",
  alt.unc = 0.5,
  smooth = F,
  .scale = 1000,
  eye.height = 1.6,
  max.distance = 10000,
  az.step = 0.25,
  distance.step = NULL,
  features = NULL,
  curvature = TRUE,
  refraction.k = NULL,
  atm = skyscapeR.env$atm,
  temp = skyscapeR.env$temp,
  tempgrad = -10,
  panorama = TRUE,
  width = 4096,
  panorama.distance.step = "adaptive",
  panorama.acuity = 1,
  terrain.palette = "temperate",
  land_cols = NULL,
  sea_cols = NULL,
  sea_level = 0,
  n_sea = 3L,
  palette_n = 256L,
  lighting = c("relief", "directional"),
  light.azimuth = 315,
  light.altitude = 45,
  ambient = 0.4,
  haze = 0.65,
  image.dir = getwd(),
  attribution = "User-supplied DEM",
  license = "See source DEM terms",
  ncores = NULL,
  verbose = TRUE,
  progress = interactive() && verbose,
  contrast = 0.7
)

Arguments

az

Array of azimuth values

alt

Array of altitude values.

loc

Observer location. For DEMs, pass a single CRS-bearing terra SpatVector point directly as loc, or a numeric latitude and longitude. Ground elevation is read from the DEM unless supplied as a third numeric value. Measured horizons take latitude, longitude and elevation.

dem

Optional single-band terra SpatRaster or local raster filename. Supply dem in place of az and alt. Requires the optional terra package.

loc.crs

CRS for numeric DEM observer coordinates in x,y order (easting, northing or longitude, latitude). Without it, numeric loc uses latitude, longitude in WGS84. A single terra SpatVector point carries its own CRS. An optional third numeric coordinate is ground elevation in metres.

name

Name of site.

alt.unc

Either a single value or an array of altitude uncertainty.

smooth

Logical to control whether to smooth horizon profile using rolling mean. Defaults to FALSE

.scale

Number of samples in the rolling mean when smooth = TRUE. The grid spacing is 0.01 degrees, so 1000 samples span approximately 10 degrees.

eye.height

Observer height above the selected ground elevation in metres.

max.distance

DEM search radius in metres, default 10000. Include any distant terrain that could form the horizon within the DEM coverage.

az.step

Maximum spacing of numerical DEM rays in degrees. The default is 0.25. An equal number of steps fills the circle.

distance.step

Maximum spacing of samples along each ray in metres. By default use half the smaller native cell dimension estimated at the site.

features

Optional horFeature object or list of such objects describing reconstructed or highlighted structures. Requires dem. Elevations are additive, with the largest positive and deepest negative contributions combined at overlaps. Later footprints take colour precedence. Features affect both numerical horizon and visible terrain. Their geometry is kept out of the returned horizon; save the feature objects separately.

curvature

Apply Earth curvature to DEM sightlines. Default TRUE.

refraction.k

Default NULL applies Patat when curvature is enabled. Set zero for geometric curvature without terrestrial refraction, or supply a coefficient below one for the effective-radius model.

atm

Ground atmospheric pressure in millibars for Patat terrestrial refraction.

temp

Ground air temperature in degrees Celsius.

tempgrad

Vertical temperature gradient in kelvins per kilometre (default -10).

panorama

Render an external terrain PNG for a DEM. Default TRUE. Set FALSE for the numerical horizon alone.

width

DEM panorama width in pixels, an even integer from 32 to 81920. Default 4096 by 2048 pixels. Height is half the width. Widths above 8192 are assembled from temporary image tiles. Both dimensions grow with width, so a tenfold increase generates 100 times as many pixels.

panorama.distance.step

The default, "adaptive", starts at one local DEM cell and increases radial spacing with distance using the larger of the requested angular acuity and one horizontal PNG pixel. This transverse footprint is a proxy for radial detail. A narrow ridge may fall between samples. Use a positive number for fixed spacing in metres or NULL to reuse distance.step. The numerical horizon uses distance.step independently. Inspect metadata$image$sampling for the effective angle, sample count and actual step range. On large DEM-only panoramas, the renderer checks near terrain against a conservative upper bound for the remaining terrain on each ray. It skips distant samples only where all remaining elevations are hidden and keeps neighbours for surface shading. Terrain with added archaeological features uses the full sampling path.

panorama.acuity

Angular detail target in arcminutes for adaptive PNG sampling. Defaults to 1 (nominal 20/20 acuity). Larger values coarsen distant terrain.

terrain.palette

Named land/water pair from demPalettes. Options are temperate (default), standalone, arid, alpine, coastal and relief.

land_cols, sea_cols

Opaque R colour names or hex colours in increasing elevation order. NULL inherits the respective ramp from terrain.palette. Supply either vector to override just that ramp. One colour gives a uniform base. Colours interpolate in Lab space.

sea_level

DEM elevation in metres at or below which the sea colour ramp is used. Default 0. A level water surface uses the shallow colour. This is an elevation threshold. Use NULL to apply the land palette over the whole visible elevation range, including depressions. The temperate land ramp starts at the lowest visible land level or sea threshold, whichever is higher. Other palettes with a threshold start at sea_level. The ramp ends at the highest visible elevation. The sea ramp starts at the lowest visible elevation.

n_sea

Number of entries reserved for the sea ramp, leaving at least two land colours. Default 3.

palette_n

Total number of palette entries, from 4 to 65536. Default 256.

lighting

Relief lighting (default) blends a light at the observer (75 percent) with the directional source (25 percent). It shades both sides of a slope and lifts deep shadows. The standalone renderer brightness response is min(1, ambient + contrast * illumination), with illumination floored at 0.15. Terrain and visible horFeature surfaces use the same lighting. Choose "directional" for one-sided hillshade. Lighting affects the PNG only.

light.azimuth, light.altitude

Direction towards the illustrative light source in degrees clockwise from true north and above the horizon. Defaults are 315 and 45 degrees. Hillshading uses upward surface normals in metric east, north and vertical coordinates. This is local illumination without cast shadows from other terrain.

ambient

Fraction of illumination retained on slopes facing away from the light (0 to 1). Default 0.40. Use 1 for unshaded palette colours.

haze

Maximum fraction of distance haze (0 to 1). Default 0.65. Set haze=0 and ambient=1 to inspect the colour mapping alone.

image.dir

Directory for the DEM PNG. Defaults to the working directory. Site names form the filename; different images with the same name receive a checksum suffix.

attribution

Credit for the DEM, included in plots and exports. The generic default credit is omitted from plots.

license

Source licence or terms for the DEM, included in exports.

ncores

Maximum DEM tracing workers. Defaults to half the available logical cores, rounded down with a minimum of one. The startup message reports used and available cores. Workers share file-backed DEM data and process separate bearings.

verbose

Announce the DEM radius, sampling and rendering stages.

progress

Show a progress bar for each tracing stage. Default on in interactive verbose sessions.

contrast

Relief-light contrast (0 to 1), default 0.70, following the standalone renderer. It controls slope detail independently of ambient brightness. Ignored for directional lighting, which retains ambient + (1 - ambient) * illumination. Regenerate existing panoramas to apply new settings.

Details

Measured bearings. To evaluate sightlines between measured bearings, the constructor repeats the azimuths one turn in each direction, removes duplicate azimuth entries and linearly interpolates altitude and altitude uncertainty onto a 0.01-degree grid from -90 to 450 degrees. Scalar uncertainty is repeated. Optional smoothing applies a running mean over the specified number of grid samples to both series, with zero fill at the outer ends. Latitude, longitude and elevation identify the observer; omitted elevation defaults to zero. Interpolation cannot recover narrow features between measurements.

Observer and DEM coverage. For a DEM, supply a point with a CRS, projected x and y with loc.crs, or WGS84 latitude and longitude. The optional third coordinate is ground elevation in metres in the DEM's vertical datum. Otherwise ground elevation is bilinearly sampled at the site. Observer elevation in the returned georeference is ground elevation plus eye.height. A terrain model represents bare earth. A surface model includes the objects represented in its elevations. Use a single continuous band in metres with a defined horizontal CRS. Missing samples and terrain beyond the raster edge are skipped. A warning and the incomplete.bearings metadata identify incomplete coverage. Each bearing needs at least one usable sample.

Sampling narrow ridges. Terrain is sampled along true bearings from north, clockwise. A WGS84 local azimuthal equidistant projection sets the distances and bearings. Sample coordinates are transformed to the source grid for bilinear elevation extraction in batches. Each horizon angle is the maximum sampled elevation angle along its ray. The requested radius is included wherever covered. A missing observer ground elevation without an override or an observer outside the DEM cause an error. Rays and distance samples are discrete. A finer constructor output grid cannot recover a ridge between rays, steps or DEM cells. Increase the radius and refine both sampling intervals to check convergence for a site. At 5 km the default 0.25-degree rays are approximately 22 metres apart. The supplied altitude uncertainty is an assumption in degrees.

Curvature and terrestrial refraction. By default the apparent altitude at each sampled distance d (metres) follows Patat (2011), equations 1 and 2. The geometric angle is atan((z-observer)/d - d/(2R)). Add (d/R) times 0.252 P (34.2 + tempgrad) / T squared in radians, using temperature T in kelvins and the latitude-dependent radius R from Appendix A1. The same corrected angles determine the numerical horizon and the visible terrain in the PNG. An explicit numeric refraction.k selects a spherical vertical section of effective radius 6371008.8 / (1 - refraction.k) metres. At ground distance d and elevation z, the forward component is (R + z) sin(d/R) and the vertical component is z minus observer elevation minus 2 (R + z) sin(d/(2R)) squared, where the square applies to the sine. The angle is obtained with atan2. With curvature disabled, use the height difference and horizontal distance directly. Terrestrial refraction applies to the terrain sightline. Atmospheric refraction is controlled separately in astronomical calls.

Panorama and reconstructed features. By default a second set of rays paints the first visible terrain at each azimuth and elevation, using local surface normals, elevation colours and distance haze. The transparent sky edge follows the numerical horizon. With features, each PNG column is traced directly through the reconstructed terrain; its edge can differ from the interpolated numerical horizon between rays. Refine az.step and width when examining narrow structures. The panorama spans the full 360 degrees from nadir to zenith. The horizon object stores its bounds, checksum, attribution and licence in metadata$image. Save the external PNG alongside the RDS. If you move them, use relinkHor to reconnect the image. A rendering failure returns the numerical horizon with a warning. Plotting also falls back to the numerical horizon if the image is missing or has changed.

Value

A skyscapeR.horizon list with metadata (site name and georeference) and a data frame named data. Its az, alt and alt.unc columns contain azimuth, horizon altitude and altitude uncertainty, all in degrees.

Accuracy, uncertainty and reproducibility

H01 compared 334 bearings at 31 observing setups. At the surveyed bearings, createHor() reproduced the observed terrain skyline to within half a degree in 91.9% of cases. See the H01 field validation in the skyscapeR technical manual for the survey protocol, station results and limitations.

With the same 1 m terrain, createHor() reproduced Horizon’s skylines to a mean absolute difference of 0.004 degrees at each of two English sites. Against field measurements at 344 Irish bearings, createHor() using SRTM had a mean absolute error of 0.328 degrees, lower than either HeyWhatsThat or PeakFinder on that sample. Field accuracy varied by site. See the H02 comparison in the skyscapeR technical manual.

The numerical skyline is a maximum over sampled terrain, not an accuracy certificate for the DEM. Horizontal and vertical datum differences, observer height, missing raster values, vegetation and buildings can exceed the sampling error. DEM elevations and a supplied observer ground elevation must use a compatible vertical datum. No geoid conversion or vertical-datum correction is performed automatically. Refine the angular and distance sampling and expand the radius until the relevant sightlines are stable. Compare with surveyed bearings and altitudes where available.

alt.unc is supplied by the user and is not estimated from DEM resolution, control residuals or atmospheric variability. Smoothing a measured profile can remove narrow notches or peaks. Adaptive panorama sampling and illustrative lighting concern the image; they do not increase numerical horizon precision. The terrestrial refraction approximation assumes the supplied atmosphere and cannot reproduce all near-ground gradients or mirage conditions.

Save the DEM provenance, observer location and datum, constructor arguments, feature objects, returned horizon and external PNG. Rebuilding from the same source is distinct from merely replotting the saved horizon.

Scientific validation

H03 examines DEM sampling against an analytic ridge and a level spherical surface. H03 scientific validation.

Scientific checks

References

Patat, F. (2011). Horizon synthesis for archaeo-astronomical purposes. Astronomische Nachrichten 332, 743-749. doi:10.1002/asna.201111570.

See Also

importPeakFinder, plot.skyscapeR.horizon

createHWT, downloadHWT

Examples

## Not run: 
observer <- terra::vect("observer.gpkg") # one point with a CRS
h <- createHor(dem="terrain.tif", loc=observer, eye.height=1.6)

## End(Not run)
# Create a skyscapeR.horizon from 5 measurements:
az <- c(0,90,180,270,360)
alt <- c(0,5,5,0,0)
hor <- createHor(az, alt, alt.unc=0.1, loc=c(40.1,-8), name='Test')
plot(hor)
## Not run: 
# loc is latitude, longitude. Distances and elevations are metres.
terrain <- createHor(dem="site-dtm.tif", loc=c(51.19,-1.75),
  name="Survey site", max.distance=5000, eye.height=1.6,
  image.dir="horizons", attribution="Survey DTM", license="Survey terms")
plot(terrain)
exportStellarium(terrain, name="Survey site")

## End(Not run)

Estimate solar declination at the December solstice

Description

Estimate the limiting solar declination at the December solstice for comparison with a structural sightline.

Usage

dS(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.00224,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

altitude

Altitude of the sun. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

The December solstice is represented by the negative obliquity of the ecliptic for the requested epoch. The result is geocentric when no site is supplied. With a site, the function subtracts the approximate parallax correction using latitude and target altitude. This obliquity-based target does not determine a solstice time or a sunrise or sunset bearing.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Validation

A05 checked the local December solar limit against annual obliquity and the specified parallax correction. See the A05 check in the technical manual.

Scientific checks

See Also

obliquity, jS, eq, zenith, antizenith, spatial.equinox, parallax.corr

Examples

# December Solstice geocentric declination for year 4001 BC:
dS(-4000)

# Topocentric declination for same year and latitude of 50 degrees N:
dS(-4000, loc=50)

Represent measured declinations as probability densities

Description

Represent the uncertainty of directly supplied declinations so they can be summed or tested against a declination model.

Usage

dec.pdf(
  dec,
  unc = NULL,
  pdf = "normal",
  name,
  .res = 0.01,
  .cutoff = 1e-04,
  verbose = TRUE,
  taper = NULL,
  survey.sd = 0.5,
  lower = NULL,
  upper = NULL
)

Arguments

dec

Measured declinations between -90 and +90 degrees. For triangular, the modal declination.

unc

One width or one per observation. Standard deviation for normal, outer half-width for uniform, Epanechnikov or symmetric triangular, and core half-width for tapered uniform or uniform convolved with normal. Omit when supplying triangular limits. See 'Choosing a measurement model'.

pdf

One measurement family per call. See 'Choosing a measurement model' for all six names. The default is "normal". The historical abbreviations "n" and "u" are accepted and names are case-insensitive.

name

Optional measurement labels in input order.

.res

Grid spacing in degrees. Default 0.01.

.cutoff

Minimum retained density height. Default 0.0001.

verbose

Logical. Report completion.

taper

Outer extension on each side of a tapered uniform core, in degrees. Required for "tapered_uniform". Zero gives a uniform density.

survey.sd

Standard deviation of independent bearing or declination error, in degrees, for "uniform_normal". Defaults to 0.5 degrees per observation. Zero gives a uniform density.

lower, upper

The two bounding directions of a triangular model, in degrees. Supply both and omit unc. Each bound, taper and survey.sd may be a scalar or a vector in measurement order.

Details

Use this constructor when both the measurement and its uncertainty are already expressed in declination. All six families have the same parameter meaning as in az.pdf. The doorway examples in 'Choosing a measurement model' illustrate their shapes. When starting from measured bearings and site horizons, use coordtrans to propagate the bearing model. Direct declinations are linear. A triangle must satisfy lower <= dec <= upper. The sampled curve is clipped to physical declinations from -90 to +90 degrees and trimmed at .cutoff. The retained area can consequently be less than one.

Value

A skyscapeR.pdf list with one x/y data frame per observation. Metadata record coord = "dec", the input measurements, family, uncertainties, labels and numerical settings.

Validation

In D01, sampled declination densities agreed with analytic references. Build 2.0.9006 retained the corresponding declination centres in all four subset checks. See D01 validation in the technical manual.

Scientific checks

Choosing a measurement model

All widths and limits are in degrees. Choose the family from the evidence for the sightline and the survey. The examples below refer to a doorway spanning 88 to 92 degrees as seen from the observing position.

"normal"

A central estimate with symmetric, approximately Gaussian error. unc is one standard deviation. Bearings farther from the centre remain possible. Use this for repeated readings or a survey error model that supplies a standard deviation. At a centre of 90 and unc=1, about 95.45 percent of the unwrapped probability lies between 88 and 92.

"uniform"

Every sightline within the stated limits receives equal weight. The density is zero beyond them. unc is the half-width, so az=90, unc=2 gives an opening from 88 to 92. Use this when the two edges are defensible limits and no direction within the opening is preferred.

"epanechnikov"

A preferred central axis with firm limits. Density decreases parabolically to zero at the limits and is zero beyond them. unc is the outer half-width. Use unc=2 when bearings closer to 90 are more plausible and 88 and 92 are the limiting sightlines.

"tapered_uniform"

An equally plausible core with approximate edges. unc gives the core half-width. taper is the additional width on EACH side over which a half-cosine falls smoothly to zero. With unc=2, taper=0.5, the whole 88–92 interval, including its edges, has the same density. The outer limits are 87.5 and 92.5. About 11.1 percent of the mass lies outside the core. Use this when field evidence supports a finite margin beyond both recorded edges.

"triangular"

A preferred bearing (the mode) and defensible limits. Density falls linearly from the mode to each outer limit. Use this when one side of a reconstructed axis is less certain. For example, az=90, lower=89, upper=93 allows a longer tail towards higher bearings. The mode may be at either limit for a one-sided triangle. Supplying only unc gives a symmetric triangle with that half-width.

"uniform_normal"

An equally weighted opening whose measured bearing has an independent, additive, zero-mean Gaussian error. unc is the opening half-width and survey.sd is the standard deviation of that error. The default is 0.5 degrees. Supply a survey-specific estimate when available. The convolution rounds the profile on both sides of each nominal edge and has tails beyond it. With unc=2, survey.sd=0.2, about 4.0 percent of the mass lies outside 88–92. Use this when the angular opening and the error in its bearing can be estimated separately.

A standard deviation, an outer half-width and a core half-width express different field judgements. For example, passing 2 as a normal standard deviation gives a much wider model than interpreting 88 and 92 as two standard deviations from 90. Six density profiles and a close-up of the two softened edges at 92 degrees.

References

Silva, F. (2020). A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology. Journal of Archaeological Science 118, 105138. doi:10.1016/j.jas.2020.105138.

See Also

az.pdf, coordtrans, spd, modelTest

Examples

d <- dec.pdf(dec = c(-18, 12), unc = c(0.8, 1.4))
head(d$data[[1]])
dec.pdf(-18, pdf="triangular", lower=-19, upper=-15)
dec.pdf(-18, 2, pdf="uniform_normal", survey.sd=0.2)

Named elevation palettes for DEM terrain panoramas

Description

Choose land and water colours for a site panorama. The presets use illustrative elevation tints for different landscapes.

Usage

demPalettes(name = NULL)

Arguments

name

Optional exact preset name. Omit to retrieve the full catalogue.

Details

Pass a preset name to the terrain.palette argument of createHor. Use demPalettes("standalone") to inspect the colours in that preset. Temperate uses green and ochre, arid uses sand and red-brown, alpine runs from forest greens to pale rock and white, and coastal pairs sand and grass with a deep-blue to turquoise water ramp. Relief gives land one neutral tint for inspecting slope shading. Each preset has its own sea_cols vector. Land stops are ordered low to high and water stops deep to shallow. createHor treats elevations at or below sea_level as water for colouring. An inland depression below that threshold also receives the water tint. sea_level=NULL uses the land ramp for all elevations.

Value

With a name, a list containing land_cols and sea_cols. Without a name, a named list of those pairs.

Scientific checks

See Also

createHor

Examples

names(demPalettes())
demPalettes("coastal")$sea_cols

Download a horizon from a HeyWhatsThat panorama

Description

Recover an existing terrain-derived horizon for use in site-specific orientation calculations.

Usage

downloadHWT(HWTID)

Arguments

HWTID

This is the 8 character ID attributed by HeyWhatsThat.com

Details

A panorama describes the horizon seen from a particular observer location. The optional httr2 package retrieves site metadata and 0.125-degree horizon bins over HTTPS. Site elevation above sea level is reported in metres, converting feet when necessary. Validated profiles are cached by panorama identifier for the R session. Read-only downloads allow up to three attempts for transient HTTP failures, with a 30-second limit per request. For each bin, the distance and angular altitude determine a height difference. The mean angular change for height offsets of plus and minus 9.73 metres estimates altitude uncertainty.

Value

A skyscapeR.horizon list containing site metadata and horizon samples. The data columns az, alt and alt.unc are in degrees. Retrieval requires access to the HeyWhatsThat service.

References

HeyWhatsThat.com

See Also

importPeakFinder, createHWT

Examples

## Not run: 
# Retrieve the Liverpool Cathedral horizon by its panorama ID.
hor <- downloadHWT('HIFVTBGK')

## End(Not run)

Estimate solar declination at an equinox

Description

Estimate the solar declination associated with the astronomical equinox, optionally applying a site-dependent parallax correction.

Usage

eq(loc = FALSE, parallax = 0.00224, altitude = 0, verbose = TRUE)

Arguments

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

altitude

Altitude of the sun. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE. This affects messages only, not the calculated declination.

Details

The geometric reference at an equinox is the celestial equator, with geocentric declination zero. Supplying a location subtracts the package's approximate parallax correction for the latitude and specified altitude. The result is a declination target in degrees; no equinox date, event time or horizon crossing is calculated.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Validation

A05 checked the equinoctial declination reference separately from the dates of the astronomical equinoxes. See the A05 check in the technical manual.

Scientific checks

See Also

obliquity, jS, zenith, antizenith, spatial.equinox, parallax.corr, dS

Examples

# Equinoctial geocentric declination:
eq()

# The same geocentric result without a message:
eq(verbose=FALSE)

# Topocentric declination at latitude 50 degrees N:
eq(loc=50)

Export a site horizon as a Stellarium landscape

Description

Reproduce a measured or modelled archaeological horizon as a Stellarium landscape for visual comparison.

Usage

exportHor(
  hor,
  name,
  author = "skyscapeR",
  description,
  use.image = TRUE,
  peakfinder.layout = c("single", "native"),
  max.texture.width = 4096,
  ground_col,
  hor_col
)

exportStellarium(
  hor,
  name,
  author = "skyscapeR",
  description,
  use.image = TRUE,
  peakfinder.layout = c("single", "native"),
  max.texture.width = 4096,
  ground_col,
  hor_col
)

Arguments

hor

Horizon data in skyscapeR.horizon format.

name

Horizon name to be displayed in Stellarium, if different from one in skyscapeR.horizon object.

author

Author, to be included in landscape.ini file.

description

Description, to be included in landscape.ini file.

use.image

Include a valid external panorama PNG when available. Default TRUE. Missing or changed files warn and use a polygonal horizon instead.

peakfinder.layout

Single spherical PNG (default) or original native tiles. Textured DEM and PeakFinder exports use their PNG silhouette.

max.texture.width

Maximum exported DEM or photographic panorama width in pixels. The default is 4096. Use max.texture.width=2048 for a smaller texture, or Inf to keep the original dimensions. Stellarium supports textures only up to the graphics hardware limit. PNG compression does not reduce the decoded texture dimensions. Larger exports are at your own risk and may fail to load or crash Stellarium. This setting does not resize PeakFinder textures.

ground_col

Color of ground. Defaults to Stellarium's default.

hor_col

Colour of a polygonal horizon line. Textured DEM and PeakFinder landscapes omit this line.

Details

A landscape lets the same terrain obstruction be used in a planetarium reconstruction. The export pairs the profile's azimuth and altitude samples in a polygonal horizon file and records the site, appearance and attribution in a Stellarium configuration. The export describes the horizon geometry; the altitude-uncertainty series remains in the R object.

DEM and SVG panoramas use a spherical landscape with the PNG rotated -90 degrees for Stellarium's east-origin mapping. A new PeakFinder import also records the original ZIP location. If native tiles are requested and that archive still matches its checksum and contains the supported calibrated eight-tile landscape, Stellarium uses those original textures and their angular settings instead. The export also includes the skyscapeR numerical profile and SVG-derived PNG. exportStellarium is an alias for exportHor.

The ZIP is saved as name-horizon.zip in the calling working directory. Choose a new archive name each time. Names cannot contain path separators or line breaks. Export requires a working system ZIP command.

Value

Invisibly, the absolute path of the created ZIP archive.

Validation

H07 checked that a partial photograph is rejected for both image and numerical landscape export. See the H07 check in the technical manual.

Scientific checks

References

Stellarium User Guide, chapter on landscapes and texture sizes.

See Also

createHor, downloadHWT, plot.skyscapeR.horizon

Examples

# Export a measured horizon from the example dataset.
## Not run: 
hor <- malta_horizons[[1]]
exportStellarium(hor, name = "Malta survey")
# For a DEM panorama, reduce the texture width on a memory-limited machine.
terrain <- createHor(dem = "terrain.tif", loc = c(51.19, -1.75))
exportStellarium(terrain, name = "Survey terrain", max.texture.width = 2048)

## End(Not run)

Export a horizon as an equirectangular PNG

Description

Write a full-sphere 2:1 RGBA texture for planetaria or image editors.

Usage

exportPanorama(
  hor,
  file,
  width = 4096,
  use.image = TRUE,
  col.ground = "darkgreen"
)

Arguments

hor

A skyscapeR.horizon object.

file

Destination PNG filename. Choose a new filename for each export.

width

Even output width in pixels. Height is half the width. Default 4096.

use.image

Use the attached terrain or photographic texture when available. Set FALSE to export the numerical skyline as a silhouette.

col.ground

Fill colour for a numerical silhouette.

Details

The left edge is true north. Azimuth increases clockwise through east, south and west. The top is the zenith, the middle is zero altitude and the bottom is the nadir. Image exports preserve the calibrated angular bounds and sample source pixels by nearest neighbour. Sky and areas outside photographic coverage are transparent. For a numerical skyline, the ground extends to the nadir over the measured azimuth sector. A missing or modified image triggers a warning and the numerical silhouette is exported instead.

Value

The absolute PNG path, invisibly.

See Also

exportStellarium, importPanorama

Examples

## Not run: 
exportPanorama(hor, "site.png")
exportPanorama(hor, "site-silhouette.png", width = 2048, use.image = FALSE)

## End(Not run)

Find celestial targets within declination and time ranges

Description

Screen solar, lunar and stellar candidates whose declinations overlap a measured orientation range during a proposed period of use.

Usage

findTargets(
  decrange,
  year,
  loc = FALSE,
  max.mag = 2.5,
  dates = FALSE,
  calendar = skyscapeR.env$calendar,
  timerange
)

Arguments

decrange

Range of declination to consider.

year

Temporal range to consider. Historical labels such as "3700 BC" are accepted by astroYear.

loc

FALSE for geocentric declinations, a vector of latitude, longitude and elevation, or a skyscapeR.horizon to also evaluate the local horizon.

max.mag

Maximum magnitude of stars to consider. Defaults to 2.5

dates

Whether to display time period when identified celestial targets occur within declination range. Default is FALSE.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

timerange

Earlier argument name for year, retained for existing scripts.

Details

The search tests overlap in declination. Solar and lunar limiting declinations are sampled across the years of the interval. Site coordinates enable zenith targets and a horizon enables the spatial equinox. The named equinoxes and solstices use geocentric apparent solar longitudes of 0, 90, 180 and 270 degrees. Dates are UT civil days in the requested calendar. Different dates for the first and last year appear in endpoint order separated by a slash. Intermediate years can differ. The sunrise/set date ranges also use the two endpoint years. Solar and lunar candidates are selected before display rounding. Zenith candidates use the period-specific tropical limit and require a reachable solar passage. For spatial equinoxes the reported range uses rising and setting solutions at the endpoint epochs, not an annual interior search. For each star passing the catalogue magnitude cut, the search computes its declination at noon UT on 1 January Gregorian of every astronomical year, including both endpoints. It tests overlap before rounding and linearly interpolates between annual samples to estimate entry and exit. Separate passages are reported separately, with boundaries rounded to the nearest year. A contact within 0.0000001 degree of a stellar band edge is treated as a closed-boundary match. Shorter variations within a sampling year are unresolved. Magnitude describes catalogue brightness and does not model atmospheric visibility.

Silva and Lomsdalen (2025, table 5) give an example of stellar target screening for the Maltese temples.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A list of candidate solar, lunar and stellar matches. The tables give target names and declination limits in degrees. Stellar matches also carry catalogue identifiers and visual magnitudes. Set dates to TRUE to request stellar date ranges. A category with no matches may be absent.

Validation

A08 verified closed-band membership, separate stellar passages, sampled contact, magnitude filtering and comparisons before display rounding. See the A08 check in the technical manual.

Candidate selection and visibility

A match is a declination overlap, not evidence that a celestial object was visible, deliberately observed or associated with the archaeological feature. The magnitude filter uses fixed catalogue values; it includes integrated magnitudes for non-stellar entries such as M45. It does not predict naked-eye visibility through extinction or twilight, or resolve the members of a cluster.

Choose the dating interval and measurement uncertainty from the archaeological and survey evidence. Then examine candidate stars with star.phases, riseset and sketchSky. For a statistically selected local declination band, candidate screening is exploratory; the significance of that band does not identify its cause. Physical plausibility and independent archaeological evidence are separate parts of the interpretation.

Spatial equinox epochs

When a horizon is supplied, the spatial equinox is evaluated at both endpoints of the requested year range (once for a single year), with the current atmospheric settings. The candidate interval spans the finite sunrise and sunset declinations at those endpoints. This is an endpoint envelope, not an exhaustive search for intermediate changes of terrain crossing over very long periods. Undefined crossings generate warnings; if all are undefined, the candidate is omitted.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

References

Silva, F. and Lomsdalen, T. (2025). 'No easy way from the earth to the stars': a new statistical approach to the orientation of the Maltese temples. Archaeological and Anthropological Sciences 17, 96. doi:10.1007/s12520-025-02208-4.

See Also

star.phases, riseset, sketchSky, spatial.equinox, solar.date, EFM, planet.extremes

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  ## Not run: 
  findTargets(c(-25,-17.5), c(-2500,-1750))
  
  # if a location is given then the zenith and anti-zenith sun will also be looked at:
  findTargets(c(3,12), c(-2500,-1750), loc=c(8.6, 7.3, 200))
  
  # if a horizon profile is given then the spatial equinox will also be looked at:
  hor <- malta_horizons[[1]]
  findTargets(c(-7,2), c(-2500,-1750), loc=hor)
  
## End(Not run)
}

Interpolate horizon altitude at a bearing

Description

Estimate the altitude of the local horizon, and optionally its uncertainty, at one or more true bearings.

Usage

hor2alt(hor, az, return.unc = F)

Arguments

hor

A skyscapeR.horizon object from which to retrieve horizon altitude.

az

Array of azimuth(s) for which to retrieve horizon altitude(s).

return.unc

Logical controlling whether to return altitude uncertainty. Default is FALSE.

Details

A measured axis rarely falls exactly on a stored horizon sample. Separate cubic splines interpolate altitude and its recorded uncertainty as functions of azimuth, and results are rounded to two decimal places. Supply bearings within the profile coverage; a spline beyond the measured range is an extrapolation. Distinguish this lookup from the linear interpolation used inside coordtrans.

Value

With return.unc = FALSE, a numeric vector of altitudes. With return.unc = TRUE and one azimuth, an unnamed numeric vector containing altitude followed by uncertainty. With multiple azimuths, a numeric matrix with columns alt and alt.unc, one row per input azimuth in the supplied order. Values are rounded to two decimal places.

Validation

In H07, lookup at each edge of a north-crossing panorama returned its measured altitude and lookup beyond either edge returned NA. See the H07 check in the technical manual.

Scientific checks

See Also

createHor, downloadHWT

Examples

hor <- createHor(c(0,90,180,270,360), c(0,5,3,1,0),
                 alt.unc=c(0.1,0.2,0.3,0.2,0.1), loc=c(40,-8,100))
hor2alt(hor, 90)
hor2alt(hor, 90, return.unc=TRUE)
hor2alt(hor, c(90,180,270), return.unc=TRUE)

Find the northern declination limit of a horizon

Description

Estimate the largest declination indicated by the horizon near true north.

Usage

hor2max.dec(hor, alt = 0, range = 25)

Arguments

hor

Either a skyscapeR.horizon object or the latitude of the place.

alt

Altitude of the horizon at northernmost point. Only necessary if no skyscapeR.horizon object is provided. Default is 0.

range

Range of azimuths to check for minimum declination. Default is 25 degrees either side of North.

Details

Terrain relief can shift the limiting sightline away from the meridian. The function samples bearings at 0.01-degree spacing within the specified half-width around 0 degrees. It calls az2dec at each bearing with the stored horizon, or with the supplied latitude and constant altitude, then returns the maximum sampled declination. A limited search sector may miss a more extreme sightline elsewhere.

Value

One numeric value in degrees, the largest declination sampled across the specified azimuth range around north.

Validation

A05 recovered a limiting sightline within the northern search sector on a synthetic skyline with an interior crest. See the A05 check in the technical manual.

Scientific checks

See Also

createHor, downloadHWT, createHWT, exportHor, hor2alt, hor2min.dec

Examples

hor <- malta_horizons[[1]]
hor2max.dec(hor)

Find the southern declination limit of a horizon

Description

Estimate the smallest declination indicated by the horizon near true south.

Usage

hor2min.dec(hor, alt = 0, range = 25)

Arguments

hor

Either a skyscapeR.horizon object or the latitude of the place.

alt

Altitude of the horizon at southernmost point. Only necessary if no skyscapeR.horizon object is provided. Default is 0.

range

Range of azimuths to check for minimum declination. Default is 25 degrees either side of South

Details

Terrain relief can shift the limiting sightline away from the meridian. The function samples bearings at 0.01-degree spacing within the specified half-width around 180 degrees. It calls az2dec at each bearing with the stored horizon, or with the supplied latitude and constant altitude, then returns the minimum sampled declination. A limited search sector may miss a more extreme sightline elsewhere.

Value

One numeric value in degrees, the smallest declination sampled across the specified azimuth range around south.

Validation

A05 recovered a limiting sightline within the southern search sector on a synthetic skyline with an interior trough. See the A05 check in the technical manual.

Scientific checks

See Also

createHor, downloadHWT, createHWT, exportHor, hor2alt, hor2max.dec

Examples

hor <- malta_horizons[[1]]
hor2min.dec(hor)

Reconstruct or highlight archaeological structures in a DEM horizon

Description

Explore how stones, poles and earthworks change the visible landscape and the horizon used in an orientation analysis. Describe one vector layer of structures, then pass one or several layers to createHor.

Usage

horFeature(
  geometry,
  type = c("stone", "pole", "bank", "ditch", "mound", "platform", "wall"),
  height = 0,
  height_field = NULL,
  depth = 0,
  depth_field = NULL,
  width = NULL,
  width_field = NULL,
  diameter = NULL,
  diameter_field = NULL,
  profile = NULL,
  use = NULL,
  colour = NULL,
  colour_field = NULL,
  name = NULL
)

Arguments

geometry

A vector filename (including a shapefile or GeoPackage), a terra SpatVector, or an object accepted by terra::vect, with a known CRS. A layer must contain one geometry family: points, lines or polygons.

type

Structure type: stone, pole, bank, ditch, mound, platform or wall. Stones and poles accept points or polygons; mounds and platforms require polygons; banks, ditches and walls accept lines or polygons.

height

Additional height in metres, nonnegative. Default 0. Ignored for ditches, which use depth. Positive height and depth cannot be combined.

height_field, depth_field, width_field, diameter_field, colour_field

Optional attribute column names supplying per-row settings. Do not also supply the corresponding common value. Numeric fields must be numeric, finite and meet the same bounds as common values. Colour fields must contain valid colours.

depth

Nonnegative ditch depth in metres. Default 0; only for ditches.

width

Total width in metres for lines or polygon boundaries.

diameter

Diameter in metres for point footprints.

profile

Either bell or flat. Defaults to bell for banks, ditches and mounds, and flat for stones, poles, platforms and walls.

use

For polygons, area or boundary. NULL chooses the type's default.

colour

One opaque R colour, or NULL for the terrain palette.

name

Descriptive label for the layer. Defaults to the structure type.

Details

Reconstructions are explicit hypotheses about additional relief above the supplied terrain. Heights are added to the existing DEM, including any surviving remains already represented there. Ditch depths are subtracted. No original ground surface or historical height is inferred. Zero height or depth highlights a footprint without changing elevation.

Every feature and multipart component is used. Points become circular footprints with the supplied diameter. Lines become strips with half the width on each side and round ends. Polygons use their whole area by default for stones, poles, mounds and platforms, and their boundary for banks, ditches and walls. Polygon holes remain holes in area mode; boundary mode includes their edges. Dimensions are metres in a local azimuthal equidistant projection.

Flat profiles extrude the footprint with vertical sides and a top following the underlying DEM. Bell profiles use sin(pi * t / 2)^2, where t is distance inward from the footprint edge divided by the maximum inward distance of its component. For buffered points and lines the normalising distance is their radius or half width. Polygon mound components use an estimated largest inscribed radius, refined from an interior grid. Irregular mounds follow their footprint, may have multiple summits, and holes affect the surface. This is a compact rounded profile with zero slope at its edge and crest, not a Gaussian.

Overlaps use the greatest positive and most negative displacement at each location, added together. Positive heights do not accumulate. Later features (then later rows within a layer) determine colour where footprints overlap. NULL colour restores the terrain palette there. Colours receive terrain shading and haze and are only drawn where the modified surface is visible.

The renderer intersects footprint boundaries with individual rays, adding samples at vertical faces and across curved profiles without refining the entire DEM. Circles and round buffers use 128-sided approximations. Numerical rays also include feature edge and central bearings. PNG columns remain a finite angular grid; a structure narrower than a pixel can be missed. Increase width and refine az.step and distance.step to assess convergence. The returned horizon still has the package's 0.01-degree grid. These are terrain-attached solids with no overhangs, openings, leaning stones, cast shadows or textures. The observer elevation is unchanged by reconstruction, so supply loc's ground elevation explicitly if the observer should stand on a reconstructed feature.

Save feature objects separately for reproducibility. They contain packed vector geometry and settings, but no DEM or PNG. The horizon stores compact settings, feature counts and a geometry checksum, with its PNG linked externally as usual.

Value

A serialisable skyscapeR.horFeature object. Pass it or a list of these objects as features to createHor with a DEM.

Scientific checks

See Also

createHor, demPalettes, exportStellarium, plot.skyscapeR.horizon

Examples

if (requireNamespace("terra", quietly=TRUE)) {
  points <- terra::vect(data.frame(x=c(-1.75,-1.751), y=c(51.19,51.191),
    h=c(2,3)), geom=c("x","y"), crs="EPSG:4326")
  stones <- horFeature(points, "stone", diameter=0.8,
    height_field="h", colour="grey50")
}
## Not run: 
banks <- horFeature("banks.shp", "bank", width=6, height=1.2,
  colour="#8A9B54")
ditches <- horFeature("ditches.shp", "ditch", width=4, depth=0.8,
  colour="#A18467")
hor <- createHor(dem="site-dtm.tif", loc=c(51.19,-1.75),
  max.distance=5000, features=list(stones, banks, ditches),
  image.dir="horizons")
plot(hor)

## End(Not run)

Find highest-density intervals for an orientation distribution

Description

Identify the angular regions containing a chosen proportion of a measured or summed orientation distribution at its highest densities.

Usage

hpdi(x, mass = 0.954)

Arguments

x

A skyscapeR.spd or skyscapeR.pdf object, or one data frame/list with numeric components x and y.

mass

Probability mass, greater than zero and at most one. Default is 0.954.

Details

A distribution with several peaks can give several disjoint intervals. The mass parameter applies to the selected regions together; the result describes concentration of the supplied density rather than significance against a null model.

Uses the existing discrete density-threshold method: sort sampled densities, find the threshold reaching the requested fraction of their sum, and include all points tied at that threshold. Consequently, the selected mass can exceed the requested value. Densities need not sum to one.

Coordinates must be finite and strictly increasing on an equally spaced grid. Missing grid points are permitted when gaps are integer multiples of the smallest observed step; omitted points are treated as zero mass and split intervals. This accommodates cutoff-trimmed azimuth distributions. Other irregular grids are rejected; no unequal-width integration is done. A single point is permitted and returns a zero-width interval.

Densities must be finite, nonnegative and have a positive total. If a saved distribution contains negative densities, regenerate it from the inputs with coordtrans before estimating intervals. Endpoints are sampled coordinates, not interpolated boundaries. Regions crossing the azimuth wrap are reported separately at the two ends of the grid; they are not joined into a circular interval.

Hyndman (1996) defines a highest-density region by a common density threshold. The discrete grid and tie rule above implement that principle for sampled curves.

Value

For a PDF object, a list of interval matrices, one per distribution, even for a single distribution. For SPD or x/y input, one matrix. Each matrix has columns start and end, with ordered endpoints and one row per contiguous region, sorted by start.

Validation

Known tied, truncated and disjoint test distributions returned the expected interval endpoints and achieved the requested minimum discrete mass. See D01 validation in the technical manual.

In D02 the default transformation grid split the middle 80 percent highest-density region of a three-mode ridge case; a finer grid recovered the three reference regions. See the D02 check in the technical manual.

Scientific checks

References

Hyndman, R. J. (1996). Computing and Graphing Highest Density Regions. The American Statistician 50, 120-126. doi:10.1080/00031305.1996.10474359.

See Also

az.pdf, dec.pdf, spd, plot.skyscapeR.pdf

Examples

xx <- seq(-6, 6, by=0.01)
hpdi(data.frame(x=xx, y=stats::dnorm(xx)), mass=0.95)

# Two separated peaks produce two ordered intervals:
yy <- stats::dnorm(xx, -3, 0.5) + stats::dnorm(xx, 3, 0.5)
hpdi(data.frame(x=xx, y=yy), mass=0.8)

# PDF objects always return a list:
Az <- az.pdf(az=c(90,120), unc=2, verbose=FALSE)
hpdi(Az)

Import user-defined constellation lines

Description

Read custom line connections for use in a sky sketch.

Usage

importConstellations(file, set = "custom")

Arguments

file

Path to a Stellarium legacy constellationship.fab text file.

set

Label for this collection, default "custom".

Details

Each non-comment line contains a unique figure identifier, the number of segments, then two Hipparcos numbers per segment. Endpoints describe separate pairs, not one continuous polygon. Blank lines and comments beginning with a hash are ignored. Non-negative segment counts and positive integer HIP identifiers are validated. Zero-segment records are retained with an empty HIP field and skipped when drawn. Repeated endpoints represent a single-star figure, drawn as a small ring. This supports Stellarium's legacy constellationship.fab format, not the JSON sky-culture format introduced in Stellarium 25.1. Only lines are imported, not artwork, labels, boundaries or star positions. Endpoint stars must be in skyscapeR's stellar catalogue; unavailable stars produce warnings when drawn. The import does not modify the bundled catalogue or register global names. Save the returned object with saveRDS(), or load the file in each script. Respect the source sky culture's attribution and redistribution terms.

Value

A data frame with the same columns as constellations, accepted by the display$constellations setting of sketchSky or the constellations argument of planisphere. Subset rows to select individual figures.

References

Stellarium User Guide, Adding Sky Cultures (legacy editions) and Sky Cultures (current editions): https://stellarium.org/guide/. Legacy example: https://github.com/Stellarium/stellarium/blob/v0.22.2/skycultures/western/constellationship.fab.

See Also

sketchSky, constellations

Examples

file <- tempfile(fileext=".fab")
writeLines("MyFigure 2 27989 25336 25336 25930", file)
figures <- importConstellations(file)
unlink(file)
figures[, c("name1", "HIP")]
## Not run: 
sky <- sketchSky(malta_horizons[[1]], time="2026/12/21 20:00",
  timezone="UTC",
  display = list(constellations = figures))
plot(malta_horizons[[1]], sky=sky)

## End(Not run)

Import a sky-masked photographic panorama

Description

Extract a numerical skyline from a transparent-sky panorama and attach the calibrated photograph.

Usage

importPanorama(
  file,
  loc,
  az.lim = c(0, 360),
  alt.lim = c(-90, 90),
  name = tools::file_path_sans_ext(basename(file)),
  calibrate = FALSE,
  points = NULL,
  alpha.threshold = 0.5,
  alt.unc = 0.5
)

Arguments

file

PNG with sky removed to transparency. Keep this file alongside saved horizon objects.

loc

WGS84 latitude, longitude and optional elevation in metres.

az.lim

True bearings of the left and right edges, increasing clockwise. A sector may cross north, e.g. c(330,30).

alt.lim

Altitudes of the bottom and top edges in degrees. Set these explicitly for a cropped panorama.

name

Site name.

calibrate

Open the interactive graphics picker. Choose Zoom and click two corners to enlarge a region. Add a control by clicking a landmark and entering its true azimuth, altitude or both. Finish to apply the fit.

points

Optional data frame with numeric x, y, az and alt. Pixel coordinates start at the upper-left image edge. Use NA for an unknown angle.

alpha.threshold

Minimum opacity counted as terrain, from above zero to one.

alt.unc

Assumed skyline altitude uncertainty in degrees.

Details

Choose controls according to what you know:

The picker samples the overview. Choose Zoom and click two corners to display the selected region at native pixel detail, then choose Add control point. Full-turn plots cut the calibrated view at north. In scripted controls use NA_real_ for each unknown angle. Levelling adjusts the near-horizon band. If an altitude shift takes image rows beyond the poles, only whole rows within the physical altitude range are kept. A one-point adjustment records the calibrated bounds and uses the original PNG. Keep it with the saved object. A tilt adjustment writes a levelled PNG in the working directory. Use a panorama with nominally linear angular axes and transparent sky above terrain in every column. A partial panorama supports altitude lookup within its photographed sector. Stellarium export requires a full turn.

Value

A skyscapeR.horizon object with a numerical profile, external PNG reference, angular bounds and control points. Use saveRDS() to save the object. Copy the displayed panorama PNG with the RDS and use relinkHor to reconnect a moved horizon or list.

Validation

H07 verified lookup inside the photographed sector, including across north. Seasonal and event searches requiring a complete skyline reject partial photographs. See the H07 check in the technical manual.

Extraction method and limitations

Sky detection uses the PNG alpha channel. In each image column the first pixel whose opacity reaches alpha.threshold defines the terrain edge. The function does not segment an ordinary opaque photograph by sky colour. Remove the sky to transparency beforehand and retain sky above terrain in every column. Trees, buildings and mask errors become part of the extracted skyline.

Calibration uses linear angular axes, origin shifts and, where supported by the controls, fitted scale or sinusoidal near-horizon tilt corrections. This is not a general camera/lens model or a full spherical photogrammetric adjustment. Wide-angle distortion, stitched-image parallax and inaccurate control measurements are not removed automatically. The supplied alt.unc is an assumed error, not an uncertainty estimated from the fit. Inspect independent field controls after calibration.

A partial panorama only supplies the photographed sector; it is unsuitable for functions requiring a closed full horizon. Supplying only latitude and longitude leaves observer elevation unknown. Add a finite measured elevation before using functions, such as sketchSky, that require it.

Scientific validation

H05 examines bearing and altitude errors at withheld synthetic landmarks. H05 scientific validation.

Scientific checks

See Also

hor2alt, exportPanorama

Examples

## Not run: 
# Known bearing at pixel (1240, 380) in a level, cropped panorama
anchor <- data.frame(x = 1240, y = 380, az = 96.4, alt = NA_real_)
h <- importPanorama("ridge.png", c(51.75, -9.37, 150),
                    az.lim = c(70, 120), alt.lim = c(-5, 12), points = anchor)
plot(h, show.skyline = TRUE)

## End(Not run)

Import a PeakFinder horizon and optional landscape drawing

Description

Bring a terrain-derived horizon into orientation and visibility calculations, optionally retaining foreground ridge lines for visual interpretation.

Usage

importPeakFinder(
  file,
  svg = NULL,
  elevation = NULL,
  alt.unc = 0.5,
  width = 4096,
  image.dir = getwd()
)

Arguments

file

Path to a PeakFinder Stellarium ZIP export.

svg

Optional path to the matching full-circle Vector SVG export.

elevation

Optional verified absolute observer elevation in metres.

alt.unc

Assumed horizon altitude uncertainty in degrees, a nonnegative scalar.

width

PNG width in pixels, an integer from 512 to 8192. Default 4096.

image.dir

Directory for generated PNGs; defaults to the working directory.

Details

The numerical horizon describes angular obstruction at the observer's location. A separate vector drawing supplies foreground detail but does not explicitly record its vertical angular calibration. Both exports are therefore needed to create a calibrated panorama PNG. Calculations always use the numerical horizon, never the PNG. Terrain data do not include every tree or building.

In PeakFinder choose Export, Horizon for Stellarium and save the ZIP. For an image also choose Export, SVG for printing, Silhouettes (Vector SVG), from 0 to 360 degrees, preferably picture format 16:2. Use exactly the same viewpoint and observer height for both. Contours (Bitmap SVG) is not supported. The PNG is a white terrain silhouette with dark foreground ridge lines and transparent sky, without labels or shading. Only PeakFinder's untransformed M/L vector path format is supported; edited or future formats may require adaptation.

Azimuth ruler positions calibrate horizontal coordinates. The upper envelope of the vector paths is fitted to y = intercept + slope * tan(altitude) using the ZIP horizon. Values at 0.01 degrees are excluded as potentially clipped. Calibration needs at least 20 matches spanning 180 degrees and 0.5 degrees of altitude relief. RMS and maximum angular residuals must not exceed 0.05 and 0.2 degrees. These are compatibility checks, not estimates of terrain accuracy. For low-relief, clipped profiles the importer can instead measure the alpha edge of the eight calibrated, north-first Stellarium textures. It checks coverage, concurrence with unclipped heights, and agreement with the SVG before using the texture-derived numerical horizon. Cropped or ambiguous tiles cannot supply this calibration. Calibration failure, unsupported SVGs or mismatched sites produce a warning and a horizon-only object.

Vector vertices are transformed to linear azimuth and altitude coordinates and rendered to a PNG. Its lower extent is -90 degrees (solid terrain below the drawing), preventing transparent holes when exported to Stellarium. The default width is 4096 pixels, about 0.088 degrees per pixel horizontally; the numerical horizon retains its own sampling. No image array is stored in the returned object. PNGs are read on demand as compact native rasters.

The default image directory is the working directory. A supplied directory is useful for project files. The object records an absolute PNG path and MD5 checksum. Saving it with saveRDS does not bundle the PNG. When moving a project, copy the PNG too and reconnect it with relinkHor. Missing or modified images trigger a warning and ordinary horizon plotting/export. Repeating an import with the same files and rendering settings reuses the PNG filename.

PeakFinder exports can report an elevation of 0 m plus eye height even at a mountain site. A warning flags this; use elevation to supply a verified absolute observer elevation. This override does not recalculate the downloaded horizon. The default altitude uncertainty of 0.5 degrees is an explicit working assumption, not a measured PeakFinder error estimate. Supply an appropriate value for research.

Value

A skyscapeR.horizon containing a periodically extended numerical horizon, site and source metadata, and, on successful calibration, metadata$image with the external PNG path, checksum, angular bounds and calibration diagnostics.

Scientific checks

References

PeakFinder, exported drawings attributed to PeakFinder under CC BY 4.0. Geometry conventions follow the Stellarium User Guide.

See Also

createHor, downloadHWT, plot.skyscapeR.horizon, exportStellarium

Examples

## Not run: 
hor <- importPeakFinder("landscape.zip") # warns that no PNG was created
hor <- importPeakFinder("landscape.zip", svg="panorama.svg",
                       image.dir="project-data/horizons", elevation=850)
plot(hor)
exportStellarium(hor, name="PeakFinder example")

## End(Not run)

Estimate solar declination at the June solstice

Description

Estimate the limiting solar declination at the June solstice for comparison with a structural sightline.

Usage

jS(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.00224,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

altitude

Altitude of the sun. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

The June solstice is represented by the positive obliquity of the ecliptic for the requested epoch. The result is geocentric when no site is supplied. With a site, the function subtracts the approximate parallax correction using latitude and target altitude. This obliquity-based target does not determine a solstice time or a sunrise or sunset bearing.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Validation

A05 checked the local June solar limit against annual obliquity and the specified parallax correction. See the A05 check in the technical manual.

Scientific checks

See Also

obliquity, dS, eq, zenith, antizenith, spatial.equinox, parallax.corr

Examples

# June Solstice geocentric declination for year 4001 BC:
jS(-4000)

# Topocentric declination for same year and latitude of 50 degres N:
jS(-4000, loc=50)

Convert a UT Julian date to local calendar date and time

Description

Express an ephemeris instant as a calendar date and clock time suitable for comparison with an observation or historical record.

Usage

jd2time(jd, timezone, calendar, verbose = F)

Arguments

jd

Finite numeric vector of UT Julian dates.

timezone

Timezone name or fixed offset; defaults to the value in skyscapeR.vars(). See Details.

calendar

Output calendar: G or Gregorian, J or Julian. Defaults to the package calendar setting, initially Gregorian.

verbose

Logical; display a conversion message. Default is FALSE.

Details

An instant is specified by its UT Julian date. To label it consistently, choose the calendar and the offset or civil timezone appropriate to the record. The conversion rounds to the nearest second, applies the offset at the rounded instant, handles day rollover and converts the day number with Swiss Ephemeris.

Fixed offsets may be numeric hours east of UTC (for example 5.5), or strings such as "UTC+05:30", "UTC-02" or "GMT+01". Offsets must lie between -14 and +14 hours. UTC, GMT and the empty string mean zero offset; an empty string does not select the system timezone.

Named zones listed by OlsonNames(), such as "Europe/London", use the installed timezone database for the actual Gregorian date, not a surrogate year. They are supported only for Gregorian years 1900-9999. Earlier dates require UTC or a fixed offset. For ancient-date workflows, set skyscapeR.vars(timezone="UTC") or provide timezone explicitly. The package's initial timezone remains Europe/London. Database versions may differ across systems; fixed offsets provide reproducible conversions.

Gregorian and Julian calendars are proleptic: no automatic calendar reform is applied. Astronomical year numbering is used: 0 is 1 BCE, -1 is 2 BCE. Fixed-offset input dates support years from -100000 to 100000. A timezone offset represents civil clock time, not local solar time. These functions apply clock offsets to a UT Julian day; they do not apply leap-second, UTC-to-UT1 or TT corrections. Leap-second input is rejected.

Output is rounded to the nearest whole second, including date rollover. The result does not contain a timezone or UTC offset. During a repeated local hour, two distinct instants can have identical output strings; retain the original Julian date or use a fixed offset for an unambiguous round trip.

Value

A character vector in YYYY/MM/DD HH:MM:SS format. Years are signed as needed and are not padded to four digits.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

time2jd, timestring, skyscapeR.vars

Examples

jd <- time2jd("2019/12/31 23:30:00", "UTC")
jd2time(jd, "UTC+02") # 2020/01/01 01:30:00
jd2time(jd, "Europe/Paris")
jd <- time2jd("-1/12/31 23:30:00", "UTC", calendar="J")
jd2time(jd, "UTC+02", calendar="J") # 0/01/01 01:30:00

Format a month and day as a calendar label

Description

Format a month and day for reporting recurring solar or stellar events within a year.

Usage

long.date(date)

Arguments

date

date in 'MM-DD' format

Details

A season or event table may need a day/month label without an epoch. The first two characters are the month number and characters four and five the day number; the separator occupies position three. The month is looked up in R's English month abbreviations. This formatting step does not validate a calendar date or convert between calendars.

Value

Character month-and-day labels such as "21 Jun", derived from the supplied month and day.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

time2jd, jd2time, timestring, BC.AD

Examples

long.date('01-01')
long.date('08-23')

Estimate magnetic declination at a site

Description

Estimate the correction between magnetic north and true north for the location and date of a field survey.

Usage

mag.dec(loc, date)

Arguments

loc

Latitude and longitude in degrees as a vector, matrix or data frame with one row per site, or a horizon object. An optional third column gives elevation.

date

One or more survey dates as Date objects or YYYY/MM/DD strings.

Details

Compass reduction depends on when and where the reading was taken. The function evaluates IGRF-14 through oce at sea level and returns east-positive declination. Supply a single site for several dates, a single date for several sites, or one date per site. Results follow input order. Other size combinations raise an error. The calendar date is converted to a decimal year using the actual length of that year at midnight UTC. Supported dates run from 1 January 1900 through 1 January 2030 inclusive. Site elevation is ignored by this model call.

Value

Numeric magnetic declination in degrees. Use it as the correction added to a magnetic bearing in reduct.compass.

Scientific validation

F01 examines magnetic and solar reductions against independent references. F01 scientific validation.

Scientific checks

References

Kelley, D. and Richards, C. oce: magneticField. https://dankelley.github.io/oce/reference/magneticField.html.

See Also

magneticField, reduct.compass

Examples

# Magnetic Declination for London on April 1st 2016:
loc <- c( 51.5074, -0.1278 )
mag.dec( loc, "2016/04/01" )
mag.dec(c(40, -8), c("2010/01/01", "2026/01/01"))

Entrance bearings of Maltese temples

Description

Compare the directions and angular widths of entrance corridors at the prehistoric Maltese temples.

Usage

data(malta_entrances)

Format

A tibble (also a data frame) with 32 rows and six columns.

Name

Structure name.

Latitude

Site latitude in degrees north.

Longitude

Site longitude in degrees east.

Az L

Azimuth of the left edge of the entrance, in degrees.

Az R

Azimuth of the right edge of the entrance, in degrees.

Phase

Archaeological phase assigned to the structure.

Details

The left and right bearings delimit the field of view from a structure. Preserve their order around north when deriving a centre and width, and specify how that sector is represented as a density. Latitude, longitude and phase support site-specific transformation and grouping. The companion horizon profiles provide the horizon altitudes used to translate bearings into possible declinations.

References

Lomsdalen, T. (2021). Viewscapes and Cosmology in the Prehistoric Temples of Malta. PhD Dissertation - University of Malta.

Silva, F. and Lomsdalen, T. (2025). ‘No easy way from the earth to the stars’: a new statistical approach to the orientation of the Maltese Temples. Archaeological and Anthropological Sciences doi:10.1007/s12520-025-02208-4

See Also

malta_horizons

Examples

data(malta_entrances)
mid_az <- (malta_entrances$`Az L` + malta_entrances$`Az R`)/2
plotAzimuth(mid_az)

DEM-derived horizon profiles for Maltese temples

Description

Account for the terrain visible from each Maltese temple when interpreting the orientation of its entrance.

Usage

data(malta_horizons)

Format

An unnamed list of 32 skyscapeR.horizon objects. Access a profile by position, for example malta_horizons[[1]].

metadata

Site name and georeference (latitude, longitude, elevation).

data

Horizon samples with columns az, alt and alt.unc. All three angles are in degrees.

Details

Tore Lomsdalen generated the profiles for his PhD research using Andrew Smith’s Horizon software and a 5 m DEM made available through Heritage Malta. The profiles describe how horizon altitude and its uncertainty vary with azimuth at each site. The list is unnamed; inspect each profile's metadata before pairing it with an entrance observation, especially after subsetting or reordering. Use the same matched profile when transforming a bearing distribution and when simulating its random-orientation null.

References

Lomsdalen, T. (2021). Viewscapes and Cosmology in the Prehistoric Temples of Malta. PhD Dissertation - University of Malta.

Silva, F. and Lomsdalen, T. (2025). ‘No easy way from the earth to the stars’: a new statistical approach to the orientation of the Maltese Temples. Archaeological and Anthropological Sciences doi:10.1007/s12520-025-02208-4

See Also

malta_entrances

Examples

data(malta_horizons)
plot(malta_horizons[[1]])
plot(malta_horizons[[10]])

Test orientations against a specified null model

Description

Use a Monte Carlo significance test to assess whether the measured orientations of a group of structures are compatible with a specified null model in azimuth or declination. The model can be shared across sites or specific to each site.

Usage

modelTest(
  pdf,
  model,
  unc = NULL,
  nsims = 1000,
  conf = 0.95,
  tails = 2,
  normalise = FALSE,
  .res = 0.01,
  ncores = NULL,
  verbose = TRUE,
  hor = NULL,
  .transform.res = 0.1,
  .prec = 0.1,
  .output.res = 0.01
)

Arguments

pdf

Empirical skyscapeR.pdf from az.pdf, dec.pdf or coordtrans. Its coordinate and the optional hor select the simulation path.

model

One shared data frame or an ordered list with one table per observation. The first column contains candidate coordinates in degrees and the second contains nonnegative discrete sampling weights, with at least one positive weight. On equally spaced grids, density heights can serve as weights.

unc

Optional replacement width in degrees of the input coordinate (azimuth on route 3). Use a standard deviation for normal, half the total span for triangular, or the family-specific half-width documented in az.pdf. Supply a scalar or one per observation. Omit to reuse stored measurement uncertainties or mean-shift transformed declination curves. See Details.

nsims

Number of simulations, at least two. Default is 1000.

conf

Confidence level as a fraction.

tails

1 for upper excesses, 2 for excesses and deficits.

normalise

Scale each summed density to unit area before comparison.

.res

Spacing of the empirical and simulated comparison grids in degrees. Default 0.01.

ncores

Worker count. By default use half the detected available logical cores, rounded down with a minimum of one. Set ncores=1 for serial execution. The simulation count and memory batch size can further limit workers. Verbose output reports the effective count.

verbose

Display simulation progress.

hor

Optional shared skyscapeR.horizon or an ordered list matching the empirical observations. With azimuth inputs, selects a declination test using individual coordinate transformations. Omit for routes 1 and 2.

.transform.res

Internal declination transformation spacing, as .res in coordtrans. Default 0.1 degrees.

.prec

Azimuth integration spacing for route 3, as in coordtrans. Default 0.1 degrees.

.output.res

Stored declination PDF spacing for route 3, as in coordtrans. Default 0.01 degrees.

Details

A proposed topographical or astronomical explanation can predict some orientations more frequently than others. Testing that explanation requires simulating its predicted distribution at the sites under study.

Silva and Lomsdalen (2025) extended the random-orientation framework of Silva (2020) to test specific hypotheses about temple orientations in Malta, including topographical and astronomical explanations. Here the hypothesis specifies the relative probability of each candidate orientation. A small global p-value is evidence against that particular model.

Input routes. There are three routes:

  1. modelTest(Az, az.model) compares azimuth inputs in azimuth.

  2. modelTest(Dec, dec.model) compares declination inputs in declination.

  3. modelTest(Az, az.model, hor=hor) compares azimuth inputs in declination. A shared horizon or an ordered list of one horizon per observation is accepted. Each observed azimuth density is transformed individually with coordtrans. Each simulation draws azimuth centres, reconstructs their measurement densities, and transforms each density through its corresponding horizon before summing. This propagates changes in width, asymmetry and peaks with azimuth, latitude and skyline. The function never shifts a fixed declination template on this route and does not transform the summed azimuth density as a shortcut.

Express model coordinates and uncertainties in the input coordinate. Supplying hor selects route 3 and requires azimuth empirical and model inputs. Transformation spacings are controlled by .transform.res, .prec and .output.res; .res controls only the final comparison grid. Atmospheric settings come from skyscapeR.vars and are recorded in the result. A uniform azimuth null matches the individual-transformation route of randomTest when candidate grids, measurement families, horizons, transformation settings and simulated draws match. Uniform declination weights generally describe a different null hypothesis.

Each simulation draws one centre per observation according to the weights in its model table. The function constructs an azimuth or declination density around each centre and sums these densities on the same comparison grid as the observed SPD. The observed measurement curves are used as supplied.

Measurement uncertainty. Direct measurement PDFs reuse the family selected in az.pdf or dec.pdf, including the observation's taper, survey error and triangular asymmetry. A direct triangular model is positioned by its mode. Overriding unc rescales its two sides in proportion; for the two softened uniform families the taper or survey-error SD stays fixed in degrees. On route 2, for declinations from coordtrans, omit unc to use each observation's own density as a template. A model draw represents the expected mean declination for that observation. The function calculates the density-weighted mean of its piecewise-linear curve and adds (draw minus mean) to every declination. For example, a curve with mean -17.6 degrees shifts by -4.4 degrees for a draw of -22 degrees. The shift preserves the curve's width, asymmetry and peaks before interpolation onto the comparison grid. It requires only the stored declination curve and assumes its shape applies at the modelled mean. A positive-weight candidate that would shift density beyond -90 or +90 degrees raises an error. An explicit unc selects a normal density around each simulated centre for transformed input. With normalise=TRUE, each final SPD has unit area.

Reading the result. The global p-value compares the departure of the entire observed curve with departures under the specified model. Local results use the largest qualifying cluster per simulation to adjust for searching the grid. Boundaries describe where departures were observed. The envelope is pointwise. Both tests use inclusive Monte Carlo ranks, with minimum p-value 1/(nsims + 1). See randomTest for the shared scoring rules, width threshold, treatment of ties and zero variance, and assumptions behind the adjustment. When a model was fitted to the same observations, its fitting procedure must be accounted for separately.

Running simulations. With a fixed seed, sampling in the calling session gives the same result for different worker counts. For grids larger than 16 MiB, allow about eight bytes of temporary disk space per simulation per grid point. Temporary files are removed on return or error.

Value

A skyscapeR.sigTest list with settings and global/local results in metadata, empirical density and null envelope in data.

Validation

In S03, independent scoring reproduced the azimuth and declination ranks on their respective grids. Build 2.0.9006 counts north once and reports one interval for a qualifying excess across north. Refit earlier azimuth tests to obtain the revised probabilities. See S03 validation in the technical manual.

In S02, identical candidate bearings produced identical directly constructed observed and simulated densities on build 2.0.9008. Global rejection at the 5 percent level ranged from 4.35 to 5.50 percent under the six matched null designs. See the S02 check in the technical manual.

Model weights and interpretation

Weights are discrete sampling probabilities up to proportionality. If a continuous model is evaluated on an uneven coordinate grid, density heights alone do not represent probability mass; construct weights that account for the bin widths before calling the function. Put site-specific model tables in the same order as the observed measurements.

A large p-value does not prove the proposed explanation or measure its probability. The test asks whether the specified model is incompatible with the observed departure statistic. Alternative models can remain compatible. The simulations do not automatically represent dependence between sites, selection after viewing the data, or uncertainty in fitted model parameters. See randomTest for study-design and Monte Carlo limitations.

Scientific checks

References

Silva, F. (2020). A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology. Journal of Archaeological Science, 118, 105138. doi:10.1016/j.jas.2020.105138.

Silva, F. and Lomsdalen, T. (2025). ‘No easy way from the earth to the stars’: a new statistical approach to the orientation of the Maltese temples. Archaeological and Anthropological Sciences, 17, 96. doi:10.1007/s12520-025-02208-4.

Maris, E. and Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. Journal of Neuroscience Methods. doi:10.1016/j.jneumeth.2007.03.024.

Sassenhagen, J. and Draschkow, D. (2019). Cluster-based permutation tests of MEG/EEG data do not establish significance of effect latency or location. Psychophysiology. doi:10.1111/psyp.13335.

Dufour, J.-M. (2006). Monte Carlo tests with nuisance parameters: A general approach to finite-sample inference and nonstandard asymptotics. Journal of Econometrics, 133, 443-477. doi:10.1016/j.jeconom.2005.06.007.

North, B. V., Curtis, D. and Sham, P. C. (2002). A note on the calculation of empirical P values from Monte Carlo procedures. American Journal of Human Genetics, 71, 439-441. doi:10.1086/341527.

See Also

az.pdf, dec.pdf, coordtrans, spd, randomTest, plot.skyscapeR.sigTest

Examples

d <- dec.pdf(dec = c(-18, 12), unc = c(0.8, 1.4))
m <- list(data.frame(x = -20:-16, w = 1), data.frame(x = 10:14, w = 1))
set.seed(42)
fit <- modelTest(d, m, nsims = 10, .res = 0.5,
                 verbose = FALSE)
print(fit)
## Not run: 
set.seed(42)
fit <- modelTest(d, m, nsims = 5000, ncores = 2)
# For transformed observations, model coordinates specify mean declinations.
Az <- az.pdf(az = c(87, 110), unc = 2)
hor <- createHor(az = c(0, 360), alt = c(0, 0), alt.unc = 0.1, loc = c(35, -8))
# Route 3: both inputs in azimuth, test in declination.
az.model <- data.frame(x = seq(0, 359.9, by = 0.1), w = 1)
fit <- modelTest(Az, az.model, hor = hor, nsims = 100, ncores = 1)
# Route 2: both inputs in declination, shift the transformed templates.
Dec <- coordtrans(Az, hor)
fit <- modelTest(Dec, data.frame(x = c(-22, 18), w = c(1, 1)))

## End(Not run)

Calculate the illuminated fraction of the Moon

Description

Determine how much of the lunar disc is illuminated at the time of an observation or proposed lunar event.

Usage

moonphase(time, timezone, calendar)

Arguments

time

One or more UT Julian dates, or local date-time strings in the form YYYY/MM/DD HH:MM:SS.

timezone

Timezone for civil timestamps. Use UTC or a fixed offset for dates before 1900. See time2jd for named zones and offsets.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

Details

Lunar illumination can be used to screen events for a nearly full Moon. The routine converts calendar input to UT Julian dates when needed and obtains the illuminated fraction from the lunar phenomena calculation in Swiss Ephemeris. Values near zero indicate a nearly new Moon and values near one a nearly full Moon; the fraction alone cannot distinguish waxing from waning.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

Numeric illuminated fraction of the lunar disc, one value per input time. At full illumination the fraction is 1.

Validation

In A02, all 108 illuminated fractions agreed with the direct Swiss Ephemeris calculation across 54 epochs and two file generations. This checks the R interface. Observed lunar photometry was outside the study. See the A02 study in the skyscapeR technical manual.

Scientific validation

A07 examines independent crossover selection and sensitivity to the illumination cutoff. A07 scientific validation.

Scientific checks

See Also

swe_pheno_ut, EFM

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Moonphase at noon GMT on Christmas day 2018:
  moonphase('2018/12/25 12:00:00', 'GMT')
}

Estimate northern major lunar standstill declination

Description

Estimate the northern declination limit of a major lunar standstill for comparison with a proposed alignment.

Usage

nMjLX(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.952,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.952 degrees for the Moon.

altitude

Altitude of the Moon. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

A major standstill defines a limiting lunar declination at the epoch of interest. The model uses the obliquity plus a fixed 5.145 + 0.145 degrees, then applies the positive sign for the northern limit. With a location it subtracts the parallax correction for latitude and altitude. The default lunar parallax is 0.952 degrees. This approximation defines a target limit; it does not search a time series for an actual lunar event.

Sprajc (2016) describes the limits set by obliquity and the mean lunar inclination. This package also includes the fixed 0.145-degree term above.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Scientific validation

A06 examines geocentric lunar and planetary limits against independent extrema. A06 scientific validation.

Scientific checks

References

Ć prajc, I. (2016). Lunar alignments in Mesoamerican architecture. Anthropological Notebooks 22(3), 61-85.

See Also

nmnLX, smnLX, sMjLX, parallax.corr

Examples

# Northern major Lunar Extreme geocentric declination for year 2501 BC:
nMjLX(-2500)

# Topocentric declination for same year and latitude of 50 degrees N:
nMjLX(-2500, loc=50)

Estimate northern minor lunar standstill declination

Description

Estimate the northern declination limit of a minor lunar standstill for comparison with a proposed alignment.

Usage

nmnLX(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.952,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.952 degrees for the Moon.

altitude

Altitude of the Moon. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

A minor standstill defines a limiting lunar declination at the epoch of interest. The model uses the obliquity minus a fixed 5.145 + 0.145 degrees, then applies the positive sign for the northern limit. With a location it subtracts the parallax correction for latitude and altitude. The default lunar parallax is 0.952 degrees. This approximation defines a target limit; it does not search a time series for an actual lunar event.

Sprajc (2016) describes the limits set by obliquity and the mean lunar inclination. This package also includes the fixed 0.145-degree term above.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Scientific validation

A06 examines geocentric lunar and planetary limits against independent extrema. A06 scientific validation.

Scientific checks

References

Ć prajc, I. (2016). Lunar alignments in Mesoamerican architecture. Anthropological Notebooks 22(3), 61-85.

See Also

smnLX, nMjLX, sMjLX, parallax.corr

Examples

# Northern minor Lunar Extreme geocentric declination for year 2501 BC:
nmnLX(-2500)

# Topocentric declination for same year and latitude of 50 degrees N:
nmnLX(-2500, loc=50)

Calculate the obliquity of the ecliptic

Description

Estimate the tilt of the ecliptic at a proposed epoch to set solar and lunar declination limits.

Usage

obliquity(year = skyscapeR.env$cur.year)

Arguments

year

Year for which to calculate the obliquity. Historical labels such as "3700 BC" are accepted by astroYear. Defaults to present year as given by Sys.Date

Details

The tilt changes over archaeological timescales. For each supplied astronomical year the calculation uses Gregorian 1 January at noon UT, requests the obliquity/nutation record from Swiss Ephemeris and returns its first element, the true obliquity in degrees. An annual value is a reference for limiting declinations rather than a search for the instant of solstice.

Value

Numeric obliquity of the ecliptic in degrees, one value per astronomical year.

Validation

A05 checked the January true obliquity at modern and prehistoric test epochs against direct engine values. See the A05 check in the technical manual.

Scientific checks

References

Laskar, J. et al. (2004), A long-term numerical solution for the insolation quantities of the Earth, Astron. Astroph., 428, 261-285, doi:10.1051/0004-6361:20041335.

See Also

swe_calc_ut, jS, dS

Examples

# Obliquity for year 4001 BC:
obliquity("4001 BC")

Trace the path of a celestial body at a site

Description

Trace the daily path of a fixed declination across the sky as seen from a site.

Usage

orbit(dec, loc, refraction, atm, temp, res = 0.25)

Arguments

dec

Declination of object.

loc

Location, either a skyscapeR.horizon or a vector containing the latitude and longitude of location, in this order.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

res

The resolution (in degrees of RA) with which to calculate the path.

Details

Latitude and declination determine where a diurnal track can meet the terrain. The function sweeps equatorial right ascension through 360 degrees at the requested angular step and converts each position to horizontal coordinates with the selected refraction and atmosphere settings. It retains altitudes above -20 degrees and sorts the points by azimuth. A horizon object supplies the location; the stored track itself includes no test of terrain obstruction or event times.

Value

A skyscapeR.orbit list with az and alt vectors in degrees, ordered by azimuth, plus the input declination (dec) and location (georef). The sampled track retains altitudes above -20 degrees.

Validation

In A08, coordinates on the two plotted solar-limit tracks recovered their source declinations by spherical inversion. See the A08 check in the technical manual.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

See Also

plotAzimuth, plotBars, sketchSky, planisphere

Examples

# Visible path of sun on june solstice on year 4001 BC from London:
sun.dec <- jS(-4000)
london.lat <- 51.5074 #N
london.lon <- -0.1278 #W
loc <- c( london.lat, london.lon, 0 )
path <- orbit(sun.dec, loc)
plot(path$az, path$alt, ylim=c(0,90), type='l', xlab='AZ', ylab='ALT', col='red', lwd=2)

Estimate the parallax correction to declination

Description

Estimate how the observer's position on Earth shifts a solar or lunar target declination relative to its geocentric value.

Usage

parallax.corr(parallax, loc, altitude = 0)

Arguments

parallax

Average parallax to correct (e.g. 0.00224 for the Sun, or 0.952 for the Moon)

loc

This can be either the latitude of the location, or a skyscapeR.horizon object.

altitude

Altitude of the celestial object. Defaults to 0 degrees.

Details

The limiting-declination functions subtract this approximate correction from their geocentric target. The correction in degrees is the supplied parallax multiplied by the cosine of altitude and sine of latitude, with the angular arguments evaluated in degrees. The sign therefore reverses between hemispheres. This scalar approximation is distinct from computing an instantaneous topocentric ephemeris.

Ruggles gives an archaeological example of applying mean lunar parallax in a declination calculator.

Value

Numeric declination correction in degrees. The sign depends on latitude.

Validation

A05 compared the returned correction with the signed spherical approximation in both hemispheres. See the A05 check in the technical manual.

Scientific checks

References

Ruggles, C. L. N. Basic declination calculator. https://web.cliveruggles.com/tools/declination-calculator.

See Also

skyObject, jS, dS, eq, nmnLX, smnLX, nMjLX, sMjLX, obliquity

Examples

# Parallax correction for the moon, as seen from latitude 50ÂșN and at 0Âș altitude
parallax.corr(0.952, 50, 0)

Extreme declinations for five visible planets

Description

Estimate the most northerly and southerly declinations reached by a visible planet near an archaeological epoch.

Usage

planet.extremes(obj, year, loc = NULL, epoch)

Arguments

obj

Planet name, with this capitalisation: Mercury, Venus, Mars, Jupiter or Saturn.

year

Year for which to do calculations. Historical labels such as "3700 BC" are accepted by astroYear.

loc

This can be either a skyscapeR.horizon object, or a vector with the latitude, longitude and elevation of the site, in this order.

epoch

Earlier argument name for year, retained for existing scripts.

Details

An epoch alone does not specify the planet's position in its cycle. The search extends three quarters of the package's planet-specific period on either side of the epoch, rounds the limiting years, and samples at daily intervals from noon UT on 1 January of the start year to the corresponding date in the end year. Each sample uses body.position and the requested site if supplied. The returned extrema are the range of these samples; finer extrema can fall between sampled instants.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A list containing planet, min.dec and max.dec. The two declinations are extrema of daily samples and are expressed in degrees.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific validation

A06 examines geocentric lunar and planetary limits against independent extrema. A06 scientific validation.

Scientific checks

See Also

spatial.equinox, zenith, antizenith, solar.date, findTargets, EFM

Examples

## Not run: 
# Searches across multiple planetary cycles; may take more than five seconds.
if (requireNamespace("swephRdata", quietly = TRUE)) {
  planet.extremes('Jupiter', 2023)
  
  planet.extremes('Venus', "4001 BC")
}

## End(Not run)

Draw a planisphere for a site and epoch

Description

Map the stars that can enter a site's sky at a chosen epoch, with the celestial equator and ecliptic as optional references.

Usage

planisphere(
  year,
  lat,
  max.mag = 6,
  show.ecliptic = TRUE,
  col.ecliptic = "#A9542E",
  show.equator = TRUE,
  col.equator = "#597575",
  star.col = "#23383A",
  epoch,
  show.milky.way = TRUE,
  show.galactic.equator = FALSE,
  constellations = NULL,
  col.constellations = "#638582",
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

year

The epoch (year) for which the planisphere is calculated. Historical labels such as "3700 BC" are accepted by astroYear.

lat

Observer latitude in degrees north, between -90 and 90.

max.mag

Faintest catalogue magnitude drawn as a star symbol (default 6). This does not filter constellation line endpoints.

show.ecliptic

Whether to display the ecliptic (TRUE or FALSE).

col.ecliptic

Colour of the ecliptic line (default ochre).

show.equator

Whether to display the celestial equator (TRUE or FALSE).

col.equator

Colour of the celestial equator (default muted grey-green).

star.col

Colour of the star symbols (default dark grey-green).

epoch

Earlier argument name for year, retained for existing scripts.

show.milky.way

Draw the Milky Way behind the stars (default TRUE). Set to FALSE for a chart without the band.

show.galactic.equator

Draw the Galactic equator as a dash-dot line. Default FALSE.

constellations

Optional constellation selection: a bundled set such as "modern", "chinese" or "chinese_mansions", figure names or identifiers, or a table from importConstellations. The default NULL draws no constellation lines.

col.constellations

Colour of the constellation lines (default muted teal).

show.legend

Show chart pole, latitude, epoch, magnitude limit and the enabled layer key. FALSE centres the bare chart, keeping its data and right-ascension ticks.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

The default star layer draws individual Pleiades members and omits integrated clusters and other nonstellar entries. The full catalogue remains available for target searches and phase calculations.

The chart compares the accessible part of the celestial sphere with a catalogue sky at the chosen year. Catalogue stars are filtered by magnitude and by the implemented declinations that rise above a level geometric horizon. Northern latitudes use the north celestial pole; southern latitudes use the south celestial pole. Polar distance sets radius, and right ascension sets angle with opposite handedness for the two poles. Magnitude controls symbol size, and hour labels are placed every three hours. The optional ecliptic uses daily solar positions over a year, using geocentric coordinates without atmospheric refraction. The plot is not an instantaneous view through a site's measured horizon. The Milky Way uses the same diffuse-light tracing as sketchSky(), with dark cutouts and two brighter tiers referenced to the whole-band mean. Source: NASA/Goddard SVS and ESA/Gaia/DPAC, Deep Star Maps 2020. It is a fixed sky map rotated to the requested epoch with Swiss Ephemeris precession and nutation. Its width is illustrative. It does not predict visibility or reconstruct the Galaxy’s internal evolution.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

Draws the polar chart on the active graphics device and invisibly returns the saved xpd, mar and pty graphics settings.

Constellation patterns

Constellation segments follow the shorter great-circle arc between catalogue endpoints at the requested epoch. They use the same polar projection as the stars and are clipped to the chart's accessible sky. Faint endpoints remain available for line drawing even when no star symbol is shown. Missing catalogue endpoints generate a warning and their segments are omitted. These are line figures; repeated endpoints mark single-star figures with small rings. They are not constellation boundaries or lunar-mansion sectors. See constellations for sources, licences and historical limitations.

Projection and visibility limits

This is a polar azimuthal equidistant chart. For latitude at or above zero, radius is 90 minus declination and right ascension increases clockwise from the top. For negative latitude, radius is 90 plus declination and right ascension increases anticlockwise. The chart radius is 180 minus absolute latitude; a non-round cutoff is retained exactly. All layers use this same projection. At the equator the north-polar convention is used.

Stars are included when their upper culmination is strictly above a level geometric horizon; stars that only touch it are excluded. This is potential annual access to that part of the sky, not visibility at any particular time. There is no date/time of night, local terrain, atmospheric extinction, moonlight or twilight detection model. Magnitudes are fixed catalogue values, and point size is a graphical brightness indicator. For a particular site and instant use sketchSky with a georeferenced horizon.

Scientific checks

References

NASA/Goddard Space Flight Center Scientific Visualization Studio (2020). Deep Star Maps 2020. https://svs.gsfc.nasa.gov/4851/.

Astrodienst. Swiss Ephemeris programmer's manual. https://www.astro.com/swisseph/swephprg.htm.

See Also

plotAzimuth, plotBars, orbit, sketchSky

Examples

## Not run: 
if (requireNamespace("swephRdata", quietly = TRUE)) {
  planisphere(2023, lat=50, max.mag=6, show.milky.way=FALSE, show.galactic.equator=TRUE)
  planisphere(2023, lat=-35, max.mag=6)
  planisphere(2023, lat=40, max.mag=3, constellations="chinese_mansions")
}

## End(Not run)

Plot a site horizon and celestial targets

Description

Inspect the terrain along a site's horizon and compare it with the apparent paths of candidate celestial targets.

Usage

## S3 method for class 'skyscapeR.horizon'
plot(
  x,
  show.az = (!missing(xrange) || !missing(xlim)),
  xrange,
  yrange,
  obj,
  col.ground = NULL,
  col.sky,
  use.image = TRUE,
  ...,
  show.skyline = NULL,
  sky = NULL,
  xlim,
  ylim,
  fastLoad = FALSE,
  show.legend = TRUE,
  style = NULL
)

Arguments

x

Object of skyscapeR.horizon format.

show.az

Logical that controls whether to display azimuth values or cardinal directions. Defaults to TRUE when xrange is supplied.

xrange

Azimuth range for plotting.

yrange

Altitude range for plotting. By default one degree of altitude occupies the same distance as one degree of azimuth on the device.

obj

A skyscapeR.object from skyObject, or a list of these objects. Each group retains its own epochs and styles for displaying the paths of celestial objects.

col.ground

Silhouette colour. NULL uses a dark muted foreground for natural skies, pale grey-green for publication colour or grey for monochrome.

col.sky

Earlier name for a solid sky colour. Prefer sky.

use.image

Use an attached external panorama PNG when available. Default TRUE. Missing or changed files warn and fall back to the numerical silhouette.

...

Additional arguments to be passed to plot.

show.skyline

Draw the numerical skyline. By default the line appears only without a panorama PNG.

sky

A colour string or a background from sketchSky or stellariumSky.

xlim

Earlier name for xrange.

ylim

Earlier name for yrange.

fastLoad

Use a sampled PNG for quick plots. New photographic imports store a preview. For older horizons the first preview loads the image. The numerical skyline and celestial tracks retain their precision.

show.legend

Display the key for celestial tracks. The angular axes are always drawn.

style

Frame and silhouette style. A sketch supplies its stored style by default. Without a sketch the default is "publication-colour". Other choices are "natural" and "publication-mono". Supplied panorama pixels and sky objects retain their own rendering.

Details

A track meeting the horizon identifies a possible rise or set direction for that declination. The horizontal axis is true bearing and the vertical axis is angular altitude. The function fills the terrain below the stored profile and can overlay diurnal tracks computed for the observing location. Refraction affects those tracks. Rescaling the display or changing its colours does not change the underlying horizon. Add lines or polygons in azimuth and altitude immediately after plotting. Set par(mfrow=c(2,1)) before plotting to stack two horizons.

For a two-year epoch range, draw tracks for the stored minimum and maximum declinations, using the session refraction setting for both tracks. Line styles are taken from the target object; older objects without them use solid lines of width 1.

A horizon with an attached DEM, PeakFinder or photographic PNG displays the image by default. Add show.skyline = TRUE to inspect its numerical profile, or use.image = FALSE to draw the silhouette alone. With xrange supplied, azimuth labels default to degrees. A partial photograph initially opens on its recorded sector. An image-backed horizon or a supplied sky uses a 2:1 plot box. Copy the PNG with the saved horizon and use relinkHor() after moving it. With automatic altitude limits, a 30-degree azimuth sector shows 15 degrees of altitude.

Value

Draws the horizon and returns the session atmosphere invisibly in a list.

Validation

W01 checked the skyline ordinate and azimuth viewport on flat and raised profiles, including natural and publication sky overlays. See the W01 check in the technical manual.

Layers and coordinate consistency

A reusable sky is calculated for its own stored location and instant. Pair it with the horizon used to create it; drawing a saved sky does not recalculate its positions for another observer. Celestial reference tracks from skyObject use the plotted horizon's location and session atmosphere. Keep that atmosphere consistent with the stored sketch when comparing a track with a disc or point symbol.

The foreground masks sky layers geometrically. It does not make the sky object an extinction or visibility calculation through the terrain. Image calibration and numerical skyline agreement remain the responsibility of the horizon source. Azimuth-altitude plotting is a cylindrical display, with increasing horizontal distortion towards the zenith. Retain consistent ranges when comparing styles, epochs or constellation traditions.

Scientific checks

See Also

downloadHWT, skyObject

Examples

# Plot a bundled Maltese horizon:
hor <- malta_horizons[[1]]
plot(hor)

# Add the paths of the solstices and equinoxes sun in the year 1999 BC:
tt <- skyObject('solar extremes', epoch=-2000, col='blue')
plot(hor, obj=tt)
# Compare the bounding tracks across a range of years:
hor <- createHor(c(0,360), c(2,2), loc=c(35,-8,25))
targets <- skyObject('solar extremes', epoch=c("4001 BC", "2001 BC"), col='red')
plot(hor, obj=targets)

Plot orientation probability distributions

Description

Compare the uncertainty distributions of individual orientations or examine how a single sightline was transformed to declination.

Usage

## S3 method for class 'skyscapeR.pdf'
plot(
  x,
  index,
  hdr = 0.954,
  show.az,
  xrange,
  col = NULL,
  ...,
  az,
  hor,
  xlim,
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

x

A skyscapeR.pdf object created with either az.pdf or coordtrans

index

A value to indicate which distribution to plot, when only one is desired.

hdr

High density region to highlight. Defaults to 0.954

show.az

Deprecated and ignored, with a warning when supplied. Provide both az and hor for the combined panels, or omit both for distributions alone.

xrange

Range of x-axis to plot.

col

Fill colour for highest-density regions. NULL uses the current style.

...

Additional arguments to be passed to plot.

az

Original azimuth skyscapeR.pdf, in the same order and with the same number of distributions as x. Supply together with hor to show combined panels for a single declination distribution.

hor

Original horizon object, or a list of horizons in the same order and with the same length as the distributions in x. Supply with az.

xlim

Earlier name for xrange.

show.legend

Show the HDR mass above stacked densities. The linked diagnostic always identifies its component panels and reports the numerical interval or intervals.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

Individual curves reveal whether measurements overlap or have disjoint high-density regions. In the stacked view, each selected density is scaled by its own peak for display and its highest-density regions are shaded using hpdi. Heights across different rows therefore do not measure relative probability mass. Use the linked panels for one transformed observation to inspect how its source azimuth distribution and horizon produce the declination distribution. Its annotation gives the measurement name and the highest-density declination interval or intervals containing the requested probability mass. Every disjoint component is listed in the HDR readout. Standalone curves have a fixed label column.

With neither source input supplied, plot the distributions alone. With both az and hor, show the information, azimuth, transformation and declination panels. A single index is required for combined panels. Supplying only one source input is an error, as is supplying source inputs for an azimuth distribution. Source inputs must be named explicitly.

Supply the original sources in measurement order. Counts and structure are checked, but the function cannot verify their identity. The transformation curve uses the refraction, pressure and temperature recorded with the result.

Value

Draws the selected probability distributions and requested intervals on the active graphics device.

Validation

In W01 the shaded components matched the two intervals returned by hpdi() for a bimodal density. See the W01 check in the technical manual.

Scientific checks

See Also

az.pdf, dec.pdf, coordtrans, hpdi

Examples

Az <- az.pdf(az=c(87,93), unc=3, verbose=FALSE)
hor <- createHor(c(0,360), c(2,2), loc=c(35,-8,25))
Dec <- coordtrans(Az, hor, verbose=FALSE)
plot(Dec)
plot(Dec, index=1, az=Az, hor=hor)

Plot an orientation significance test

Description

Locate the orientations at which the observed summed density departs from the simulated comparison envelope. New tests use an envelope pooled from the observation and simulations.

Usage

## S3 method for class 'skyscapeR.sigTest'
plot(
  x,
  xrange,
  title = NULL,
  col = NULL,
  show.pval = TRUE,
  show.local = FALSE,
  pal = NULL,
  ...,
  obj = NULL,
  xlim,
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

x

A skyscapeR.sigTest object created with randomTest

xrange

Range of x-axis to plot.

title

Title to add to the plot.

col

Observed density colour. NULL uses the current style.

show.pval

Logical to control whether to print the global p-value. Default is TRUE.

show.local

Draw a separate panel on the same angular scale, with Excess and Deficit rows. Default FALSE. Symbols are ***, **, *, + and an open circle, with upper cutoffs 0.001, 0.01, 0.05 and 0.10. The open circle is centred at the same height as the stars and marks values above 0.10.

pal

Deficit and excess colours in that order. NULL uses the current style.

...

Additional arguments to be passed to plot.

obj

A skyObject or list of target groups for a density or significance plot. Declination plots show single epochs as lines and epoch ranges as bands. Azimuth plots use each group's site latitude to mark rising and setting boundary bearings at a geometric level horizon.

xlim

Earlier name for xrange.

show.legend

Display the density/envelope key and any local significance symbol key. show.pval independently controls the numeric global p-value.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

The observed curve and envelope use the azimuth or declination grid stored in the test result. The two-tailed display shades between its lower and upper pointwise bounds; the one-tailed display shades up to the upper bound from zero. Optional annotations show the stored global p-value and the local intervals, coloured by deficit or excess and labelled by p-value symbols. The observed and envelope curves jointly set the visible vertical range. The lower panel identifies adjusted and legacy unadjusted local results. The plot reads the fitted result without repeating the simulations. New local values use maximum-cluster adjustment under the complete null; cluster endpoints remain descriptive, not confidence limits. Legacy fits retain their original unadjusted values. Interpret local regions alongside the whole-curve test. The x axis uses more closely spaced labelled angular ticks and shorter unlabelled subdivisions. Tick spacing adapts to the displayed range and physical plot width, including when the local significance panel is shown.

Value

Draws the empirical density and pointwise comparison envelope. Optional annotations display the global p-value and local regions.

Validation

The tested public fits plotted the stored local interval midpoints and significance symbols. A wrapped interval has start greater than end. A plot spanning the full turn displays its two visible segments with the same adjusted probability. See S03 validation in the technical manual.

W01 checked clipped local intervals, the pointwise envelope and the global probability label against the stored fit. See the W01 check in the technical manual.

Scientific checks

See Also

randomTest, modelTest, print.skyscapeR.sigTest

Examples

az <- az.pdf(az = c(85, 95, 112), unc = 3, verbose = FALSE)
set.seed(42)
fit <- randomTest(az, nsims = 10, ncores = 1, .res = 2, verbose = FALSE)
plot(fit)

Plot a summed orientation density

Description

Visualise concentrations of orientation density across a group of structures.

Usage

## S3 method for class 'skyscapeR.spd'
plot(
  x,
  xrange,
  yrange,
  title = NULL,
  col = NULL,
  shading = TRUE,
  ...,
  obj = NULL,
  xlim,
  ylim,
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

x

A skyscapeR.spd object created with spd

xrange

Range of x-axis to plot.

yrange

Range of y-axis to plot.

title

Title to add to the plot.

col

Observed density colour. NULL uses the current style.

shading

Logical to control whether to color the entire distribution. Defaults to TRUE

...

Additional arguments to be passed to plot.

obj

A skyObject or list of target groups for a density or significance plot. Declination plots show single epochs as lines and epoch ranges as bands. Azimuth plots use each group's site latitude to mark rising and setting boundary bearings at a geometric level horizon.

xlim

Earlier name for xrange.

ylim

Earlier name for yrange.

show.legend

Show the observed-curve and celestial-target key when target overlays are supplied.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

A peak can arise where several uncertain sightlines coincide. The horizontal axis uses the summed curve's stored coordinate and the vertical axis its density. Optional shading fills the area beneath the curve; changing colours or axis limits does not renormalise it. Whether its integral is one depends on the normalisation used when creating the object. Assess departures from a specified null using a significance test.

Value

Draws the summed density against its angular coordinate on the active graphics device.

Validation

In W01 the drawn line matched the stored coordinates and heights of the summed density. See the W01 check in the technical manual.

Scientific checks

See Also

spd, plot.skyscapeR.pdf

Examples

az <- az.pdf(az = c(85, 92), unc = 2, verbose = FALSE)
plot(spd(az))

Plot seasonal stellar visibility

Description

Compare the seasonal visibility of one or more stars at the modelled site and epoch. Each result shows the stellar name, designation and epoch. To compare one star across epochs, compute a phase object for each year and pass the second object to plot as its second argument.

Usage

## S3 method for class 'skyscapeR.starphases'
plot(
  x,
  y,
  show.labels = TRUE,
  show.legend = TRUE,
  show.grid = TRUE,
  sort.by,
  pal,
  ...,
  layout = c("auto", "linear", "circular"),
  style = "publication-colour"
)

Arguments

x

A star phase result.

y

A second object of skyscapeR.starphases format or a list of skyscapeR.starphases objects for plotting (see Examples).

show.labels

Logical. Mark annual events for a single result in either layout. Defaults to TRUE.

show.legend

Show a legend for seasons present among the plotted stars (default TRUE). For circular plots FALSE also hides titles, site/epoch text and all layer or event callouts. The seasonal scale stays visible. Linear plots keep their data and event labels.

show.grid

Draw monthly dividers through each ring or strip. Defaults to TRUE. Set FALSE to omit the monthly divisions and retain the seasonal axis.

sort.by

Optional ordering by catalogue magnitude ("mag"), first R-only sample ("rise") or first S-only sample ("set") on the stored cycle. This is not sorting by the dated heliacal event. Missing classes are placed last; omission retains input order.

pal

Five colours in the order RS (rise and set), R (rise only), S (set only), V (curtailed passage) and I (arising and lying hidden). The default uses five colours from the plot style. Monochrome adds textures to distinguish the classes. Supply all five even when only some seasons occur.

...

Additional arguments to be passed to plot.

layout

"auto" and "circular" draw a single ring or concentric rings in input (or requested sort) order from the outside inward. Leaders connect the layer identifiers to their rings. Select "linear" for strips. Supply this argument by name.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

Read each colour as a daily model classification: visible rising and setting, rising only, setting only, visible without a qualifying near-horizon passage, or invisible. The function plots the stored phase sequence on a 365-day scale and can label seasons or display a legend. A single result defaults to a circular view, advancing clockwise from December solstice. Further results use concentric rings with one leader per displayed layer; optional sorting uses the stored apparent magnitude or seasonal onset. Changing the display does not recalculate the visibility thresholds. Use plot(first, list(second, third)) to compare results.

Value

Draws on the active graphics device and returns NULL invisibly.

Validation

W01 checked season boundaries, event positions, quarterly landmarks and star, site and epoch labels in linear and circular layouts. See the W01 check in the technical manual.

Seasonal axis and comparison

The axis is a 365-sample synthetic solar-longitude cycle anchored at December solstice. Equinoxes and solstices mark quarter-cycle positions. The monthly dividers mark twelve equal intervals of 30 degrees in solar longitude, beginning at December solstice. For calendar dates use the underlying result's metadata$events$date.julian, as described in star.phases.

Objects may represent different stars, epochs, sites or model assumptions. Shared star, epoch and site appear once. Different epochs of the same star label individual rings or rows. Mixed comparisons identify both star and year. Hold the site, extinction and other inputs fixed for a controlled epoch comparison, or state their differences in the figure caption. Names on the supplied list can override the displayed star names. The legend contains only the union of season classes present in the plotted objects.

Event annotations follow the event table. The Schaefer first-morning and last-evening markers use the solar longitude of the predicted local date. Passage bands and the two other markers follow the Purrington seasonal classification. See V01 observed dates and scientific checks. A single ring labels each event by name on two lines just outside the rim. Its short leader meets the ring at the event's model day. A single ring shows the star, epoch and site in its centre. Rings for one star at several epochs show the star, designation and shared site in the centre, with a year for each ring. The circular layout labels the solstices and equinoxes outside its rim. Both layouts mark the event's model day, as recorded in the event table. The linear seasonal scale sits immediately below the lowest strip. Each quarter label aligns with its solstice or equinox across every row. Rising-event labels sit close above a single strip and setting-event labels close below it, leaving room for the seasonal scale where needed. Both layouts use the same sequence and colours; the circular layout makes the cycle boundary explicit. Labels wrap and shrink to fit; crowded comparisons need a larger device.

Scientific checks

See Also

star.phases

Examples

## Not run: 
if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Plot the seasonality of Aldebaran for 4001 BCE:
  s1 <- star.phases('Aldebaran',-4000, c(35,-8, 200))
  plot(s1) # circular by default
  plot(s1, layout="linear")
  # Plot seasonality of several stars
  s2 <- star.phases('Alnilam',-4000, c(35,-8, 200))
  s3 <- star.phases('Elnath',-4000, c(35,-8, 200))
  plot(s1, s2)
  plot(s1, list(s2,s3))
  plot(s1, show.legend=FALSE, show.grid=FALSE)
}

## End(Not run)

Plot orientation measurements on a compass grid

Description

Inspect the directions of structural axes on a compass and compare them with candidate rise or set bearings.

Usage

plotAzimuth(
  az,
  obj,
  show.obj.labels = TRUE,
  col = NULL,
  lty = 1,
  lwd = 1.5,
  marks = c("spokes", "rim"),
  obj.position = c("inside", "outside"),
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

az

Azimuths in degrees clockwise from north. Can be omitted if obj is given.

obj

A skyscapeR.object from skyObject, or a list of these objects. Each group retains its own epochs and styles for displaying the azimuths of celestial objects. Note that this assumes a single location per group and a flat horizon of zero degrees. For a year range, the target colour fills the interval of rising or setting bearings between the stored declination limits. A zero-width interval is drawn as a line.

show.obj.labels

Logical to control whether to display celestial objects names. Defaults to TRUE.

col

Single color or color palette to use for plotting measurements.

lty

Line type to plot measurements. Defaults to 1.

lwd

Line width for measured bearings. Defaults to 1.5.

marks

Draw measured orientations as equal-length "spokes" (default) or short "rim" ticks.

obj.position

Draw target reference lines "inside" the circle or just "outside" its rim. In both positions labels lie outside the circle. The first line names the target and the second gives rise or set. Range endpoints share a label. Non-crossing targets have no reference bearing.

show.legend

With TRUE, show the count and enabled target labels. FALSE centres the bare compass, including its cardinal scale, measured bearings and target lines.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

Measurements are drawn as spokes or rim ticks. North is at the top and bearings increase clockwise; repeated bearings can overplot. A data frame supplies the True.Azimuth column. For optional targets the function converts zero apparent altitude to geometric altitude using the session atmosphere. It solves for rising and setting bearings on a level horizon and shows the part of each declination interval that reaches it.

Value

Draws measured bearings and optional target directions on the active graphics device. North is at the top and azimuth increases clockwise.

Validation

W01 checked compass bearings and the inner and outer edges of celestial year-range sectors against their spherical reference bearings. See the W01 check in the technical manual.

Scientific checks

See Also

plotBars, orbit, sketchSky, planisphere

Examples

# Plot some azimuth data:
az <- c(120, 100, 93, 97, 88, 115, 112, 67)
plotAzimuth(az)

# To visualize this data against the common solar and lunar targets:
tt <- skyObject('solar extremes', epoch=-2000, loc=c(35,-8), col='red')
plotAzimuth(az, obj=tt)

# To display only celestial objects
plotAzimuth(obj=tt)

Plot orientation intervals in declination

Description

Compare central orientations and their angular uncertainties across observations, optionally against celestial target ranges.

Usage

plotBars(
  val,
  unc,
  names,
  unit = "Declination",
  obj,
  show.obj.label = TRUE,
  xrange,
  yrange,
  sort = FALSE,
  shade = TRUE,
  mark = TRUE,
  col = NULL,
  geometry = if (missing(shade)) "interval" else "bar",
  show.legend = TRUE,
  style = "publication-colour"
)

Arguments

val

Array of declination or azimuth values.

unc

Single value or array of measurement uncertainty

names

Array of names of measurements in val

unit

(Optional). Either 'Declination' or 'Azimuth'. Defaults to 'Declination'.

obj

A skyscapeR.object from skyObject, or a list of these objects. Each group retains its own epochs and styles for displaying the declination values of celestial objects.

show.obj.label

Logical. Label celestial overlays on the declination plot. Defaults to TRUE.

xrange

Array of limits for x-axis.

yrange

Array of limits for y-axis.

sort

Logical to control whether to sort the measurements by their declination value. Defaults to FALSE

shade

Logical to control whether to shade a polygon of measurements. Defaults to TRUE

mark

Logical to control whether to mark the declination value. Defaults to TRUE

col

Measurement colour. NULL uses the current style.

geometry

Use "interval" for sightline intervals with a centre point, or "bar" for filled or outlined rectangles. Explicitly supplying the older shade setting selects rectangles unless geometry is supplied.

show.legend

Display target annotations when show.obj.label is also TRUE.

style

Analytical display style, either "publication-colour" (default) or "publication-mono". Monochrome uses grayscale and preserves line styles.

Details

A row represents one measurement. Its horizontal bar spans the supplied value minus and plus its uncertainty, and an optional mark shows the centre. A scalar uncertainty is reused for all rows. Sorting rearranges measurements, labels and widths together. Celestial overlays use the declination axis. The widths reflect the supplied uncertainties and acquire a probability interpretation only from the measurement model.

For a two-year epoch range, celestial targets are displayed as bands covering their stored minimum and maximum declinations across the full plot height. Single-year targets are displayed as lines.

Value

Draws orientation measurements and their uncertainties on the active graphics device.

Validation

W01 checked the endpoints and row labels of an azimuth interval spanning north. See the W01 check in the technical manual.

Coordinates and interpretation

unit labels the measurement axis; it does not transform azimuths into declinations. Celestial overlay values are declinations. Use them with declination measurements, or convert measurements first using the appropriate site and horizon. Bars show the supplied symmetric angular bounds, not fitted confidence intervals. Use az.pdf, coordtrans and spd when the full measurement distributions are needed.

Scientific checks

See Also

skyObject

Examples

# Plot some declination data:
decs <- c(10, 12, -5, 4)
plotBars(decs, unc=5)

# To visualize this data against the common solar and lunar targets:
tt <- skyObject(c('solar extremes','lunar extremes'), epoch=-2000, lty=c(2,3))
plotBars(decs, unc=5, obj=tt)
# Display a year-range target band:
targets <- skyObject('solar extremes', epoch=c("4001 BC", "2001 BC"), col='red')
plotBars(c(-24,-23,23,24), unc=0.5, obj=targets)

Print global and local significance results

Description

Report how strongly the observed orientation distribution departs from the fitted null model, overall and within local angular intervals.

Usage

## S3 method for class 'skyscapeR.sigTest'
print(x, ...)

Arguments

x

Object of skyscapeR.sigTest format.

...

Additional arguments to be passed to print.

Details

Start with the stored global Monte Carlo result, then examine the direction, limits and local p-value of each reported interval. The summary gives the tail setting, confidence level and number of simulations. It counts unequal observations at constant null density separately and reports when there are no local regions. The method formats a saved result on the console without recomputing it. Read interval coordinates in the units and coordinate system of the fitted test.

Value

Prints the test summary and global and local results to the console.

Validation

The tested public fits printed the stored global probability and local interval endpoints. A wrapped interval has start greater than end. A plot spanning the full turn displays its two visible segments with the same adjusted probability. See S03 validation in the technical manual.

W01 checked the reported wrapped interval endpoints and adjusted probabilities against a known fit. See the W01 check in the technical manual.

Scientific checks

See Also

randomTest, modelTest, plot.skyscapeR.sigTest

Examples

az <- az.pdf(az = c(85, 95, 112), unc = 3, verbose = FALSE)
set.seed(42)
fit <- randomTest(az, nsims = 10, ncores = 1, .res = 2, verbose = FALSE)
print(fit)

Format a p-value as a significance symbol

Description

Annotate a significance-test result with the conventional symbol for its p-value range.

Usage

pval2stars(p.value)

Arguments

p.value

p-value

Details

Use a symbol for compact plot labels while retaining the numeric p-value for interpretation. The cut points are 0.001, 0.01, 0.05 and 0.1, with symbols ***, **, *, + and an open circle in order of increasing p. An equality belongs to the interval ending at that cut point. For legacy strings beginning with a less-than sign and space, the function classifies the printed bound. It does not calculate a test or adjust for multiple comparisons.

Value

A character vector of significance symbols: ***, **, *, + or an open circle, using cut points 0.001, 0.01, 0.05 and 0.1.

Validation

All tested symbol thresholds, their equality cases and the legacy printed bound agreed with their stated probability ranges. See S03 validation in the technical manual.

Scientific checks

See Also

print.skyscapeR.sigTest, plot.skyscapeR.sigTest

Examples

pval2stars(c(0.0005, 0.008, 0.03, 0.08, 0.2))

Test orientations against the null hypothesis of random azimuths

Description

Use a Monte Carlo significance test to assess whether the measured orientations of a group of structures are compatible with uniformly random azimuths, taking their uncertainties and, for a declination comparison, their horizons into account.

Usage

randomTest(
  pdf,
  az,
  hor,
  nsims = 1000,
  conf = 0.95,
  tails = 2,
  normalise = F,
  .res = 0.1,
  ncores = NULL,
  verbose = T
)

Arguments

pdf

A skyscapeR.pdf object created with either az.pdf or coordtrans

az

Original azimuth skyscapeR.pdf; required only when pdf contains declination distributions. Must match its distribution count and order. Do not supply this argument when pdf already contains azimuths.

hor

For azimuth input, optionally supply one shared skyscapeR.horizon to test in declination. For declination input, required: the original shared horizon or an ordered list matching the distributions in pdf.

nsims

Number of simulations, at least two. Default is 1000.

conf

Confidence level as a fraction. For example, 0.95 requests a 95 percent envelope.

tails

1 for upper excesses, 2 for excesses and deficits (default).

normalise

Logical to control whether to normalize SPDs. Default is FALSE

.res

Resolution with which to output probability distribution(s). Default is 0.1 degrees.

ncores

Worker count. By default use half the detected available logical cores, rounded down with a minimum of one. Set ncores=1 for serial execution. The simulation count and memory batch size can further limit workers. Verbose output reports the effective count.

verbose

Logical. Display progress or informational messages. Default TRUE.

Details

Following Silva (2020), the test combines the observed measurement densities into a summed probability density (SPD). For each simulated dataset, the function draws one azimuth per measurement with replacement from the uniform grid from 0 to 360 degrees at the source azimuth spacing. It applies the source density family and measurement uncertainties and constructs a comparable SPD. All six families from az.pdf are supported. Simulated centres are uniformly distributed under the null. At each centre the original observation's taper, survey error or triangular left/right proportions are reused. For a triangle the sampled bearing is its mode. For a declination test, random azimuths are transformed using the site geometry; the resulting null distribution in declination depends on latitude and horizon.

A new transformation takes its atmosphere from skyscapeR.vars. A saved declination PDF supplies its original settings. The fit records these in metadata$atmosphere for declination tests.

Input coordinates. With azimuth input alone, all curves are compared in azimuth. With azimuth input and one shared horizon, the function sums the azimuth densities before transforming the SPD. With a transformed declination PDF, supply its original az and hor in measurement order. Simulated measurements are then transformed individually before summation, using the stored refraction and atmosphere settings. Newer PDFs store the transformation grid spacings; older PDFs use the legacy defaults. The comparison grid uses .res. The two transformation routes can give different results. If normalise=TRUE, each final curve has unit trapezoidal area. Each parallel worker receives its own copy of the required horizons.

Scoring the curves. At each angle, the observed summed density and all simulated summed densities jointly define a pointwise envelope at confidence level conf. An upper-tail test scores excesses; a two-tailed test also scores deficits, using equal tail probabilities for the bounds. For every curve, each departure beyond a bound is divided by the standard deviation of all B+1 curves at that angle. Ties at a bound contribute zero. The global statistic sums the departure magnitudes across the grid. A small global p-value means that few simulated datasets depart from the envelope as much as the observed dataset.

Interpreting local intervals. Local results identify contiguous clusters of departures on the stored linear grid. At least two consecutive points must cross the same bound and span at least 0.5 degrees, inclusive. The same selection and width filter apply to every simulated curve. Each observed cluster's summed departure magnitude is compared with the largest qualifying cluster in each simulation (zero if none), across both signs in a two-tailed test. The inclusive rank gives a maximum-cluster adjusted p-value. Under the complete specified null and exchangeable curves this controls the probability of reporting any cluster as significant, accounting for the interval search. It is not strong error control for arbitrary mixtures of true and false local nulls, and does not establish that every angle inside a cluster is significant or that its endpoints are confidence limits. Azimuth scoring counts each direction once and joins qualifying excursions across north for both observed and simulated curves. A start greater than the end denotes a wrapped interval. Declination retains its two endpoints. The filter does not change the global test. The maximum-cluster principle is adapted from Maris and Oostenveld (2007); cluster interpretation follows Sassenhagen and Draschkow (2019).

If all B+1 curves agree at an angle, its standard deviation is zero and it contributes zero. When only the simulations agree, a differing observation remains in the pooled calculation and can contribute to the score. Such points are also listed in result$data$constant.departures with coordinate x (degrees), observed and simulated densities and direction (above or below), for either tail setting.

Monte Carlo ranks. Global and local Monte Carlo p-values use (b+1)/(B+1), where B is the number of simulations and b counts simulated scores at least as large as the observed score, including ties (North, Curtis and Sham, 2002). The minimum is 1/(B+1); all ties give 1. The observation enters the pooled bounds, mean and standard deviation once. The envelope describes each grid point separately. The rank test assumes that observed and simulated curves are exchangeable under the specified null (Dufour, 2006). Apply the same uncertainty and transformation procedures to both. If you estimate the null model from these observations, account for that fitting when interpreting the test.

Running simulations. With a fixed seed, sampling in the calling session gives the same result for different worker counts. For grids larger than 16 MiB, allow about eight bytes of temporary disk space per simulation per grid point. Temporary files are removed on return or error.

Value

A skyscapeR.sigTest list containing metadata (test settings, global and local p-values) and data (empirical SPD and null confidence envelope). No original PDFs or horizon objects are attached.

Validation

In S03, independent scoring reproduced the azimuth and declination ranks on their respective grids. Build 2.0.9006 counts north once and reports one interval for a qualifying excess across north. Refit earlier azimuth tests to obtain the revised probabilities. See S03 validation in the technical manual.

In S01, at a nominal 5 percent level the global rejection rate was 4.25 to 5.85 percent across the tested uniform-null settings with sufficient Monte Carlo resolution. Build 2.0.9007 uses the source azimuth density spacing and cutoff for simulations and matches the observed SPD spacing on the shared-horizon route. Refit earlier analyses that used different settings. See the S01 calibration in the technical manual.

The 500-simulation Ggantija-phase workflow in W02 reproduced the bundled global probability, local intervals and adjusted probabilities. See the W02 check in the technical manual.

Study design and numerical checks

The simulated null describes independently sampled orientations with the specified site geometry and measurement model. It does not automatically model shared construction episodes, correlated measurement errors, geographical clustering or selection of sites after inspecting their orientations. Such structure needs a justified sampling model or separate sensitivity analysis.

The pointwise envelope is not a simultaneous confidence band. A significant global result rejects the specified random-orientation model; it does not identify a celestial target. Refine the comparison grid and increase nsims to assess borderline results, preserving the seed and inputs. More simulations improve Monte Carlo resolution, not the validity of the archaeological sampling design. Repeated searches over alternative subsets or models are not included in the within-fit local-cluster adjustment.

Scientific checks

References

Silva, F. (2020). A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology. Journal of Archaeological Science, 118, 105138. doi:10.1016/j.jas.2020.105138.

Silva, F. and Lomsdalen, T. (2025). ‘No easy way from the earth to the stars’: a new statistical approach to the orientation of the Maltese temples. Archaeological and Anthropological Sciences, 17, 96. doi:10.1007/s12520-025-02208-4.

Maris, E. and Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. Journal of Neuroscience Methods. doi:10.1016/j.jneumeth.2007.03.024.

Sassenhagen, J. and Draschkow, D. (2019). Cluster-based permutation tests of MEG/EEG data do not establish significance of effect latency or location. Psychophysiology. doi:10.1111/psyp.13335.

Dufour, J.-M. (2006). Monte Carlo tests with nuisance parameters: A general approach to finite-sample inference and nonstandard asymptotics. Journal of Econometrics, 133, 443-477. doi:10.1016/j.jeconom.2005.06.007.

North, B. V., Curtis, D. and Sham, P. C. (2002). A note on the calculation of empirical P values from Monte Carlo procedures. American Journal of Human Genetics, 71, 439-441. doi:10.1086/341527.

See Also

az.pdf, coordtrans, spd, hpdi, modelTest

Examples

## Not run: 
# significance test for azimuth
Az <- az.pdf(az=c(87,93,90,110), unc=3)
st1 <- randomTest(Az, nsims=1000)
plot(st1)

# significance test for declination
hor <- createHor(az=c(0,360), alt=c(0,0), loc=c(35,-8,25)) # flat horizon
Dec <- coordtrans(Az, hor)
st2 <- randomTest(Dec, az=Az, hor=hor, nsims=1000)
plot(st2)

## End(Not run)

Reduce magnetic compass bearings to true bearings

Description

Recover true bearings from magnetic compass observations and, where horizon altitude is known, estimate the indicated declinations.

Usage

reduct.compass(loc, mag.az, date, magdec, alt, name, ID, HWT.ID)

Arguments

loc

Location, either a skyscapeR.horizon or a vector containing the latitude, longitude and elevation of location, in this order.

mag.az

Array of magnetic azimuth measurements.

date

Date of measurements as a string in the format: 'YYYY/MM/DD'. Only necessary if magdec is not given. When omitted, the output Date column contains missing values (NA).

magdec

Magnetic declination, if known.

alt

Altitude, necessary for automatic declination calculation. If missing and loc is a skyscapeR.horizon object then the altitude will be automatically read from the horizon profile.

name

Names or labels to identify each measurement.

ID

IDs or codes to identify each measurement.

HWT.ID

HeyWhatsThat IDs relating to a previously generated horizon profile for measurement.

Details

Magnetic north differs from true north at the time and place of survey. Add the supplied magnetic declination to each magnetic bearing, or calculate it from the survey coordinates and date with mag.dec. Corrected bearings are rounded using the input bearing representation. With an explicit altitude or a measured horizon, the corrected bearing also enters the conversion to declination.

Supply either a measurement date or a known magnetic declination. If both are given, the supplied magnetic declination is used and the date is retained in the output. Explicit altitude values take precedence over a horizon profile. Otherwise, each measurement's corrected true azimuth is used to retrieve its horizon altitude; the same altitude is reported and used to calculate celestial declination. Supply one site and date for the whole survey or one location row and/or date per bearing, in measurement order. A supplied correction can likewise be shared or paired with each bearing.

Value

A data frame with one row per measurement, including location, magnetic azimuth, date, magnetic declination and true azimuth. Altitude and celestial declination are included when altitudes are supplied or a horizon is available. Optional identification columns are retained.

Validation

W02 checked north-crossing magnetic readings against the supplied corrections before passing true bearings into a skyline analysis. See the W02 check in the technical manual.

Scientific validation

F01 examines magnetic and solar reductions against independent references. F01 scientific validation.

Scientific checks

See Also

mag.dec, az2dec, hor2alt

Examples

loc <- c(35,-7, 100)
mag.az <- c(89.5, 105, 109.5)
data <- reduct.compass(loc, mag.az, "2016/04/02")

# Declination will be automatically calculated if the altitude is also given:
data <- reduct.compass(loc, mag.az, "2016/04/02", alt=c(1,2,0))

# Alternatively, the altitude can be automatically retrieved from a horizon profile:
hor <- malta_horizons[[1]]
data <- reduct.compass(hor, mag.az, "2016/04/02")

# Known magnetic declination: no measurement date is required.
reduct.compass(c(35,-7,100), c(89.5,105,109.5), magdec=-2, alt=c(1,2,0))

# A varying horizon supplies an altitude for each corrected azimuth.
hor <- createHor(c(0,90,180,270,360), c(0,2,6,1,0), loc=c(35,-7,100))
reduct.compass(hor, c(89.5,105,109.5), magdec=-2)

Reduce theodolite readings using a solar sight

Description

Orient a theodolite survey to true north using a timed solar sight, then recover the true bearing of a structural axis.

Usage

reduct.theodolite(
  loc,
  az,
  date,
  time,
  tz,
  az.sun = 0,
  limb,
  alt,
  name,
  ID,
  HWT.ID
)

Arguments

loc

Location, either a skyscapeR.horizon or a vector containing the latitude, longitude and elevation of location, in this order.

az

Array of azimuths. Use ten to convert to decimal degrees if necessary.

date

Date of measurements as a string in the format: 'YYYY/MM/DD'

time

Time of sun-sight measurement in the format: 'HH:MM:SS'

tz

Timezone of input either as a known acronym (e.g. "GMT", "CET") or a string with continent followed by country capital (e.g. "Europe/London").

az.sun

Measured azimuth of the sun. Defaults to zero.

limb

Measured limb of the sun. Options are left, right. If missing the center of the sun will be used for calculations.

alt

Altitude, necessary for automatic declination calculation. If missing and loc is a skyscapeR.horizon object then the altitude will be automatically read from the horizon profile.

name

Names or labels to identify each measurement.

ID

IDs or codes to identify each measurement.

HWT.ID

HeyWhatsThat IDs relating to a previously generated horizon profile for measurement.

Details

The observed difference between the instrument readings to the structure and to the Sun is added to the calculated solar azimuth at the observation time. The routine handles a circle-boundary difference, accounts for the selected solar limb through sunAz and rounds the reference bearing according to the input readings. True bearings lie in [0, 360) degrees. A three-coordinate vector supplies one shared site; for multiple sites, supply a matrix with one latitude, longitude and elevation row per reading. An explicit altitude or a supplied horizon allows the corrected bearing to be converted to declination. Correct time, civil timezone, limb and site are all essential to the reduction.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A data frame with one row per observation. True.Azimuth is the corrected azimuth in degrees. The table also records the observed azimuth, solar azimuth, time and site coordinates. Where available it includes Altitude and Declination in degrees and the supplied identifiers.

Validation

W02 recovered both independent circle-difference control bearings and retained each site row in a multi-site solar reduction. See the W02 check in the technical manual.

Scientific validation

F01 examines magnetic and solar reductions against independent references. F01 scientific validation.

Scientific checks

References

Ruggles, C.L.N. (1999). Astronomy in Prehistoric Britain and Ireland. Yale University Press.

See Also

sunAz, ten

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  lat <- ten(35,50,37.8)
  lon <- ten(14,34,6.4)
  elev <- 100
  az <- c( ten(298,24,10), ten(302,20,40))
  az.sun <- ten(327,29,50)
  date <- "2016/02/20"
  time <- "11:07:17"
  
  data <- reduct.theodolite(c(lat,lon,elev), az, date , time, tz= "Europe/Malta", az.sun)
  
  # Declination will be automatically calculated if the altitude is also given:
  data <- reduct.theodolite(c(lat,lon,elev), az, date, time,
  tz="Europe/Malta", az.sun=az.sun, alt=c(2,5))
  
  # Alternatively, the altitude can be automatically retrieved from a horizon profile:
  hor <- malta_horizons[[1]]
  data <- reduct.theodolite(hor, az, date, time, tz= "Europe/Malta", az.sun)
}

Reconnect saved horizons to moved panorama PNGs

Description

Update the external PNG paths in one horizon or a list after moving a project.

Usage

relinkHor(hor, path, recursive = FALSE)

Arguments

hor

A skyscapeR.horizon object or a list of horizon objects.

path

A directory containing the moved PNGs, or a character vector of PNG filenames in any order.

recursive

Search subdirectories when path names a directory. Defaults to FALSE.

Details

A saved horizon records the checksum of its displayed PNG. Copy that PNG with the RDS, including the levelled copy for a calibrated photograph. Matching checks file contents, so a renamed file can be recovered and different panoramas with the same filename can be distinguished. For identical copies, the original basename is preferred, then the first matching candidate. A skyline-only horizon passes through unchanged. If any required image cannot be verified, the function stops before returning a result. Assign the returned object and use saveRDS() to keep the updated paths. The original PeakFinder archive used for native-layout export is separate.

Value

The horizon or list, retaining its names, order and metadata with updated absolute PNG paths.

Examples

## Not run: 
sites <- readRDS("sites.rds")
sites <- relinkHor(sites, "panoramas", recursive = TRUE)
saveRDS(sites, "sites.rds")
# A single renamed image
hh <- relinkHor(hh, "photos/west-ridge.png")

## End(Not run)

Find rising and setting times and bearings at a site

Description

Find when and where a star or Solar System body first rises above or sets below the horizon at an observing site.

Usage

riseset(
  loc,
  date,
  jd,
  obj = "sun",
  alt = 0,
  timezone,
  calendar,
  dec,
  refraction,
  atm,
  temp,
  verbose = TRUE
)

Arguments

loc

Location, either a skyscapeR.horizon or a vector containing the latitude, longitude and elevation of location, in this order.

date

Either a string containing the date in the format "YYYY/MM/DD" (see timestring), or a numeric containing the julian date (see time2jd). Can also be a single year ("YYYY") or a month ("YYYY/MM") to calculate risings and settings for every day in the year or month, respectively. Not necessary if jd is given.

jd

A numeric containing the julian date (see time2jd) for which to calculate rising and settings. Only needed if date is not given.

obj

Solar System body, Western star name or fixed-star catalogue identifier (including M 45). Defaults to 'sun'.

alt

The altitude of the horizon to consider. Defaults to zero degrees.

timezone

Timezone for civil timestamps. Use UTC or a fixed offset for dates before 1900. See time2jd for named zones and offsets.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

dec

Output declination: geo for the geocentric, or topo for the topocentric frame of reference. If not given the value set by skyscapeR.vars will be used instead.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

verbose

Logical. Display progress or informational messages. Default TRUE.

Details

The event is a crossing of the local horizon by the body's centre. A raised ridge can delay the first visible rise and an uneven horizon can give several appearances or disappearances. Choose the horizon model, atmosphere, calendar and time convention to match the observation.

Events refer to the centre of the disc. For a Solar System body with a coordinate vector, alt is one constant horizon altitude and the Swiss Ephemeris rise/set solver is used. For stars, the daily track is evaluated against the supplied constant altitude or site skyline. With a horizon object, its profile is linearly interpolated in azimuth and compared with the body's topocentric altitude; do not supply alt as well. Refraction TRUE uses apparent altitude; FALSE uses geometric altitude. The constant-altitude solver likewise disables refraction only when FALSE. For a profile, search the 48 hours after each requested local midnight and return the first upward and first downward crossing separately. They need not enclose one continuous visibility interval or occur on the requested day. Missing crossings return NA fields. A one-minute base grid, quarter-step samples, azimuth turning points and recursively subdivided rapid azimuth motion bracket visits to the profile's corners. Each smooth segment is also searched for an interior altitude extremum, so short emergence/reoccultation pairs need not straddle time samples. A pure tangency without a sign change is not a rise or set. Horizon altitudes at 0 and 360 degrees must agree. Root tolerance is 0.01 seconds; interior optimization uses relative seconds to avoid precision loss from large Julian dates. These settings are not a physical accuracy guarantee: finite precision, unresolved terrain and near-zenith azimuth singularities limit numerical completeness. The dec argument controls returned declination, not the topocentric event search.

The Swiss Ephemeris manual documents the fixed-altitude rise/set calculation.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A list containing object, rise and set; rise/set are data frames with date, time, azimuth and declination columns. Missing events have NA fields.

Validation

A02 tested sensitivity to ephemeris conventions using a separate solver on airless lunar-centre trajectories. Across 177 prehistoric skyline crossings, default azimuths differed from JPL Horizons by a median of 0.059 degrees and a maximum of 0.322 degrees. Matching delta T reduced the maximum to 0.027 degrees. See the A02 study in the skyscapeR technical manual.

A04 recovered the expected crossing counts and order on synthetic ridges, notches and grazing tracks; solar and lunar centre crossings at the Malta test site agreed with JPL Horizons within 0.85 seconds and 0.0041 degrees. See the A04 check in the technical manual.

H07 verified that a partial panorama is rejected before searching for solar or stellar crossings on an unobserved skyline. See the H07 check in the technical manual.

Crossing is not first visibility

The result supplies geometry and time. It applies neither atmospheric extinction nor a twilight detection threshold and does not test whether the star can be seen. A centre exactly at the skyline can remain obscured in a plot or too faint to detect. Use star.phases to select a candidate season, then inspect moments after the crossing with sketchSky and skyStep. The extra time needed for clearance depends on track slope, latitude and terrain; a universal minute offset is inappropriate.

A numerical root tolerance describes the solver, not observational timing accuracy. Uncertain terrain height, refraction and ancient Earth-rotation models can dominate it. Saved output contains formatted civil times rather than a complete record of the input atmosphere and horizon. Preserve the original call and convert date/time back with matching calendar and timezone.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

References

Astrodienst. Swiss Ephemeris programmer's manual. https://www.astro.com/swisseph/swephprg.htm.

See Also

swe_calc_ut, swe_azalt, body.position, star.phases

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Rising and setting of the sun on june solstice 2018, from the location of London
  riseset(obj='sun', date='2018/06/21', loc=c(51.5, 0.11, 100))
  
  ## Not run: 
  # Horizon searches and multi-date calculations can exceed five seconds.
  # Rising and setting of the moon on june solstice 2018, using a horizon profile
  hor <- malta_horizons[[1]]
  riseset(obj='moon', date='2018/06/21', loc=hor)
  
  # Rising and setting of the sun throughout February 1999, from the location of London
  riseset(obj='sun', date='1999/02', loc=c(51.5, 0.11, 100))
  
  # Rising and setting of the sun throughout 3001 BC, from the location of London
  riseset(obj='sun', date=-3000, loc=c(51.5, 0.11, 100))
  
## End(Not run)
}

Estimate southern major lunar standstill declination

Description

Estimate the southern declination limit of a major lunar standstill for comparison with a proposed alignment.

Usage

sMjLX(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.952,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.952 degrees for the Moon.

altitude

Altitude of the Moon. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

A major standstill defines a limiting lunar declination at the epoch of interest. The model uses the obliquity plus a fixed 5.145 + 0.145 degrees, then applies the negative sign for the southern limit. With a location it subtracts the parallax correction for latitude and altitude. The default lunar parallax is 0.952 degrees. This approximation defines a target limit; it does not search a time series for an actual lunar event.

Sprajc (2016) describes the limits set by obliquity and the mean lunar inclination. This package also includes the fixed 0.145-degree term above.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Scientific validation

A06 examines geocentric lunar and planetary limits against independent extrema. A06 scientific validation.

Scientific checks

References

Ć prajc, I. (2016). Lunar alignments in Mesoamerican architecture. Anthropological Notebooks 22(3), 61-85.

See Also

nmnLX, smnLX, nMjLX, parallax.corr

Examples

# Southern major Lunar Extreme geocentric declination for year 2501 BC:
sMjLX(-2500)

# Topocentric declination for same year and latitude of 50 degrees N:
sMjLX(-2500, loc=50)

Prepare a reusable sky sketch for a horizon plot

Description

Calculate the sky above one observing site at one instant, then reuse it as the background of a horizon plot. Natural style illustrates daylight, twilight, moonlight and atmospheric extinction. Publication styles show the selected objects without brightness-dependent visibility filtering.

Usage

sketchSky(
  hor,
  jd = NULL,
  time = NULL,
  timezone,
  calendar,
  display = list(),
  style = c("natural", "publication-colour", "publication-mono"),
  max.mag = 6,
  k = skyscapeR.vars()$k,
  band.extinction = TRUE
)

Arguments

hor

A skyscapeR.horizon with finite latitude, longitude and observer elevation in metres in metadata$georef. The numerical profile supplies the foreground when plotted. A panorama image is optional.

jd

One finite UT Julian day. Supply exactly one of jd and time.

time

A civil timestamp accepted by time2jd, or a POSIXt instant.

timezone, calendar

Civil timezone and calendar for character time, as in time2jd. Defaults are the session settings. A POSIXt value already identifies an instant; these arguments do not reinterpret it. Use UTC or a fixed offset for ancient civil dates.

display

A named list of logical switches: sun, moon, planets, stars, constellation.lines, milky.way, galactic.equator, ecliptic, equator, poles and zenith. Sun, Moon and stars default to TRUE; other switches default to FALSE, except that the Milky Way follows stars unless explicitly set. The additional constellations entry accepts names or an imported data frame, rather than a logical value. See Constellations below. A named logical vector is sufficient when supplying only switches.

style

One of "natural", "publication-colour" or "publication-mono". Publication styles have a white background and dark guides. Colour uses muted stellar and planetary colours and a warm solar disc; mono uses black and white. Neither publication style predicts visibility.

max.mag

Finite catalogue magnitude cutoff, default 6. Applied before extinction to star symbols and the integrated magnitudes of supported clusters. It does not limit constellation endpoints, the Sun, Moon or planets. Raising the cutoff includes additional stars only where the catalogue supplies them.

k

Non-negative visual extinction coefficient in magnitudes per airmass for natural style. Defaults to skyscapeR.vars()$k, initially 0.2. This clear-sky baseline is an assumption, not an estimate of the site's weather. Zero removes extinction and the modelled lunar scattering. Publication styles do not apply extinction to symbols.

band.extinction

Logical. Defaults to TRUE. Set to FALSE to disable Milky Way extinction in publication styles. Natural style already applies it.

Details

The function computes an object without drawing. Use plot(hor, sky = sky, xrange = ..., yrange = ...) to choose the sector. Replotting the object changes framing without recalculating the instant. Use skyStep to recalculate at another time. Astronomical calculations require Swiss Ephemeris files covering the epoch; see skyscapeR-package for installation.

Value

An object of classes skyscapeR.sketch and skyscapeR.sky. It stores jd, loc, style, display, settings (calendar, magnitude cutoff and extinction), and atmosphere. stars and coords contain azimuth, altitude and symbol size; star.opacity retains an earlier symbol-opacity diagnostic; natural sketches draw from light.budget. bodies, diameters, planet.size and lunar describe selected Solar System bodies. clusters holds supported cluster footprints and opacity when applicable. The natural view uses the integrated Pleiades magnitude as the light budget within its projected footprint. When the plotted stars exceed that budget, their fluxes are scaled together to preserve their relative brightness. Any residual light uses a broad, tapered profile; guides, light, background and twilight fields support drawing. Components can be empty when a layer is disabled. No image file is written.

Reading a natural sketch

The sky is calculated for the specified instant. Stars, clusters, planets and the Moon contribute light on a common visual (V-band) magnitude scale. Diffuse Milky Way light and atmospheric background are measured per unit sky area. Their light is added before brightness is compressed for display. To inspect the values underlying a view, use skyRadiance.

Stars remain unresolved as the field is enlarged. Mercury, Venus, Mars, Jupiter, Saturn and the Moon use apparent disc sizes and illuminated fractions from Swiss Ephemeris. A close view can therefore show the phase of Venus. Star colours follow catalogue spectral classes; the diffuse band has a neutral tint. Colour and projection influence the screen appearance. Publication styles use magnitude-scaled star and planet symbols on white. In publication colour, stellar hue identifies the leading catalogue spectral class O through M; other or missing classes use neutral grey.

Azimuth increases clockwise from true north. Refraction, pressure and temperature come from skyscapeR.vars when the sky is calculated. The Sun and Moon switches control their contributions to sky illumination as well as their discs. Use display = list(moon = FALSE) for a moonless comparison. The terrain masks the drawn sky; a local ridge hiding the Moon can still leave scattered moonlight in the sky.

Constellations

Use display = list(constellations = "Orion") to select and enable line figures. "modern" selects all 88 Western figures, "chinese" the full Chinese set, and "chinese_mansions" the 28 lunar-mansion figures. Names and abbreviations are case-sensitive; for example c("Ori", "Tau"). Alternatively, supply a data frame from importConstellations. See constellations for sources and identifiers.

Supplying a selection enables lines unless constellation.lines = FALSE is also supplied. Setting constellation.lines = TRUE without a selection uses modern figures. Endpoint coordinates are calculated independently of the star-symbol magnitude cut. Lines therefore remain when their stars are faint, extincted, or switched off. A single-star figure is drawn as a ring. Normal plot clipping and the horizon foreground still apply. These are reference figures; their visibility is not an observing prediction.

Twilight and extinction

At twilight the sky brightens differently towards and away from the Sun. Zenith brightness uses the Paranal V-band observations of Patat et al. (2006) at solar depressions of 5 to 15 degrees. Sacramento Peak measurements supply earlier twilight levels and the directional variation (Koomen et al. 1952). These clear-sky estimates depend on site conditions. Moonlight uses the scattering model of Krisciunas and Schaefer (1991), with its dependence on lunar phase, altitude and angular separation.

Direct light fades towards the horizon as its path through the atmosphere lengthens. The coefficient k sets the loss per airmass. The model uses Rozenberg's airmass approximation (Krisciunas and Schaefer 1991); uncertainty is greatest close to the skyline. The twilight colours are illustrative (Lee 1994, 2015). Above the geometric horizon, the display blends gradually into a clear daylight blue, reaching its full daytime palette and exposure at a solar altitude of 15 degrees.

Milky Way and clusters

The Milky Way uses a 0.1-degree Galactic grid classified from the reviewed 1024-pixel diffuse-light image in Deep Star Maps 2020. A smoothed image-tone threshold defines its outer envelope. Dark patches are more than 8 percent below an 8-degree local reference and cover at least 7 square degrees. Two brighter classes use fixed image-tone cutoffs and a 10-square-degree minimum area. These settings, including the 7-square-degree cutoff, were chosen by visual comparison and remain illustrative, not visibility thresholds. Dark patches remain within the outer envelope for alignment purposes. See the technical manual and bundled milky-way-source.txt for reproduction. Natural sketches anchor the mean surface brightness of a four-degree field in Carina to 20.7 V magnitudes per square arcsecond (van der Kruit 2024). Brightness elsewhere is approximate. Atmospheric extinction can make the band difficult to follow down to its calculated horizon crossing. The Galactic equator is an optional geometric guide.

A supported cluster contributes its catalogue light across its angular extent. Light already assigned to plotted stars within that footprint is subtracted before the remaining glow is drawn. This accounts for projected overlap; it does not establish membership. Integrated cluster magnitude alone is insufficient to predict first detection (Crumey 2014).

Using a sketch with a stellar phase date

Use riseset to locate the terrain crossing and skyStep to follow the star through twilight. For first morning or last evening, inspect adjacent dates as well. A rendered symbol alone cannot establish naked-eye detection.

Validation

W02 verified the reconstructed Gacrux bearing and altitude at the same instant and viewpoint using direct equatorial coordinates and spherical geometry. See the W02 check in the technical manual.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Observational validation

Across 56 recorded dates, heliacal rising fell within seven days of 22 of 23 first morning sightings. The median prediction was two days early. Acronycal setting fell within seven days of 21 of 33 last evening sightings. The median prediction was five days late. A week is a practical search window. Larger discrepancies occur, especially at dusk. These results apply to the two tested events. V01 observed dates and scientific checks.

Scientific checks

Additional stellar visibility checks

References

Patat, F., Ugolnikov, O. S. and Postylyakov, O. V. (2006). UBVRI twilight sky brightness at ESO-Paranal. Astronomy and Astrophysics 455, 385-393. doi:10.1051/0004-6361:20064992.

Koomen, M. J. et al. (1952). Measurements of the brightness of the twilight sky. JOSA 42, 353-356. doi:10.1364/JOSA.42.000353.

van der Kruit, P. C. (2024). Pannekoek's Galaxy. Journal of Astronomical History and Heritage 27, 135-199. doi:10.3724/SP.J.1440-2807.2024.01.10.

Krisciunas, K. and Schaefer, B. E. (1991). A model of the brightness of moonlight. PASP 103, 1033-1039. doi:10.1086/132921.

Schaefer, B. E. (1986). Atmospheric Extinction Effects on Stellar Alignments. Journal for the History of Astronomy 17, S32-S42. doi:10.1177/002182868601701003.

Schaefer, B. E. (1993). Astronomy and the Limits of Vision. Vistas in Astronomy 36, 311-361. doi:10.1016/0083-6656(93)90113-X.

Lee, R. L., Jr. (1994). Twilight and daytime colors of the clear sky. Applied Optics 33, 4629-4638. doi:10.1364/AO.33.004629.

Lee, R. L., Jr. (2015). Measuring and modeling twilight's Belt of Venus. Applied Optics 54, B194-B203. doi:10.1364/AO.54.00B194.

Crumey, A. (2014). Human contrast threshold and astronomical visibility. MNRAS 442, 2600-2619. doi:10.1093/mnras/stu992.

NASA/Goddard Space Flight Center Scientific Visualization Studio (2020). Deep Star Maps 2020. https://svs.gsfc.nasa.gov/4851/.

Verga, M. and contributors. OpenNGC. Source of cluster angular sizes. https://github.com/mattiaverga/OpenNGC. See installed COPYRIGHTS for data attribution and licences.

Astrodienst. Swiss Ephemeris programmer's manual, fixed stars, horizontal coordinates and planetary phenomena. https://www.astro.com/swisseph/swephprg.htm.

See Also

star.phases, riseset, findTargets, skyStep, stellariumSky, plot.skyscapeR.horizon, importConstellations, skyscapeR.vars

Examples

## Not run: 
hor <- malta_horizons[[1]]
sector <- c(0, 180)
sky <- sketchSky(hor, time = "2026/12/21 20:00", timezone = "UTC")
plot(hor, sky = sky, xrange = sector)
sky <- skyStep(hor, sky, minutes = 10, xrange = sector)

# Compare publication styles at exactly the same instant.
colour <- sketchSky(hor, jd = sky$jd, style = "publication-colour",
                    display = list(constellations = "modern"))
mono <- sketchSky(hor, jd = sky$jd, style = "publication-mono",
                  display = list(constellations = "modern"))
plot(hor, sky = colour, xrange = sector)
plot(hor, sky = mono, xrange = sector)

## End(Not run)

Prepare celestial targets for orientation plots

Description

Define celestial targets and their declinations so the same hypotheses can be overlaid on several orientation plots.

Usage

skyObject(names, year, loc = FALSE, col = "#A9542E", lty = 1, lwd = 1, epoch)

sky.objects(names, year, loc = FALSE, col = "#A9542E", lty = 1, lwd = 1, epoch)

Arguments

names

Target names, star names or custom declinations in degrees. Use "solar extremes" for the solstices or "lunar extremes" for the four lunar extremes.

year

An astronomical year or a pair of year endpoints. Historical labels such as "3700 BC" are accepted by astroYear.

loc

This can be either a vector with the latitude and longitude of the location, or a skyscapeR.horizon object.

col

The color for plotting, and differentiating these objects. Defaults to ochre for all objects.

lty

Line type (see par) used for differentiation. Used for single-year tracks and year-range boundaries.

lwd

Line width (see par) used for differentiation. Used for single-year tracks and year-range boundaries.

epoch

Earlier argument name for year, retained for existing scripts.

Details

An overlay identifies which targets to compare before inspecting a distribution. Names may denote stars, solar or lunar limits, or fixed custom declinations. Group names expand into the individual limits. At one epoch, the function evaluates each target; for two endpoints it takes the minimum and maximum over every integer year, including both endpoints. Stars use January barycentric declinations. Solar and lunar limits use the supplied site correction for each year. Styles and epochs travel with the object. Changes between annual samples remain unresolved. A single object can contain several related targets. Pass a list of objects to plot(hor), plotBars or plotAzimuth to combine groups with independent epochs, colours, line styles and labels. Groups are drawn in list order. Horizon plots use the plotted horizon's location for every track. Compass plots use each group's stored location and a level horizon, shading the azimuth interval between the two declination boundaries for a year-range group. Declination plots need no location. No common epoch range is imposed and no astronomical positions are recomputed merely by combining objects. The output class remains skyscapeR.object, so previously saved objects remain usable. sky.objects is a silent compatibility alias for skyObject.

Value

A skyscapeR.object list. Columns of decs represent targets, in degrees. A single epoch produces one row. For a two-year range the rows are labelled min and max. The other fields record target count, epoch, location and plotting styles.

Validation

A08 checked annual stellar, solar and lunar range endpoints, local corrections, identifier aliases and retention of target labels and line styles. See the A08 check in the technical manual.

A reference track is not a dated orbit

Each target represents a declination or declination range. A plotted track holds that declination fixed while hour angle varies. It does not follow the changing declination of a moving Solar System body through a particular day. In particular, skyObject("Equinox", year) is an equinox reference; the Sun at sunrise or sunset on the equinox date need not lie at the same declination as at the equinox instant. A small offset from a solar disc in sketchSky can therefore be expected.

To compare with a particular instant, obtain its declination with body.position using the intended coordinate frame, and pass that numeric value to skyObject. Even that fixed-declination track is an approximation to a moving body's full daily orbit. Refraction and the plotted site's coordinates are applied when drawing the horizon track.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

See Also

plot.skyscapeR.horizon, plotBars, plotAzimuth, jS, dS, eq, nmnLX, smnLX, nMjLX, sMjLX, obliquity, parallax.corr

Examples

# Create an object with solar targets for epoch range 4001-2001 BC:
tt <- skyObject('solar extremes', c("4001 BC", "2001 BC"))

if (requireNamespace("swephRdata", quietly=TRUE)) {
# Create an object with a few stars for same epoch:
tt <- skyObject(c('Sirius', 'Betelgeuse', 'Antares'), c("4001 BC", "2001 BC"),
col=c('white', 'red', 'orange'))
}

# Create an object with solstices and a custom declination value:
tt <- skyObject(c('December Solstice','June Solstice', -13), c("4001 BC", "2001 BC"))
# Mix a single-epoch group with a range, preserving each group's styles:
groups <- list(skyObject(12, "2001 BC", col="blue"),
               skyObject("solar extremes", c("4001 BC", "2001 BC"), col="orange"))
plotBars(c(-24,12,24), unc=1, obj=groups)

Inspect the linear light field of a natural sky

Description

Samples a natural sketch before display compression or masking by local terrain. One integrated flux unit is a magnitude-zero V-band source.

Usage

skyRadiance(sky, xrange = c(0, 360), yrange = c(0, 90), size = c(720, 180))

Arguments

sky

A natural sketch from sketchSky.

xrange

Increasing true azimuth limits in degrees. A sector may cross north, for example c(340,380).

yrange

Increasing altitude limits within -90 to 90 degrees.

size

Positive integer column and row counts, up to 1600 by 1000.

Details

Direct light includes stars, residual cluster light, planetary discs and the illuminated lunar disc. The Milky Way uses the accepted tracing and a provisional Carina surface-brightness calibration. Stars remain unresolved as the view is enlarged. See sketchSky for sources, assumptions and interpretation.

Value

A list containing azimuth and altitude pixel centres, total radiance, direct light (stars, residual cluster light, planets and lunar disc), and Milky Way radiance. Matrices are in magnitude-zero flux units per square degree, ordered from high to low altitude and increasing azimuth. Multiply by area (square degrees per pixel by row) and sum to obtain flux. The difference between total and the two source matrices is the atmospheric background. The Sun contributes to the background; its disc is a plot overlay.

Observational validation

Across 56 recorded dates, heliacal rising fell within seven days of 22 of 23 first morning sightings. The median prediction was two days early. Acronycal setting fell within seven days of 21 of 33 last evening sightings. The median prediction was five days late. A week is a practical search window. Larger discrepancies occur, especially at dusk. These results apply to the two tested events. V01 observed dates and scientific checks.

Scientific checks

Additional stellar visibility checks


Inspect or set session defaults for skyscapeR

Description

Set the observing and time conventions that should be shared across an analysis, or retrieve them for a reproducible methods record.

Usage

skyscapeR.vars(timezone, calendar, refraction, atm, temp, dec, k)

Arguments

timezone

Timezone name (for example "Europe/London") or fixed offset in hours east of UTC, or a string such as "UTC+02:00". Initially "Europe/London". Use UTC or a fixed offset for dates before 1900. See time2jd for details.

calendar

Calendar for civil dates. Use "G" for Gregorian or "J" for Julian.

refraction

Whether atmospheric refraction is to be taken into account. Default is TRUE.

atm

Air pressure in mbar for the refraction calculation. Default is 1013.25 mbar.

temp

Air temperature in degrees Celsius for the refraction calculation. Default is 15 degrees Celsius.

dec

Output declination: geo for the geocentric, or topo for the topocentric frame of reference. Defaults to topocentric.

k

Visual extinction in magnitudes per airmass, shared by natural sky sketches and stellar phase calculations. The initial value of 0.2 is a clear-sky baseline, consistent with the approximate V-band coefficient for Kitt Peak in the UC Davis Physics 157 Observing Guide. Extinction varies with site and atmospheric conditions (Schaefer 1986, 1993). Use zero to disable extinction.

Details

The same observation can have different labels or apparent coordinates under different calendar, timezone, reference-frame or atmospheric choices. With no arguments the function returns a named snapshot. Supplied arguments update the package environment for subsequent calls in the current R session. Functions with their own explicit arguments or fixed UT sampling conventions may override these defaults. Record the settings with the survey data.

Value

A named list of the current session settings, including the current year. Supplying an argument updates that setting for subsequent package calls in this R session.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

References

Schaefer, B. E. (1986). Atmospheric Extinction Effects on Stellar Alignments. Journal for the History of Astronomy 17, S32-S42. doi:10.1177/002182868601701003.

Schaefer, B. E. (1993). Astronomy and the Limits of Vision. Vistas in Astronomy 36, 311-361. doi:10.1016/0083-6656(93)90113-X.

University of California, Davis. Physics 157 Observing Guide, Spring 2022, discussion of extinction coefficients.

See Also

skyscapeR-package, time2jd, body.position

Examples

settings <- skyscapeR.vars()
settings$timezone

Estimate southern minor lunar standstill declination

Description

Estimate the southern declination limit of a minor lunar standstill for comparison with a proposed alignment.

Usage

smnLX(
  year = skyscapeR.env$cur.year,
  loc = FALSE,
  parallax = 0.952,
  altitude = 0,
  verbose = TRUE
)

Arguments

year

Astronomical year. The default is the current year in the package settings. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Latitude in degrees north or a skyscapeR.horizon object. Omit this argument or use FALSE for geocentric declination.

parallax

Mean horizontal parallax in degrees. The default is 0.952 degrees for the Moon.

altitude

Altitude of the Moon. Defaults to 0 degrees.

verbose

Logical to control output of warnings and messages. Defaults to TRUE.

Details

A minor standstill defines a limiting lunar declination at the epoch of interest. The model uses the obliquity minus a fixed 5.145 + 0.145 degrees, then applies the negative sign for the southern limit. With a location it subtracts the parallax correction for latitude and altitude. The default lunar parallax is 0.952 degrees. This approximation defines a target limit; it does not search a time series for an actual lunar event.

Sprajc (2016) describes the limits set by obliquity and the mean lunar inclination. This package also includes the fixed 0.145-degree term above.

Value

Numeric declination in degrees. With loc = FALSE the result is geocentric. Supplying a location applies the parallax correction for the chosen altitude.

Scientific validation

A06 examines geocentric lunar and planetary limits against independent extrema. A06 scientific validation.

Scientific checks

References

Ć prajc, I. (2016). Lunar alignments in Mesoamerican architecture. Anthropological Notebooks 22(3), 61-85.

See Also

nmnLX, nMjLX, sMjLX, parallax.corr

Examples

# Southern minor Lunar Extreme geocentric declination for year 2501 BC:
smnLX(-2500)

# Topocentric declination for same year and latitude of 50 degrees N:
smnLX(-2500, loc=50)

Find dates when the Sun reaches a specified declination

Description

Estimate the dates on which the Sun could attain a declination indicated by a structure in a selected year.

Usage

solar.date(dec, year, calendar, verbose = TRUE)

Arguments

dec

One or more declinations in degrees.

year

Year for which to do calculations. Historical labels such as "3700 BC" are accepted by astroYear.

calendar

Calendar for sampling and output. G for Gregorian or J for Julian. Defaults to the package calendar, initially Gregorian.

verbose

Logical. Display progress or informational messages. Default TRUE.

Details

The Sun can pass the same declination on either side of a solstice. The search covers the selected civil year from midnight UT, including its first instant and excluding the start of the next year. Daily geocentric apparent solar declinations bracket the annual turning points. The function refines each extremum against the ephemeris and solves separately on either side, then reports the civil day of each crossing. A tangency gives one date. Two crossings can share a calendar day. The calculation uses no terrain or solar limb model.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A character matrix with one column per reachable input, in input order. The rows are Dec, Date1 and Date2, with Date3 added if three passages fall in one civil year. Dates are chronological day/month labels. Unused date cells are missing. The function stops if all requested declinations are unreachable.

Validation

The JPL comparison in A05 matched all tested civil-day passages, including paired dates near a solstice. See the A05 check in the technical manual.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

See Also

spatial.equinox, zenith, antizenith, findTargets, EFM, planet.extremes

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  solar.date(-23, 2018)
  solar.date(-12, 1200, calendar='G')
  solar.date(-12, 1200, calendar='J')
  solar.date(14, -2000)
}

Estimate the spatial equinox from a site horizon

Description

Find the directions halfway between the two solstitial sunrise bearings and between the two solstitial sunset bearings on a particular horizon.

Usage

spatial.equinox(
  hor,
  parallax = 0.00224,
  year = skyscapeR.env$cur.year,
  refraction = skyscapeR.env$refraction,
  atm = skyscapeR.env$atm,
  temp = skyscapeR.env$temp
)

Arguments

hor

A skyscapeR.horizon with finite, increasing azimuths covering 0 to 360 degrees and matching endpoint altitudes.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

year

One astronomical year, defaulting to the package's current-year setting. Historical labels such as "3250 BC" are accepted.

refraction

Whether to apply atmospheric refraction. Defaults to the package setting, normally TRUE.

atm

Atmospheric pressure in hPa. Defaults to the package setting. Zero requests an estimate from site elevation.

temp

Air temperature in degrees Celsius. Defaults to the package setting.

Details

A spatial midpoint is defined by the local terrain and need not coincide with the astronomical equinox. The function uses the positive and negative obliquity at the requested year as the geocentric solstitial declinations. Each fixed track is followed through one rotation from lower culmination to lower culmination. Horizontal solar parallax is applied to geometric altitude before atmospheric refraction. The terrain is interpolated linearly in azimuth.

On the rising half of each track, the first emergence is selected; on the setting half, the final disappearance is selected. The circular midpoint of the two solstitial bearings is then found separately for sunrise and sunset. At each midpoint, refraction and horizontal parallax are inverted to recover the geocentric declination. Atmospheric settings are identical in both stages.

Ruggles (1997) distinguishes the spatial midpoint of the solstitial horizon bearings from the midpoint in time between the solstices.

Value

A list containing azimuth and declination. Each contains rise and set values in degrees for the supplied horizon. Declinations are geocentric. An undefined side returns NA for both values, with a warning; the other side is retained when defined.

Validation

H07 checked that partial photographs are rejected and that a full photographic profile can be used. See the H07 check in the technical manual.

In A05, rising and setting midpoints matched independent track intersections on flat, eastern-ridge and western-ridge skylines; missing polar crossings were identified. See the A05 check in the technical manual.

Crossing conventions and limitations

Both rising and setting tracks are considered in either hemisphere. The search uses the terrain-aware crossing machinery also used by riseset, including terrain vertices and interior extrema. Tangencies without a change of visibility are excluded. Multiple terrain crossings are resolved using the first-emergence/final-disappearance rule; this need not be the locally preferred observational definition of sunrise or sunset. Inspect complex skylines before interpretation.

If either solstitial track lacks the required crossing, the corresponding midpoint is undefined. This includes polar non-rising/non-setting cases and complete terrain obstruction. Exactly opposite bearings have no unique circular midpoint and also return NA.

These are fixed-declination solar-centre tracks, not a dated solar ephemeris or upper-limb calculation. The mean horizontal parallax is fixed, and the refraction model cannot represent local atmospheric anomalies. Results are limited by horizon resolution and atmospheric assumptions. Solar semidiameter is not included. The result is a spatial midpoint, not the Sun's rising or setting at the astronomical equinox.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

References

Ruggles, C. L. N. (1997). Whose Equinox? Journal for the History of Astronomy 28, S45-S96. doi:10.1177/002182869702802205.

See Also

jS, dS, eq, zenith, antizenith, findTargets

Examples

## Not run: 
hor <- createHWT(34.174051531543405, 110.81299818694872, name='Xipo, Lingbao')
spatial.equinox(hor, year="3250 BC")

## End(Not run)

Sum orientation probability densities

Description

Combine uncertain orientations to show where a group of structures concentrates in azimuth or declination.

Usage

spd(pdf, xrange, normalise = F, .res = 0.01, .cutoff = 1e-05)

Arguments

pdf

A skyscapeR.pdf object created with either az.pdf or coordtrans

xrange

Array of values (min and max) for SPD if different from range of pdf. If given, it overrides .cutoff

normalise

If TRUE, scale the returned density to unit area using trapezoidal integration. Default FALSE leaves the summed density unnormalised.

.res

Resolution with which to output SPD. Default is 0.01 degrees.

.cutoff

When the range is chosen automatically, set summed densities below this threshold to zero. Default 1e-5.

Details

A summed probability density gives each input measurement one density curve. The function linearly interpolates these curves onto one angular grid, assigns zero outside each curve's sampled support and adds their heights point by point. With an automatically chosen range it zeroes summed heights below the cutoff. With an explicit range it retains the calculated heights across that range.

Normalisation takes place after interpolation and any cutoff, over the returned grid. An explicit restricted xrange therefore normalises the retained portion only. Zero-area, nonfinite or negative densities and grids with fewer than two points cannot be normalised and produce an error. Earlier versions divided by the sum of sampled heights. Normalised outputs now have a different scale; on a regular grid with zero endpoint densities, new heights equal old heights divided by .res. Existing saved objects are not converted. Changing resolution can still affect interpolation and truncation accuracy, but the returned trapezoidal area is one.

Value

A skyscapeR.spd list with metadata and a data data frame containing coordinate x (degrees) and density y. Normalised densities have units of inverse degrees.

Validation

The tested sums agreed with independently constructed density sums, and the normalised curves had unit trapezoidal area. See D01 validation in the technical manual.

For two bearings on a shared slope, the D02 comparison of summing before and after transformation gave an integrated absolute density difference of 0.00159 after normalisation. See the D02 check in the technical manual.

Scientific checks

References

Silva, F (2020) A probabilistic framework and significance test for the analysis of structural orientations in skyscape archaeology Journal of Archaeological Science 118, 105138. doi:10.1016/j.jas.2020.105138

See Also

az.pdf, coordtrans, hpdi, randomTest, dec.pdf, modelTest, plot.skyscapeR.spd

Examples

# SPD of azimuths
Az <- az.pdf(az=c(87,93,90,110), unc=3)
s1 <- spd(Az)
plot(s1)
s.norm <- spd(Az, normalise=TRUE)
with(s.norm$data, sum(diff(x) * (head(y,-1) + tail(y,-1))/2)) # 1

# SPD of declinations
hor <- createHor(az=c(0,360), alt=c(0,0), loc=c(35,-8,25)) # flat horizon
Dec <- coordtrans(Az, hor)
s2 <- spd(Dec)
plot(s2)

Calculate a fixed star's coordinates for an epoch

Description

Find a catalogue object's equatorial position at an archaeological epoch and its apparent magnitude for a sky or visibility model.

Usage

star(string, year = skyscapeR.env$cur.year)

Arguments

string

This can be either the traditional name for the star or its Bayer designation.

year

Year for which to calculate the coordinates. Historical labels such as "3700 BC" are accepted by astroYear. Defaults to current year.

Details

A historical comparison requires a stellar coordinate for the epoch under study. The function resolves a Western common name through star.names or accepts a catalogue identifier and checks it against Swiss Ephemeris. It evaluates equatorial coordinates at noon UT on 1 January of each supplied astronomical year in the Gregorian calendar. The magnitude is a catalogue value. These outputs can feed horizon transformations or visibility estimates, which additionally require observer and atmosphere information.

The Swiss Ephemeris manual documents fixed-star positions and catalogue magnitudes.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

A skyscapeR.star list with name, Bayer designation, apparent magnitude (app.mag) and a coord data frame. Each row contains year, right ascension (RA) and declination (Dec), both angles in degrees.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction.

Scientific checks

References

Astrodienst. Swiss Ephemeris programmer's manual. https://www.astro.com/swisseph/swephprg.htm.

See Also

swe_fixstar2_ut, swe_fixstar2_mag, star.names, star.phases

Examples

# M45 and M 45 identify the Pleiades.
if (requireNamespace("swephRdata", quietly=TRUE)) star("M45", -4300)

if (requireNamespace("swephRdata", quietly = TRUE)) {
  # Retrieve data for Aldebaran:
  Aldeb <- star('Aldebaran')
  
  # Retrieve data for Aldebaran on 3001 BC:
  ss <- star('Aldebaran', -3000)
}

Catalogue of star names and designations

Description

Relate stellar proper names and other celestial object names to the catalogue identifiers needed to calculate stellar positions.

Usage

data(star.names)

Format

A data frame with 304 rows and two character columns.

identifier

Catalogue identifier used to look up the object in the ephemeris.

Western

Object name used in the package.

Details

Use this lookup to resolve a named target before comparing its position across epochs. Each entry associates a common name with the identifier used by the fixed-star routines. Positional and photometric calculations use the stellar catalogue; this table describes the naming convention and does not establish that a historical observer recognised the same figure.

The stellar proper names come from the IAU Catalog of Star Names, compiled by the International Astronomical Union Working Group on Star Names. The table also includes lookup entries for supernovae or their remnants, deep-sky objects, the Galactic Pole and the Galactic Centre. The WGSN describes the approved stellar names as public-domain scientific standards. See COPYRIGHTS for the catalogue attribution and source notice.

References

International Astronomical Union, Working Group on Star Names. IAU Catalog of Star Names. https://exopla.net/star-names/modern-iau-star-names/.

See Also

constellations

Examples

data(star.names)
star.names$identifier[star.names$Western == "Aldebaran"]

Model seasonal changes in stellar visibility

Description

Estimate seasonal opportunities for naked-eye stellar visibility.

Usage

star.phases(
  star,
  year,
  loc,
  alt.hor = 0,
  alt.rs = 10,
  solar.alt = NULL,
  k = skyscapeR.vars()$k,
  limit = 6,
  refraction,
  atm,
  temp,
  res = 1/24/6,
  method = c("schaefer", "purrington")
)

Arguments

star

Either the star name or a skyscapeR.star object.

year

The year of interest. Historical labels such as "3700 BC" are accepted by astroYear.

loc

Location, either a skyscapeR.horizon or a vector containing the latitude, longitude and elevation of location, in this order.

alt.hor

The altitude of the horizon to consider. Defaults to zero degrees.

alt.rs

The maximum altitude of a star's first or last visibility for it to still be considered to be as rising or setting. Defaults to ten degrees.

solar.alt

Solar altitude threshold in degrees. NULL uses -6 for a horizon, or alt.hor - 6 for coordinate input.

k

Visual extinction in magnitudes per airmass (Schaefer 1986, p. S33). The package adopts 0.2 as a clear-sky baseline. Extinction varies with site and atmospheric conditions (Schaefer 1986, 1993). Defaults to the session value from skyscapeR.vars().

limit

The maximum magnitude of a star that can be visible with the naked eye. Defaults to 6.

refraction

Logical. Apply atmospheric refraction. Defaults to the session setting in skyscapeR.vars.

atm

Atmospheric pressure in mbar. Defaults to the session setting in skyscapeR.vars.

temp

Air temperature in degrees Celsius. Defaults to the session setting in skyscapeR.vars.

res

Spacing of solar altitude samples in days, greater than zero and at most one. Default 1/144 day (ten minutes). Terrain crossings are refined separately.

method

Visibility model for first morning and last evening. Defaults to Schaefer. Select "purrington" for the passage-transition rule.

Details

The default uses Schaefer's directional twilight brightness and Hecht's naked-eye point-source threshold for heliacal rising (first morning visibility) and acronycal setting (last evening visibility). On each local mean-solar date the calculation searches the terrain-clear rising branch before noon and descending branch after noon, with the Sun below the astronomical horizon. A transition marks the first qualifying morning following an unsuccessful morning, or the last qualifying evening preceding an unsuccessful evening. Solar altitude, stellar zenith distance and the difference in azimuth determine the twilight background. The limiting magnitude sets the dark zenith reference. Rozenberg airmass and the extinction coefficient attenuate the star. Stellar clearance and extinction use the selected apparent or geometric altitude. Solar altitude in the twilight equation is geometric.

The passage bands, phase type, heliacal setting and acronycal rising use Purrington's altitude-difference rule on a 365-sample solar-longitude cycle. The solar.alt cutoff and alt.rs passage ceiling apply to this classification. Therefore a Schaefer event marker may lie inside a passage band. Selecting the Purrington method also derives first morning and last evening from the passage transitions. A horizon object must cover all bearings. With coordinates, alt.hor supplies the constant skyline.

The Schaefer fit was developed for twilight near the horizon. Searches at high latitudes or far from the solar azimuth can extend outside its empirical range. The calculation assumes a clear sky and a fixed observer limit. Moonlight, weather and observer adaptation can affect field sightings. Treat an integrated cluster magnitude as a single unresolved target.

Value

A skyscapeR.starphases object. The data and seasons tables describe the passage classification. In metadata, events records the event, schematic day, solar.longitude, local date.julian, method and numeric model.day. Use date.julian with riseset and calendar = "J" to locate a crossing. In Schaefer mode visibility.calendar contains morning and evening flags for each local date in the requested Gregorian astronomical year. local.jd is the Julian day number at 00:00 UT for that date label. The horizon.status field describes clearance from the supplied skyline.

Accuracy of first and last visibility dates

Across 56 recorded dates, heliacal rising fell within seven days of 22 of 23 first morning sightings. The median prediction was two days early. Acronycal setting fell within seven days of 21 of 33 last evening sightings. The median prediction was five days late. A week is a practical search window. Larger discrepancies occur, especially at dusk. These results apply to the two tested events. V01 observed dates and scientific checks.

Workflow checks

W02 field-to-sky replay checks the Gacrux event at Skorba West. H07 skyline coverage checks terrain inputs. A03 stellar positions checks catalogue propagation.

Scientific checks

Additional stellar visibility checks

References

Crumey, A. (2014). Human contrast threshold and astronomical visibility. MNRAS 442, 2600-2619. doi:10.1093/mnras/stu992.

Purrington, R. D. (1988). Heliacal Rising and Setting: Quantitative Aspects. Journal for the History of Astronomy 19, S72-S84. https://articles.adsabs.harvard.edu/pdf/1988JHAS...19...72P.

Schaefer, B. E. (1986). Atmospheric Extinction Effects on Stellar Alignments. Journal for the History of Astronomy 17, S32-S42. doi:10.1177/002182868601701003.

Schaefer, B. E. (1993). Astronomy and the Limits of Vision. Vistas in Astronomy 36, 311-361. doi:10.1016/0083-6656(93)90113-X.

Schaefer, B. E. (1987). Heliacal Rise Phenomena. Journal for the History of Astronomy 18, S19-S33. doi:10.1177/002182868701801103.

Brady, B. (2015). Star Phases: the Naked-eye Astronomy of the Old Kingdom Pyramid Texts. In F. Silva and N. Campion (eds), Skyscapes: The Role and Importance of the Sky in Archaeology. Oxbow Books, pp. 76-86.

See Also

plot.skyscapeR.starphases, riseset, sketchSky, skyStep, star

Examples

## Not run: 
if (requireNamespace("swephRdata", quietly = TRUE)) {
  ss1 <- star.phases('Aldebaran',-4000, c(35,-8,200))
  
  # One can then look at the star's phase type:
  ss1$metadata$type
  
  # Date range of seasons:
  ss1$metadata$seasons
  
  # Date range of phase-type events:
  ss1$metadata$events
  
  # And plot them:
  plot(ss1)
  
  # You can play with the parameters and see how predictions change:
  ss1 <- star.phases('Aldebaran',-4000, c(35,-8,200), alt.hor=2, alt.rs=5)
  plot(ss1)
}

## End(Not run)

Capture and step through the Stellarium sky above a horizon

Description

Capture an equirectangular sky panorama at the observing site and display it behind a horizon.

Usage

stellariumSky(
  hor,
  jd = NULL,
  screenshot.dir = getOption("skyscapeR.screenshot.dir", "~/Pictures/Stellarium"),
  port = 8090L,
  timeout = 60,
  time = NULL,
  timezone,
  calendar,
  display = c(landscape = FALSE, fog = FALSE),
  width = NULL
)

skyStep(hor, sky, minutes = 1, ...)

Arguments

hor

Site horizon with latitude, longitude and elevation in metres.

jd

Numeric UT Julian day. Supply either jd or time.

screenshot.dir

Existing local directory where Stellarium writes screenshots.

port

Local Remote Control server port.

timeout

Maximum wait for the capture in seconds.

time

A date and clock time such as "2026/12/21 16:00", or a POSIXct or POSIXlt instant.

timezone

For character time, a zone name or fixed UTC offset as in time2jd(). Defaults to the package setting.

calendar

For character time, the Gregorian or Julian calendar as in time2jd(). Defaults to the package setting.

display

Named logical switches: atmosphere, landscape, fog, cardinals, compass.marks (numbered horizon bearings), azimuthal.grid, equatorial.grid, constellation.lines, constellation.labels (names) and constellation.art. Use galactic.equator to toggle the Galactic equator independently of the equatorial grid. Use ecliptic and equator for the lines of date, poles for the celestial poles and zenith for the Stellarium zenith/nadir markers. Older Stellarium versions may require the Compass Marks plugin to be loaded to show the bearings. Landscape and fog default to FALSE so the site horizon supplies the foreground. Other omitted switches use the current Stellarium setting.

width

Even screenshot width in pixels, up to 8192. The default NULL uses the size configured in Stellarium. Try 4096 if a larger capture fails. For a narrow sector, sketchSky gives scalable vector detail.

sky

A background returned by sketchSky(), stellariumSky() or skyStep().

minutes

Signed elapsed minutes from the captured instant. Fractions are allowed.

...

Arguments passed to plot(hor, sky=...), such as xrange.

Details

Enable Remote Control under Configuration > Plugins in Stellarium Desktop, select Load at startup and restart if needed. Enable the server in the plugin settings. Use the local server without a password and install the R packages httr2 and png. Close dialogs and use a normal rectangular viewport. Point screenshot.dir at the directory configured in Stellarium.

The script freezes time and takes one full-sphere Cylinder Fill screenshot. The centre is south, the seam is north, and the horizon is halfway up. Choose width for more pixels per degree. R keeps the native pixels for each plotted sector. For a 30-degree sector a width of 8192 supplies about 683 source pixels. The physical plot size and graphics device determine the displayed resolution. If the script times out, check the screenshot path and that your Stellarium version offers Cylinder Fill.

Capture restores the requested display switches, location, time and time rate after taking the picture. The GUI is shown again. Each capture leaves one PNG in the screenshot directory. Replot an existing sky to inspect another bearing without recapturing.

To move through time, pass either kind of sky to skyStep(). For a natural sketchSky background, each step retains the Sun and Moon display settings and recalculates illumination from the enabled sources. Positive minutes advance the clock and negative minutes rewind it. Assign the result back to the sky variable to continue from the new instant. Repeat xrange and any other plot limits to keep the framing. A sketch is recalculated locally with its style, display switches, constellations and magnitude limit. Older sketches without saved catalogue or calendar settings use the defaults. A Stellarium step takes a fresh screenshot using the saved capture settings.

Value

stellariumSky() returns a skyscapeR.sky object with the native raster, PNG path, Julian day, observer location and capture settings. skyStep() invisibly returns the updated sky of the same kind.

Reproducibility and stepping

A Stellarium capture reflects the installed Stellarium version, its catalogues, selected sky culture and current settings for switches not explicitly supplied. It is an external rendered image, not the package's twilight or extinction model. Record those settings when comparing it with sketchSky. The external application and a working local Remote Control connection are required for every new capture, but not for replotting a saved raster.

Atmospheric settings when using skyStep

For a sketch, skyStep retains calendar, max.mag, k, style and display selections. Refraction, pressure and temperature are read again from skyscapeR.vars; the previous object's atmosphere is not restored automatically. Changing these session settings between the original sketch and a step changes the atmosphere as well as the time. Keep them fixed for a time-only comparison, including when resuming a saved sketch in another R session. This behaviour is intentional. Stellarium captures instead use the external application's atmospheric settings. Each call draws immediately and returns the new object invisibly. Save it with sky <- skyStep(hor, sky, minutes = 10) before taking the next step.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction. For Stellarium captures, these are the R package versions, not the external Stellarium engine version. Record that version and its settings separately. A stepped sky carries the package versions from the new calculation or capture.

Scientific checks

See Also

time2jd, plot.skyscapeR.horizon

Examples

## Not run: 
hor <- malta_horizons[[1]]
sector <- c(220, 240)
sky <- stellariumSky(hor, time = "2026/12/21 16:00", timezone = "UTC",
                    display = c(atmosphere = TRUE, cardinals = FALSE))
plot(hor, sky = sky, xrange = sector)
sky <- skyStep(hor, sky, minutes = 2, xrange = sector)
sky <- skyStep(hor, sky, minutes = -0.5, xrange = sector)

## End(Not run)

Select measurement densities

Description

Select measurement curves and their corresponding metadata in the requested order.

Usage

## S3 method for class 'skyscapeR.pdf'
subset(x, subset, ...)

Arguments

x

An object of class skyscapeR.pdf.

subset

An integer or logical index identifying the curves to retain.

...

Additional arguments accepted by the generic.

Value

A skyscapeR.pdf object containing the selected curves.

Scientific checks


Calculate the solar bearing for a field observation

Description

Establish the true direction of a timed solar sight used to orient an instrument in a field survey.

Usage

sunAz(loc, time, timezone, limb, alt = FALSE)

Arguments

loc

Location, either a skyscapeR.horizon or a vector containing the latitude, longitude and elevation of location, in this order.

time

String containing the date and time in the following format: "YYYY-MM-DD HH:MM:SS"

timezone

Timezone for civil timestamps. Use UTC or a fixed offset for dates before 1900. See time2jd for named zones and offsets.

limb

Measured limb of the sun. Options are left, right. If missing the center of the sun will be output.

alt

Logical that triggers output of altitude of the sun at exact time. Default is FALSE.

Details

A solar reference requires the observer position, timestamp, timezone and the part of the disc that was sighted. Times are parsed using R's civil-time routines and converted to UT Julian dates. Swiss Ephemeris supplies the topocentric solar position and its horizontal coordinates using 1013.25 mbar and 15 degrees Celsius. The returned bearing is measured clockwise from north. Sighting the left or right limb applies a fixed minus or plus 16 arcminutes in azimuth. Optional altitude is the geometric centre altitude.

Astronomical positions require Swiss Ephemeris files covering the epoch. We recommend installing swephRdata; see skyscapeR-package for setup.

Value

Solar azimuth in degrees clockwise from north, one value per observation. With alt = TRUE, a data frame with columns az and alt is returned. The altitude is geometric and is expressed in degrees.

Provenance

Structured results carry a provenance attribute. Read it with attr(result, "provenance"); its packages entry records the loaded skyscapeR and swephR versions, with NA when a namespace version is unavailable. This attribute adds no list entries or table columns. Ordinary subsetting or transformations may discard attributes; save the original result for reference. It does not identify ephemeris files, catalogue revisions or a development commit. Retain those and the analysis script separately for exact reproduction. Only the table returned with alt = TRUE carries this attribute; the default numeric output is unchanged.

Scientific validation

F01 examines magnetic and solar reductions against independent references. F01 scientific validation.

Scientific checks

See Also

reduct.theodolite

Examples

if (requireNamespace("swephRdata", quietly = TRUE)) {
  sunAz(c(52,-3,100), '2017-10-04 12:32:14', 'Europe/London')
}

Convert degrees, arcminutes and arcseconds to decimal degrees

Description

Convert a signed field angle in degrees, minutes and seconds to decimal degrees for coordinate and orientation calculations.

Usage

ten(dd, mm = 0, ss = 0)

Arguments

dd

Degrees as a finite numeric scalar, or a single character string containing an angle, for example "-8:30:00".

mm

Arcminutes as a finite numeric scalar. Defaults to zero.

ss

Arcseconds as a finite numeric scalar. Defaults to zero.

Details

The sign applies to the whole angle. The magnitude is the sum of absolute degrees, minutes divided by 60 and seconds divided by 3600. With numeric components the first nonzero component sets the sign and later components must be nonnegative. A string may contain one to three colon- or space-separated components and an optional leading sign. A string such as "-0:30" preserves the negative sign even when degrees are zero.

Value

A numeric scalar giving the angle in signed decimal degrees.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

reduct.compass, reduct.theodolite, mag.dec, sunAz, az2dec

Examples

ten(24, 52, 16)
ten(-8, 30, 0)     # -8.5 degrees
ten(0, -30, 0)     # -0.5 degrees
ten(0, 0, -30)     # -1/120 degrees
ten("-8:30:00")    # -8.5 degrees
ten("-0:30:00")    # Preserve the minus sign when degrees are zero

Convert local calendar date and time to a UT Julian date

Description

Place a dated field observation or historical event on the continuous UT Julian-date scale used in ephemeris calculations.

Usage

time2jd(time, timezone, calendar, verbose = F)

Arguments

time

Character vector in YYYY/MM/DD format, optionally followed by HH:MM or HH:MM:SS. Fractional seconds are accepted. Omitted clock time means midnight.

timezone

Timezone name or fixed offset; defaults to the value in skyscapeR.vars(). See Details.

calendar

Calendar: G or Gregorian, J or Julian. Defaults to the package calendar setting, initially Gregorian.

verbose

Logical; display a conversion message. Default is FALSE.

Details

Civil dates require both a calendar and a time convention to specify an instant. The function parses each supplied date and time, verifies that the calendar date exists by converting it to a Julian date and back, then applies the chosen offset or civil timezone to obtain UT. A date without a time uses local midnight. Astronomical year numbering includes year zero. An era label can also precede the month, for example "3700 BCE/06/21".

Fixed offsets may be numeric hours east of UTC (for example 5.5), or strings such as "UTC+05:30", "UTC-02" or "GMT+01". Offsets must lie between -14 and +14 hours. UTC, GMT and the empty string mean zero offset; an empty string does not select the system timezone.

Named zones listed by OlsonNames(), such as "Europe/London", use the installed timezone database for the actual Gregorian date, not a surrogate year. They are supported only for Gregorian years 1900-9999. Earlier dates require UTC or a fixed offset. For ancient-date workflows, set skyscapeR.vars(timezone="UTC") or provide timezone explicitly. The package's initial timezone remains Europe/London. Database versions may differ across systems; fixed offsets provide reproducible conversions.

Gregorian and Julian calendars are proleptic: no automatic calendar reform is applied. Astronomical year numbering is used: 0 is 1 BCE, -1 is 2 BCE. Fixed-offset input dates support years from -100000 to 100000. A timezone offset represents civil clock time, not local solar time. These functions apply clock offsets to a UT Julian day; they do not apply leap-second, UTC-to-UT1 or TT corrections. Leap-second input is rejected.

Ambiguous and nonexistent local times at clock transitions are rejected. For an ambiguous time, specify a fixed offset to identify the intended instant. Calendar dates and clock components are validated before conversion.

Value

A numeric vector of UT Julian dates, in the same order as time.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

jd2time, timestring, BC.AD, skyscapeR.vars

Examples

time2jd("2000/01/01 12:00:00", "UTC") # 2451545
# A positive offset crosses into the preceding UTC year:
jd <- time2jd("2020/01/01 00:30:00", "UTC+02")
jd2time(jd, "UTC") # 2019/12/31 22:30:00
# Ancient Julian-calendar date, with an explicit fixed offset:
time2jd("-4000/06/21 06:00:00", "UTC+02", calendar="J")
# A modern date uses that year's timezone rules:
time2jd("2007/03/15 12:00:00", "America/New_York")

Assemble a timestamp from calendar and clock fields

Description

Assemble separately recorded date and clock fields into the timestamp used by the package's ephemeris routines.

Usage

timestring(year, month, day, hour = 12, minute = 0, second = 0)

Arguments

year

Year. Historical labels such as "3700 BC" are accepted by astroYear.

month

Month

day

Day

hour

Hour

minute

Minute

second

Second

Details

Survey records often store year, month, day and clock time separately. This formatter pads the month, day and clock components to two characters and joins them as year/month/day and hours:minutes:seconds. Omitted time is noon. Formatting alone does not supply a timezone or check that the date exists; use time2jd to validate and convert it.

Value

A character date-time string in the slash-separated format accepted by time2jd.

Validation

Build 2.0.9005 passed all 499 calendar, clock, era, angle and setting checks in A01. The largest discrepancy across 240 absolute Julian dates was 0.000021 seconds. See A01 validation in the technical manual.

Scientific checks

See Also

time2jd, jd2time, BC.AD, long.date

Examples

timestring(2018, 12, 25, 2, 34)

Estimate solar declination at the zenith

Description

Determine the solar declination associated with an overhead passage at the observer's latitude, where such a passage is possible.

Usage

zenith(loc, parallax = 0.00224, altitude = 90, year = skyscapeR.env$cur.year)

Arguments

loc

This can be either the latitude of the location, or a skyscapeR.horizon object.

parallax

Mean horizontal parallax in degrees. The default is 0.00224 degrees for the Sun.

altitude

Altitude used in the approximate parallax correction. Defaults to 90 degrees.

year

Astronomical year used to determine the tropical latitude limit.

Details

The geometric zenith has declination equal to the site latitude. The function checks whether the latitude lies within the obliquity of the requested epoch. At the geometric zenith the altitude is 90 degrees and the parallax correction vanishes. An explicitly supplied altitude invokes the approximate correction at that altitude. The function returns NULL outside the permitted band. This supplies a declination criterion rather than the dates of the passages.

Value

Solar declination in degrees with the requested parallax correction, or NULL when the latitude falls outside the solstitial limits used by the function.

Validation

A05 verified the geometric zenith declination and tropical-boundary eligibility at two epochs. See the A05 check in the technical manual.

Scientific checks

See Also

jS, dS, eq, antizenith, spatial.equinox, parallax.corr

Examples

# Zenith sun declination for Mexico City:
zenith(19.419)

# There is no zenith sun phenomenon in London:
zenith(51.507)