def get_angam(jd, angam_type):
    """Returns the angam prevailing at a particular time

      Args:
        float jd: The Julian Day at which the angam is to be computed
        float arc_len: The arc_len for the corresponding angam
        w_moon: The multiplier for moon's longitude
        w_sun: The multiplier for sun's longitude

      Returns:
        int angam

      Examples:
      >>> get_angam(2444961.7125,NAKSHATRAM)
      16

      >>> get_angam(2444961.7125,TITHI)
      28

      >>> get_angam(2444961.7125,YOGAM)
      8

      >>> get_angam(2444961.7125,KARANAM)
      55
    """
    swe.set_sid_mode(swe.SIDM_LAHIRI)  # Force Lahiri Ayanamsha

    return int(1 + floor(get_angam_float(jd, angam_type)))
def nakshatra(jd, place):
    """Current nakshatra as of julian day (jd)
     1 = Asvini, 2 = Bharani, ..., 27 = Revati
  """
    swe.set_sid_mode(swe.SIDM_LAHIRI)
    # 1. Find time of sunrise
    lat, lon, tz = place
    rise = sunrise(jd, place)[0] - tz / 24.  # Sunrise at UT 00:00

    # Swiss Ephemeris always gives Sayana. So subtract ayanamsa to get Nirayana
    offsets = [0.0, 0.25, 0.5, 0.75, 1.0]
    longitudes = [(lunar_longitude(rise + t) - swe.get_ayanamsa_ut(rise)) % 360
                  for t in offsets]

    # 2. Today's nakshatra is when offset = 0
    # There are 27 Nakshatras spanning 360 degrees
    nak = ceil(longitudes[0] * 27 / 360)

    # 3. Find end time by 5-point inverse Lagrange interpolation
    y = unwrap_angles(longitudes)
    x = offsets
    approx_end = inverse_lagrange(x, y, nak * 360 / 27)
    ends = (rise - jd + approx_end) * 24 + tz
    answer = [int(nak), to_dms(ends)]

    # 4. Check for skipped nakshatra
    nak_tmrw = ceil(longitudes[-1] * 27 / 360)
    isSkipped = (nak_tmrw - nak) % 27 > 1
    if isSkipped:
        leap_nak = nak + 1
        approx_end = inverse_lagrange(offsets, longitudes, leap_nak * 360 / 27)
        ends = (rise - jd + approx_end) * 24 + tz
        answer += [int(leap_nak), to_dms(ends)]

    return answer
def get_last_dhanur_transit (jd_start,latitude,longitude):
  swisseph.set_sid_mode(swisseph.SIDM_LAHIRI) #Force Lahiri Ayanamsha
  for d in range(-25,0):
    jd = jd_start + d
    [y,m,d,t] = swisseph.revjul(jd)
  
    jd_sunrise=swisseph.rise_trans(jd_start=jd,body=swisseph.SUN,lon=longitude,
      lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
    jd_sunrise_tmrw=swisseph.rise_trans(jd_start=jd+1,body=swisseph.SUN,
      lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
    jd_sunset =swisseph.rise_trans(jd_start=jd,body=swisseph.SUN,lon=longitude,
      lat=latitude,rsmi=swisseph.CALC_SET|swisseph.BIT_DISC_CENTER)[1][0]
  
    longitude_sun=swisseph.calc_ut(jd_sunrise,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_sunrise)
    longitude_sun_set=swisseph.calc_ut(jd_sunset,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_sunset)
    sun_month_rise = int(1+math.floor(((longitude_sun)%360)/30.0))
    sun_month = int(1+math.floor(((longitude_sun_set)%360)/30.0))
    longitude_sun_tmrw=swisseph.calc_ut(jd_sunrise+1,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_sunrise+1)
    sun_month_tmrw = int(1+math.floor(((longitude_sun_tmrw)%360)/30.0))

    if sun_month_rise!=sun_month_tmrw:
      if sun_month!=sun_month_tmrw:
        return jd+1
      else:
        return jd
Example #4
0
def raasi(jd):
  """Zodiac of given jd. 1 = Mesha, ... 12 = Meena"""
  swe.set_sid_mode(swe.SIDM_LAHIRI)
  s = solar_longitude(jd)
  solar_nirayana = (solar_longitude(jd) - swe.get_ayanamsa_ut(jd)) % 360
  # 12 rasis occupy 360 degrees, so each one is 30 degrees
  return ceil(solar_nirayana / 30.)
def raasi(jd):
    """Zodiac of given jd. 1 = Mesha, ... 12 = Meena"""
    swe.set_sid_mode(swe.SIDM_LAHIRI)
    s = solar_longitude(jd)
    solar_nirayana = (solar_longitude(jd) - swe.get_ayanamsa_ut(jd)) % 360
    # 12 rasis occupy 360 degrees, so each one is 30 degrees
    return ceil(solar_nirayana / 30.)
Example #6
0
    def planets_lister(self):
        """Sidereal or tropic mode."""
        self.iflag = swe.FLG_SWIEPH + swe.FLG_SPEED

        if self.zodiactype == "sidereal":
            self.iflag += swe.FLG_SIDEREAL
            mode = "SIDM_FAGAN_BRADLEY"
            swe.set_sid_mode(getattr(swe, mode))
        """Calculates the position of the planets and stores it in a list."""

        self.sun_deg = swe.calc(self.j_day, 0, self.iflag)[0][0]
        self.moon_deg = swe.calc(self.j_day, 1, self.iflag)[0][0]
        self.mercury_deg = swe.calc(self.j_day, 2, self.iflag)[0][0]
        self.venus_deg = swe.calc(self.j_day, 3, self.iflag)[0][0]
        self.mars_deg = swe.calc(self.j_day, 4, self.iflag)[0][0]
        self.jupiter_deg = swe.calc(self.j_day, 5, self.iflag)[0][0]
        self.saturn_deg = swe.calc(self.j_day, 6, self.iflag)[0][0]
        self.uranus_deg = swe.calc(self.j_day, 7, self.iflag)[0][0]
        self.neptune_deg = swe.calc(self.j_day, 8, self.iflag)[0][0]
        self.pluto_deg = swe.calc(self.j_day, 9, self.iflag)[0][0]
        self.mean_node_deg = swe.calc(self.j_day, 10, self.iflag)[0][0]
        self.true_node_deg = swe.calc(self.j_day, 11, self.iflag)[0][0]

        #print(swe.calc(self.j_day, 7, self.iflag)[3])

        self.planets_degs = [
            self.sun_deg, self.moon_deg, self.mercury_deg, self.venus_deg,
            self.mars_deg, self.jupiter_deg, self.saturn_deg, self.uranus_deg,
            self.neptune_deg, self.pluto_deg, self.mean_node_deg,
            self.true_node_deg
        ]

        return self.planets_degs
Example #7
0
def get_angam(jd, angam_type, ayanamsha_id=swe.SIDM_LAHIRI):
    """Returns the angam prevailing at a particular time

      Args:
        float jd: The Julian Day at which the angam is to be computed
        float arc_len: The arc_len for the corresponding angam

      Returns:
        int angam

      Examples:
      >>> get_angam(2444961.7125,NAKSHATRAM)
      16

      >>> get_angam(2444961.7125,TITHI)
      28

      >>> get_angam(2444961.7125,YOGA)
      8

      >>> get_angam(2444961.7125,KARANAM)
      55
    """
    swe.set_sid_mode(ayanamsha_id)

    return int(
        1 + floor(get_angam_float(jd, angam_type, ayanamsha_id=ayanamsha_id)))
Example #8
0
def nakshatra(jd, place):
  """Current nakshatra as of julian day (jd)
     1 = Asvini, 2 = Bharani, ..., 27 = Revati
  """
  swe.set_sid_mode(swe.SIDM_LAHIRI)
  # 1. Find time of sunrise
  lat, lon, tz = place
  rise = sunrise(jd, place)[0] - tz / 24.  # Sunrise at UT 00:00
   
  # Swiss Ephemeris always gives Sayana. So subtract ayanamsa to get Nirayana
  offsets = [0.0, 0.25, 0.5, 0.75, 1.0]
  longitudes = [ (lunar_longitude(rise + t) - swe.get_ayanamsa_ut(rise)) % 360 for t in offsets]

  # 2. Today's nakshatra is when offset = 0
  # There are 27 Nakshatras spanning 360 degrees
  nak = ceil(longitudes[0] * 27 / 360)
  
  # 3. Find end time by 5-point inverse Lagrange interpolation
  y = unwrap_angles(longitudes)
  x = offsets
  approx_end = inverse_lagrange(x, y, nak * 360 / 27)
  ends = (rise - jd + approx_end) * 24 + tz
  answer = [int(nak), to_dms(ends)]

  # 4. Check for skipped nakshatra
  nak_tmrw = ceil(longitudes[-1] * 27 / 360)
  isSkipped = (nak_tmrw - nak) % 27 > 1
  if isSkipped:
    leap_nak = nak + 1
    approx_end = inverse_lagrange(offsets, longitudes, leap_nak * 360 / 27)
    ends = (rise - jd + approx_end) * 24 + tz
    answer += [int(leap_nak), to_dms(ends)]

  return answer
Example #9
0
    def get_lagna_float(self, jd, offset=0, debug=False):
        """Returns the angam

          Args:
            :param jd: The Julian Day at which the lagnam is to be computed
            :param offset: Used by internal functions for bracketing
            :param debug

          Returns:
            float lagna
        """
        swe.set_sid_mode(self.ayanamsha_id)
        lcalc = swe.houses_ex(
            jd, self.city.latitude,
            self.city.longitude)[1][0] - swe.get_ayanamsa_ut(jd)
        lcalc = lcalc % 360

        if offset == 0:
            return lcalc / 30

        else:
            if debug:
                logging.debug(debug)
                logging.debug(('offset:', offset))
                logging.debug(('lcalc/30', lcalc / 30))
                logging.debug(('lcalc/30 + offset = ', lcalc / 30 + offset))

            # The max expected value is somewhere between 2 and -2, with bracketing

            if (lcalc / 30 + offset) >= 3:
                return (lcalc / 30) + offset - 12
            elif (lcalc / 30 + offset) <= -3:
                return (lcalc / 30)
            else:
                return (lcalc / 30) + offset
Example #10
0
def get_angam_float(jd,
                    angam_type,
                    offset=0,
                    ayanamsha_id=swe.SIDM_LAHIRI,
                    debug=False):
    """Returns the angam

      Args:
        float jd: The Julian Day at which the angam is to be computed
        angam_type: One of the pre-defined constants in the panchangam
        class, such as TITHI, NAKSHATRAM, YOGA, KARANAM or SOLAR_MONTH

      Returns:
        float angam

      Examples:
        >>> get_angam_float(2444961.7125,NAKSHATRAM)
        15.967801358055189
    """
    swe.set_sid_mode(ayanamsha_id)
    w_moon = angam_type['w_moon']
    w_sun = angam_type['w_sun']
    arc_len = angam_type['arc_len']

    lcalc = 0  # computing weighted longitudes
    if debug:
        logging.debug('## get_angam_float(): jd=%f', jd)
        logging.debug("Ayanamsha: %f", swe.get_ayanamsa(jd))

    #  Get the lunar longitude, starting at the ayanaamsha point in the ecliptic.
    if w_moon != 0:
        lmoon = (swe.calc_ut(jd, swe.MOON)[0] - swe.get_ayanamsa(jd)) % 360
        if (debug):
            logging.debug("Moon longitude: %f", swe.calc_ut(jd, swe.MOON)[0])
            logging.debug('## get_angam_float(): lmoon=%f', lmoon)
        lcalc += w_moon * lmoon

    #  Get the solar longitude, starting at the ayanaamsha point in the ecliptic.
    if w_sun != 0:
        lsun = (swe.calc_ut(jd, swe.SUN)[0] - swe.get_ayanamsa(jd)) % 360
        if (debug):
            logging.debug('## get_angam_float(): lsun=%f', lsun)
        lcalc += w_sun * lsun

    if debug:
        logging.debug('## get_angam_float(): lcalc=%f', lcalc)

    lcalc = lcalc % 360

    if debug:
        logging.debug('## get_angam_float(): lcalc %% 360=%f', lcalc)
        logging.debug("offset: %f", offset)
        logging.debug(offset + int(360.0 / arc_len))

    if offset + int(360.0 / arc_len) == 0 and lcalc < arc_len:
        # Angam 1 -- needs different treatment, because of 'discontinuity'
        return (lcalc / arc_len)
    else:
        return (lcalc / arc_len) + offset
def yoga(jd, place):
    """Yoga at given jd and place.
     1 = Vishkambha, 2 = Priti, ..., 27 = Vaidhrti
  """
    swe.set_sid_mode(swe.SIDM_LAHIRI)
    # 1. Find time of sunrise
    lat, lon, tz = place
    rise = sunrise(jd, place)[0] - tz / 24.  # Sunrise at UT 00:00

    # 2. Find the Nirayana longitudes and add them
    lunar_long = (lunar_longitude(rise) - swe.get_ayanamsa_ut(rise)) % 360
    solar_long = (solar_longitude(rise) - swe.get_ayanamsa_ut(rise)) % 360
    total = (lunar_long + solar_long) % 360
    # There are 27 Yogas spanning 360 degrees
    yog = ceil(total * 27 / 360)

    # 3. Find how many longitudes is there left to be swept
    degrees_left = yog * (360 / 27) - total

    # 3. Compute longitudinal sums at intervals of 0.25 days from sunrise
    offsets = [0.25, 0.5, 0.75, 1.0]
    lunar_long_diff = [
        (lunar_longitude(rise + t) - lunar_longitude(rise)) % 360
        for t in offsets
    ]
    solar_long_diff = [
        (solar_longitude(rise + t) - solar_longitude(rise)) % 360
        for t in offsets
    ]
    total_motion = [
        moon + sun for (moon, sun) in zip(lunar_long_diff, solar_long_diff)
    ]

    # 4. Find end time by 4-point inverse Lagrange interpolation
    y = total_motion
    x = offsets
    # compute fraction of day (after sunrise) needed to traverse 'degrees_left'
    approx_end = inverse_lagrange(x, y, degrees_left)
    ends = (rise + approx_end - jd) * 24 + tz
    answer = [int(yog), to_dms(ends)]

    # 5. Check for skipped yoga
    lunar_long_tmrw = (lunar_longitude(rise + 1) -
                       swe.get_ayanamsa_ut(rise + 1)) % 360
    solar_long_tmrw = (solar_longitude(rise + 1) -
                       swe.get_ayanamsa_ut(rise + 1)) % 360
    total_tmrw = (lunar_long_tmrw + solar_long_tmrw) % 360
    tomorrow = ceil(total_tmrw * 27 / 360)
    isSkipped = (tomorrow - yog) % 27 > 1
    if isSkipped:
        # interpolate again with same (x,y)
        leap_yog = yog + 1
        degrees_left = leap_yog * (360 / 27) - total
        approx_end = inverse_lagrange(x, y, degrees_left)
        ends = (rise + approx_end - jd) * 24 + tz
        answer += [int(leap_yog), to_dms(ends)]

    return answer
Example #12
0
def elapsed_year(jd):
  swe.set_sid_mode(swe.SIDM_LAHIRI)
  ahar = ahargana(jd)
  mean_sidereal_year = 365.25636
  solar_long = (solar_longitude(jd) - swe.get_ayanamsa_ut(jd)) % 360
  kali = round(ahar / mean_sidereal_year -  solar_long / 360)
  saka = kali - 3179
  vikrama = saka + 135
  return kali, saka
Example #13
0
 def compute_solar_month(self):
   if not hasattr(self, "jd_sunrise") or self.jd_sunrise is None:
     self.compute_sun_moon_transitions()
   swe.set_sid_mode(self.ayanamsha_id)
   self.longitude_sun_sunrise = swe.calc_ut(self.jd_sunrise, swe.SUN)[0] - swe.get_ayanamsa(self.jd_sunrise)
   self.longitude_sun_sunset = swe.calc_ut(self.jd_sunset, swe.SUN)[0] - swe.get_ayanamsa(self.jd_sunset)
   
   # Each solar month has 30 days. So, divide the longitude by 30 to get the solar month.
   self.solar_month_sunset = int(1 + floor((self.longitude_sun_sunset % 360) / 30.0))
   self.solar_month_sunrise = int(1 + floor(((self.longitude_sun_sunrise) % 360) / 30.0))
Example #14
0
def function(point):
    swe.set_sid_mode(swe.SIDM_USER, point, 0.0)
    #swe.set_sid_mode(swe.SIDM_LAHIRI)
    # Place Revati at 359°50'
    #fval = norm180(swe.fixstar_ut("Revati", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0]) - ((359 + 49/60 + 59/3600) - 360)
    # Place Revati at 0°0'0"
    #fval = norm180(swe.fixstar_ut("Revati", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0])
    # Place Citra at 180°
    fval = swe.fixstar_ut("Citra", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0] - (180)
    # Place Pushya (delta Cancri) at 106°
    # fval = swe.fixstar_ut(",deCnc", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0] - (106)
    return fval
Example #15
0
def function(point):
    swe.set_sid_mode(swe.SIDM_USER, point, 0.0)
    #swe.set_sid_mode(swe.SIDM_LAHIRI)
    # Place Revati at 359°50'
    #fval = norm180(swe.fixstar_ut("Revati", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0]) - ((359 + 49/60 + 59/3600) - 360)
    # Place Revati at 0°0'0"
    #fval = norm180(swe.fixstar_ut("Revati", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0])
    # Place Citra at 180°
    fval = swe.fixstar_ut("Citra", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0] - (180)
    # Place Pushya (delta Cancri) at 106°
    # fval = swe.fixstar_ut(",deCnc", point, flag = swe.FLG_SWIEPH | swe.FLG_SIDEREAL)[0] - (106)
    return fval
Example #16
0
 def get_offset(self, jd):
     if self.ayanaamsha_id == Ayanamsha.VERNAL_EQUINOX_AT_0:
         return 0
     elif self.ayanaamsha_id == Ayanamsha.CHITRA_AT_180:
         # TODO: The below fails due to https://github.com/astrorigin/pyswisseph/issues/35
         from jyotisha.panchaanga.temporal import body
         return body.get_star_longitude(star="Spica", jd=jd) - 180
     elif self.ayanaamsha_id == Ayanamsha.ASHVINI_STARTING_0:
         return 0
     elif self.ayanaamsha_id == Ayanamsha.RASHTRIYA_PANCHANGA_NAKSHATRA_TRACKING:
         swe.set_sid_mode(swe.SIDM_LAHIRI)
         return swe.get_ayanamsa_ut(jd)
     raise Exception("Bad ayanamsha_id")
Example #17
0
def get_planet_next_transit(jd_start, jd_end, planet, ayanamsha_id=swe.SIDM_LAHIRI):
    """Returns the next transit of the given planet e.g. swe.JUPITER

      Args:
        float jd_start, jd_end: The Julian Days between which transits must be computed
        int planet  - e.g. swe.SUN, swe.JUPITER, ...

      Returns:
        List of tuples [(float jd_transit, int old_rashi, int new_rashi)]

      Examples:
      >>> get_planet_next_transit(2457755, 2458120, swe.JUPITER)
      [(2458008.5710764076, 6, 7)]
    """
    swe.set_sid_mode(ayanamsha_id)

    transits = []
    MIN_JUMP = 15  # Random check for a transit every 15 days!
    # Could be tweaked based on planet using a dict?

    curr_L_bracket = jd_start
    curr_R_bracket = jd_start + MIN_JUMP

    while curr_R_bracket <= jd_end:
        L_rashi = floor(get_planet_lon(curr_L_bracket, planet, offset=0,
                                       ayanamsha_id=ayanamsha_id) / 30) + 1
        R_rashi = floor(get_planet_lon(curr_R_bracket, planet, offset=0,
                                       ayanamsha_id=ayanamsha_id) / 30) + 1

        if L_rashi == R_rashi:
            curr_R_bracket += MIN_JUMP
            continue
        else:
            # We have bracketed a transit!
            if L_rashi < R_rashi:
                target = R_rashi
            else:
                # retrograde transit
                target = L_rashi
            try:
                jd_transit = brentq(get_planet_lon, curr_L_bracket, curr_R_bracket,
                                    args=(planet, (-target + 1) * 30, ayanamsha_id))
                transits += [(jd_transit, L_rashi, R_rashi)]
                curr_R_bracket += MIN_JUMP
                curr_L_bracket = jd_transit + MIN_JUMP
            except ValueError:
                sys.stderr.write('Unable to compute transit of planet;\
                                 possibly could not bracket correctly!\n')
                return (None, None, None)

    return transits
Example #18
0
    def __init__(self,
                 city: City,
                 year: int,
                 month: int,
                 day: int,
                 ayanamsha_id: int = swe.SIDM_LAHIRI,
                 previous_day_panchangam=None) -> None:
        """Constructor for the panchangam.
        """
        super(DailyPanchanga, self).__init__()
        self.city = city
        (self.year, self.month, self.day) = (year, month, day)
        self.julian_day_start = self.city.local_time_to_julian_day(
            year=self.year,
            month=self.month,
            day=self.day,
            hours=0,
            minutes=0,
            seconds=0)

        self.weekday = datetime.date(
            year=self.year, month=self.month, day=self.day).isoweekday() % 7
        self.ayanamsha_id = ayanamsha_id
        swe.set_sid_mode(ayanamsha_id)

        self.jd_sunrise = None
        self.jd_sunset = None
        self.jd_previous_sunset = None
        self.jd_next_sunrise = None
        self.jd_moonrise = None
        self.jd_moonset = None
        self.compute_sun_moon_transitions(
            previous_day_panchangam=previous_day_panchangam)

        self.tb_muhuurtas = None
        self.lagna_data = None
        self.kaalas = None

        self.solar_month_day = None
        self.solar_month_end_jd = None

        self.tithi_data = None
        self.tithi_at_sunrise = None
        self.nakshatram_data = None
        self.nakshatram_at_sunrise = None
        self.yoga_data = None
        self.yoga_at_sunrise = None
        self.karanam_data = None
        self.rashi_data = None

        self.festivals = []
Example #19
0
def get_angam_float(jd, angam_type, offset=0, debug=False):
    """Returns the angam

      Args:
        float jd: The Julian Day at which the angam is to be computed
        angam_type: One of the pre-defined constants in the panchangam
            class, such as TITHI, NAKSHATRAM, YOGAM, KARANAM or
            SOLAR_MONTH

      Returns:
        float angam

      Examples:
        >>> get_angam_float(2444961.7125,NAKSHATRAM)
        15.967801358055189
    """
    swe.set_sid_mode(swe.SIDM_LAHIRI)  # Force Lahiri Ayanamsha
    w_moon = angam_type['w_moon']
    w_sun = angam_type['w_sun']
    arc_len = angam_type['arc_len']

    lcalc = 0  # computing weighted longitudes
    if debug:
        print('## get_angam_float(): jd=', jd)

    if w_moon != 0:
        lmoon = (swe.calc_ut(jd, swe.MOON)[0] - swe.get_ayanamsa(jd)) % 360
        if (debug):
            print('## get_angam_float(): lmoon=', lmoon)
        lcalc += w_moon * lmoon

    if w_sun != 0:
        lsun = (swe.calc_ut(jd, swe.SUN)[0] - swe.get_ayanamsa(jd)) % 360
        if (debug):
            print('## get_angam_float(): lsun=', lsun)
        lcalc += w_sun * lsun

    if debug:
        print('## get_angam_float(): lcalc=', lcalc)

    lcalc = lcalc % 360

    if debug:
        print('## get_angam_float(): lcalc%360=', lcalc)
        print("offset: ", offset)
        print(offset + int(360.0 / arc_len))
    if offset + int(360.0 / arc_len) == 0 and lcalc + offset >= 0:
        return (lcalc / arc_len)
    else:
        return (lcalc / arc_len) + offset
Example #20
0
 def _setup_swisseph(self):
     """Prepare swisseph for calculations."""
     f = self._filter
     # ephemeris type
     if f._ephe_type == 'swiss':
         swe.set_ephe_path(f._ephe_path)
     elif f._ephe_type == 'jpl':
         swe.set_jpl_file(f._ephe_path)
     # sidereal mode
     if f._sid_mode > -1:
         swe.set_sid_mode(f._sid_mode, f._sid_t0, f._sid_ayan_t0)
     # situation
     if f._xcentric == 'topo':
         swe.set_topo(float(self._longitude), float(self._latitude),
             self._altitude)
Example #21
0
def yoga(jd, place):
  """Yoga at given jd and place.
     1 = Vishkambha, 2 = Priti, ..., 27 = Vaidhrti
  """
  swe.set_sid_mode(swe.SIDM_LAHIRI)
  # 1. Find time of sunrise
  lat, lon, tz = place
  rise = sunrise(jd, place)[0] - tz / 24.  # Sunrise at UT 00:00

  # 2. Find the Nirayana longitudes and add them
  lunar_long = (lunar_longitude(rise) - swe.get_ayanamsa_ut(rise)) % 360
  solar_long = (solar_longitude(rise) - swe.get_ayanamsa_ut(rise)) % 360
  total = (lunar_long + solar_long) % 360
  # There are 27 Yogas spanning 360 degrees
  yog = ceil(total * 27 / 360)

  # 3. Find how many longitudes is there left to be swept
  degrees_left = yog * (360 / 27) - total

  # 3. Compute longitudinal sums at intervals of 0.25 days from sunrise
  offsets = [0.25, 0.5, 0.75, 1.0]
  lunar_long_diff = [ (lunar_longitude(rise + t) - lunar_longitude(rise)) % 360 for t in offsets ]
  solar_long_diff = [ (solar_longitude(rise + t) - solar_longitude(rise)) % 360 for t in offsets ]
  total_motion = [ moon + sun for (moon, sun) in zip(lunar_long_diff, solar_long_diff) ]

  # 4. Find end time by 4-point inverse Lagrange interpolation
  y = total_motion
  x = offsets
  # compute fraction of day (after sunrise) needed to traverse 'degrees_left'
  approx_end = inverse_lagrange(x, y, degrees_left)
  ends = (rise + approx_end - jd) * 24 + tz
  answer = [int(yog), to_dms(ends)]

  # 5. Check for skipped yoga
  lunar_long_tmrw = (lunar_longitude(rise + 1) - swe.get_ayanamsa_ut(rise + 1)) % 360
  solar_long_tmrw = (solar_longitude(rise + 1) - swe.get_ayanamsa_ut(rise + 1)) % 360
  total_tmrw = (lunar_long_tmrw + solar_long_tmrw) % 360
  tomorrow = ceil(total_tmrw * 27 / 360)
  isSkipped = (tomorrow - yog) % 27 > 1
  if isSkipped:
    # interpolate again with same (x,y)
    leap_yog = yog + 1
    degrees_left = leap_yog * (360 / 27) - total
    approx_end = inverse_lagrange(x, y, degrees_left)
    ends = (rise + approx_end - jd) * 24 + tz
    answer += [int(leap_yog), to_dms(ends)]

  return answer
Example #22
0
def get_planet_lon(jd, planet, offset=0, ayanamsha_id=swe.SIDM_LAHIRI):
    """Returns the longitude of the given planet e.g. swe.JUPITER

      Args:
        float jd: The Julian Day at which the longitude is to be computed
        int planet  - e.g. swe.SUN, swe.JUPITER, ...

      Returns:
        float longitude

      Examples:
      >>> get_planet_lon(2458008.58, swe.JUPITER)
      180.00174875784376
    """
    swe.set_sid_mode(ayanamsha_id)
    lon = (swe.calc_ut(jd, planet)[0] - swe.get_ayanamsa(jd)) % 360
    return lon + offset
Example #23
0
 def __init__(self, city, julian_day, ayanamsha_id=swe.SIDM_LAHIRI):
   """Constructor for the panchangam.
   """
   super().__init__()
   self.city = city
   self.julian_day = julian_day
   self.julian_day_start = None
   self.compute_jd_start()
   self.ayanamsha_id = ayanamsha_id
   swe.set_sid_mode(ayanamsha_id)
   self.jd_sunrise = None
   self.jd_sunset = None
   self.jd_moonrise = None
   self.jd_moonset = None
   self.tb_muhuurtas = None
   self.solar_month_day = None
   self.solar_month_end_jd = None
Example #24
0
def get_last_dhanur_transit(jd_start, latitude, longitude):
    swisseph.set_sid_mode(swisseph.SIDM_LAHIRI)  #Force Lahiri Ayanamsha
    for d in range(-25, 0):
        jd = jd_start + d
        [y, m, d, t] = swisseph.revjul(jd)

        jd_rise = swisseph.rise_trans(jd_start=jd,
                                      body=swisseph.SUN,
                                      lon=longitude,
                                      lat=latitude,
                                      rsmi=swisseph.CALC_RISE
                                      | swisseph.BIT_DISC_CENTER)[1][0]
        jd_rise_tmrw = swisseph.rise_trans(jd_start=jd + 1,
                                           body=swisseph.SUN,
                                           lon=longitude,
                                           lat=latitude,
                                           rsmi=swisseph.CALC_RISE
                                           | swisseph.BIT_DISC_CENTER)[1][0]
        jd_set = swisseph.rise_trans(jd_start=jd,
                                     body=swisseph.SUN,
                                     lon=longitude,
                                     lat=latitude,
                                     rsmi=swisseph.CALC_SET
                                     | swisseph.BIT_DISC_CENTER)[1][0]

        longitude_sun = swisseph.calc_ut(
            jd_rise, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_rise)
        longitude_sun_set = swisseph.calc_ut(
            jd_set, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_set)
        sun_month_rise = masa_names[int(1 + math.floor((
            (longitude_sun) % 360) / 30.0))]
        sun_month = masa_names[int(1 + math.floor((
            (longitude_sun_set) % 360) / 30.0))]
        longitude_sun_tmrw = swisseph.calc_ut(
            jd_rise + 1, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_rise + 1)
        sun_month_tmrw = masa_names[int(1 + math.floor((
            (longitude_sun_tmrw) % 360) / 30.0))]

        #print '%f:%d-%d-%d: rise=%s, set=%s, tmrw=%s' %(jd,y,m,d,sun_month_rise,sun_month,sun_month_tmrw)

        if sun_month_rise != sun_month_tmrw:
            if sun_month != sun_month_tmrw:
                return jd + 1
            else:
                return jd
Example #25
0
def calculate_iflag(input_data):

    config = input_data['config']

    iflag = SEFLG_SWIEPH + SEFLG_SPEED

    if config['postype'] == 'truegeo':
        iflag += SEFLG_TRUEPOS
    if config['postype'] == 'topo':
        iflag += SEFLG_TOPOCTR
    if config['postype'] == 'helio':
        iflag += SEFLG_HELCTR

    if config['zodiactype'] == 'sidereal':
        iflag += SEFLG_SIDEREAL
        swe.set_sid_mode(getattr(swe, 'SIDM_' + config['siderealmode']))

    return iflag
Example #26
0
def get_lagna_float(jd, lat, lon, offset=0, ayanamsha_id=swe.SIDM_LAHIRI, debug=False):
  """Returns the angam

    Args:
      :param jd: The Julian Day at which the lagnam is to be computed
      :param lat: Latitude of the place where the lagnam is to be computed
      :param lon: Longitude of the place where the lagnam is to be computed
      :param offset: Used by internal functions for bracketing
      :param ayanamsha_id
      :param debug

    Returns:
      float lagna

    Examples:
      >>> get_lagna_float(2444961.7125,13.08784, 80.27847)
      10.353595502472984
  """
  swe.set_sid_mode(ayanamsha_id)
  lcalc = swe.houses_ex(jd, lat, lon)[1][0] - swe.get_ayanamsa_ut(jd)
  lcalc = lcalc % 360

  if offset == 0:
    return lcalc / 30

  else:
    if (debug):
      print('offset:', offset)
      print('lcalc/30', lcalc / 30)
      print('lcalc/30 + offset = ', lcalc / 30 + offset)

    # The max expected value is somewhere between 2 and -2, with bracketing

    if (lcalc / 30 + offset) >= 3:
      return (lcalc / 30) + offset - 12
    elif (lcalc / 30 + offset) <= -3:
      return (lcalc / 30)
    else:
      return (lcalc / 30) + offset
Example #27
0
def compute_lagna_float(jd, lat=13.08784, lon=80.27847, offset=0, debug=False):
    swe.set_sid_mode(swe.SIDM_LAHIRI)  # Force Lahiri Ayanamsha
    lcalc = swe.houses_ex(jd, lat, lon)[1][0] - swe.get_ayanamsa_ut(jd)
    lcalc = lcalc % 360

    if offset == 0:
        return lcalc / 30

    else:
        if (debug):
            print('offset:', offset)
            print('lcalc/30', lcalc / 30)
            print('lcalc/30 + offset = ', lcalc / 30 + offset)

        # The max expected value is somewhere between 2 and -2, with bracketing

        if (lcalc / 30 + offset) >= 3:
            return (lcalc / 30) + offset - 12
        elif (lcalc / 30 + offset) <= -3:
            return (lcalc / 30)
        else:
            return (lcalc / 30) + offset
Example #28
0
    def __init__(self, latitude='12.9399348 N', longitude='77.7337622 E'):
        self.latitude = latitude
        self.longitude = longitude
        self.topo = Topos(latitude=latitude, longitude=longitude)
        self.time_scale, self.planets = Almanac.init_skyfield()
        self.yoga = None
        self.karanam = None
        self.earth = self.planets['earth']
        self.moon = self.planets['moon']
        self.sun = self.planets['sun']
        self.time = self.time_scale.now()
        self.ayanamsa = None
        self.moon_pos = None
        self.sun_pos = None
        self.thithi = None
        self.nakshaktra = None
        self.vara = None
        self.sun_rise_cache = dict()
        self.tzone = self.time.utc_datetime().astimezone().tzinfo

        self.compute_almanac()
        Almanac._compute_tara_palan_dict()

        swe.set_sid_mode(swe.SIDM_LAHIRI)
Example #29
0
	def __init__(self,year,month,day,hour,geolon,geolat,altitude,planets,zodiac,openastrocfg,houses_override=None):
		#ephemeris path (default "/usr/share/swisseph:/usr/local/share/swisseph")
		#swe.set_ephe_path(ephe_path)
		
		#basic location		
		self.jul_day_UT=swe.julday(year,month,day,hour)
		self.geo_loc = swe.set_topo(geolon,geolat,altitude)

		#output variables
		self.planets_sign = list(range(len(planets)))
		self.planets_degree = list(range(len(planets)))
		self.planets_degree_ut = list(range(len(planets)))
		self.planets_info_string = list(range(len(planets)))
		self.planets_retrograde = list(range(len(planets)))
		
		#iflag
		"""
		#define SEFLG_JPLEPH         1L     // use JPL ephemeris
		#define SEFLG_SWIEPH         2L     // use SWISSEPH ephemeris, default
		#define SEFLG_MOSEPH         4L     // use Moshier ephemeris
		#define SEFLG_HELCTR         8L     // return heliocentric position
		#define SEFLG_TRUEPOS        16L     // return true positions, not apparent
		#define SEFLG_J2000          32L     // no precession, i.e. give J2000 equinox
		#define SEFLG_NONUT          64L     // no nutation, i.e. mean equinox of date
		#define SEFLG_SPEED3         128L     // speed from 3 positions (do not use it, SEFLG_SPEED is // faster and preciser.)
		#define SEFLG_SPEED          256L     // high precision speed (analyt. comp.)
		#define SEFLG_NOGDEFL        512L     // turn off gravitational deflection
		#define SEFLG_NOABERR        1024L     // turn off 'annual' aberration of light
		#define SEFLG_EQUATORIAL     2048L     // equatorial positions are wanted
		#define SEFLG_XYZ            4096L     // cartesian, not polar, coordinates
		#define SEFLG_RADIANS        8192L     // coordinates in radians, not degrees
		#define SEFLG_BARYCTR        16384L     // barycentric positions
		#define SEFLG_TOPOCTR      (32*1024L)     // topocentric positions
		#define SEFLG_SIDEREAL     (64*1024L)     // sidereal positions 		
		"""
		#check for apparent geocentric (default), true geocentric, topocentric or heliocentric
		iflag=swe.FLG_SWIEPH+swe.FLG_SPEED
		if(openastrocfg['postype']=="truegeo"):
			iflag += swe.FLG_TRUEPOS
		elif(openastrocfg['postype']=="topo"):
			iflag += swe.FLG_TOPOCTR
		elif(openastrocfg['postype']=="helio"):
			iflag += swe.FLG_HELCTR

		#sidereal
		if(openastrocfg['zodiactype']=="sidereal"):
			iflag += swe.FLG_SIDEREAL
			mode="SIDM_"+openastrocfg['siderealmode']
			swe.set_sid_mode(getattr(swe,mode.encode("ascii")))

		#compute a planet (longitude,latitude,distance,long.speed,lat.speed,speed)
		for i in range(23):
			ret_flag = swe.calc_ut(self.jul_day_UT,i,iflag)
			for x in range(len(zodiac)):
				deg_low=float(x*30)
				deg_high=float((x+1)*30)
				if ret_flag[0] >= deg_low:
					if ret_flag[0] <= deg_high:
						self.planets_sign[i]=x
						self.planets_degree[i] = ret_flag[0] - deg_low
						self.planets_degree_ut[i] = ret_flag[0]
						#if latitude speed is negative, there is retrograde
						if ret_flag[3] < 0:						
							self.planets_retrograde[i] = True
						else:
							self.planets_retrograde[i] = False

							
		#available house systems:
		"""
		hsys= ‘P’     Placidus
				‘K’     Koch
				‘O’     Porphyrius
				‘R’     Regiomontanus
				‘C’     Campanus
				‘A’ or ‘E’     Equal (cusp 1 is Ascendant)
				‘V’     Vehlow equal (Asc. in middle of house 1)
				‘X’     axial rotation system
				‘H’     azimuthal or horizontal system
				‘T’     Polich/Page (“topocentric” system)
				‘B’     Alcabitus
				‘G’     Gauquelin sectors
				‘M’     Morinus
		"""
		#houses calculation (hsys=P for Placidus)
		#check for polar circle latitude < -66 > 66
		if houses_override:
			self.jul_day_UT = swe.julday(houses_override[0],houses_override[1],houses_override[2],houses_override[3])
			
		if geolat > 66.0:
			geolat = 66.0
			print("polar circle override for houses, using 66 degrees")
		elif geolat < -66.0:
			geolat = -66.0
			print("polar circle override for houses, using -66 degrees")
		#sidereal houses
		if(openastrocfg['zodiactype']=="sidereal"):
			sh = swe.houses_ex(self.jul_day_UT,geolat,geolon,openastrocfg['houses_system'].encode("ascii"),swe.FLG_SIDEREAL)
		else:
			sh = swe.houses(self.jul_day_UT,geolat,geolon,openastrocfg['houses_system'].encode("ascii"))
		self.houses_degree_ut = list(sh[0])
		self.houses_degree = list(range(len(self.houses_degree_ut)))
		self.houses_sign = list(range(len(self.houses_degree_ut)))
		for i in range(12):
			for x in range(len(zodiac)):
				deg_low=float(x*30)
				deg_high=float((x+1)*30)
				if self.houses_degree_ut[i] >= deg_low:
					if self.houses_degree_ut[i] <= deg_high:
						self.houses_sign[i]=x
						self.houses_degree[i] = self.houses_degree_ut[i] - deg_low
		



		#compute additional points and angles
		#list index 23 is asc, 24 is Mc, 25 is Dsc, 26 is Ic
		self.planets_degree_ut[23] = self.houses_degree_ut[0]
		self.planets_degree_ut[24] = self.houses_degree_ut[9]
		self.planets_degree_ut[25] = self.houses_degree_ut[6]
		self.planets_degree_ut[26] = self.houses_degree_ut[3]	
		#arabic parts
		sun,moon,asc = self.planets_degree_ut[0],self.planets_degree_ut[1],self.planets_degree_ut[23]
		dsc,venus = self.planets_degree_ut[25],self.planets_degree_ut[3]			
		#list index 27 is day pars
		self.planets_degree_ut[27] = asc + (moon - sun)
		#list index 28 is night pars
		self.planets_degree_ut[28] = asc + (sun - moon)
		#list index 29 is South Node
		self.planets_degree_ut[29] = self.planets_degree_ut[10] - 180.0
		#list index 30 is marriage pars
		self.planets_degree_ut[30] = (asc+dsc)-venus
		#if planet degrees is greater than 360 substract 360 or below 0 add 360
		for i in range(23,31):
			if self.planets_degree_ut[i] > 360.0:
				self.planets_degree_ut[i] = self.planets_degree_ut[i] - 360.0
			elif self.planets_degree_ut[i] < 0.0:
				self.planets_degree_ut[i] = self.planets_degree_ut[i] + 360.0
			#get zodiac sign
			for x in range(12):
				deg_low=float(x*30.0)
				deg_high=float((x+1.0)*30.0)
				if self.planets_degree_ut[i] >= deg_low:
					if self.planets_degree_ut[i] <= deg_high:
						self.planets_sign[i]=x
						self.planets_degree[i] = self.planets_degree_ut[i] - deg_low
						self.planets_retrograde[i] = False

		
		
		#close swiss ephemeris
		swe.close()
Example #30
0
 def __init__(self, julday, ayanamsha_id=swe.SIDM_LAHIRI):
   self.ayanamsha_id = ayanamsha_id
   swe.set_sid_mode(ayanamsha_id)
   self.set_time(julday=julday)
Example #31
0
def get_angam_data(jd_sunrise,
                   jd_sunrise_tmrw,
                   angam_type,
                   ayanamsha_id=swe.SIDM_LAHIRI):
    """Computes angam data for angams such as tithi, nakshatram, yoga
    and karanam.

    Args:
      angam_type: TITHI, NAKSHATRAM, YOGA, KARANAM, SOLAR_MONTH, SOLAR_NAKSH


    Returns:
      tuple: A tuple comprising
        angam_sunrise: The angam that prevails as sunrise
        angam_data: a list of (int, float) tuples detailing the angams
        for the day and their end-times (Julian day)

    Examples:
      >>> get_angam_data(2444961.54042,2444962.54076,TITHI)
      [(27, 2444961.599213231)]
      >>> get_angam_data(2444961.54042,2444962.54076,NAKSHATRAM)
      [(16, 2444961.7487953394)]
      >>> get_angam_data(2444961.54042,2444962.54076,YOGA)
      [(8, 2444962.1861976916)]
      >>> get_angam_data(2444961.54042,2444962.54076,KARANAM)
      [(54, 2444961.599213231), (55, 2444962.15444546)]
    """
    swe.set_sid_mode(ayanamsha_id)

    w_moon = angam_type['w_moon']
    w_sun = angam_type['w_sun']
    arc_len = angam_type['arc_len']

    num_angas = int(360.0 / arc_len)

    # Compute angam details
    angam_now = get_angam(jd_sunrise, angam_type, ayanamsha_id=ayanamsha_id)
    angam_tmrw = get_angam(jd_sunrise_tmrw,
                           angam_type,
                           ayanamsha_id=ayanamsha_id)

    angams_list = []

    num_angas_today = (angam_tmrw - angam_now) % num_angas

    if num_angas_today == 0:
        # The angam does not change until sunrise tomorrow
        return [(angam_now, None)]
    else:
        lmoon = (swe.calc_ut(jd_sunrise, swe.MOON)[0] -
                 swe.get_ayanamsa(jd_sunrise)) % 360

        lsun = (swe.calc_ut(jd_sunrise, swe.SUN)[0] -
                swe.get_ayanamsa(jd_sunrise)) % 360

        lmoon_tmrw = (swe.calc_ut(jd_sunrise_tmrw, swe.MOON)[0] -
                      swe.get_ayanamsa(jd_sunrise_tmrw)) % 360

        lsun_tmrw = (swe.calc_ut(jd_sunrise_tmrw, swe.SUN)[0] -
                     swe.get_ayanamsa(jd_sunrise_tmrw)) % 360

        for i in range(num_angas_today):
            angam_remaining = arc_len * (i + 1) - ((
                (lmoon * w_moon + lsun * w_sun) % 360) % arc_len)

            # First compute approximate end time by essentially assuming
            # the speed of the moon and the sun to be constant
            # throughout the day. Therefore, angam_remaining is computed
            # just based on the difference in longitudes for sun and
            # moon today and tomorrow.
            approx_end = jd_sunrise + angam_remaining / (
                ((lmoon_tmrw - lmoon) % 360) * w_moon +
                ((lsun_tmrw - lsun) % 360) * w_sun)

            # Initial guess value for the exact end time of the angam
            x0 = approx_end

            # What is the target (next) angam? It is needed to be passed
            # to get_angam_float for zero-finding. If the target angam
            # is say, 12, then we need to subtract 12 from the value
            # returned by get_angam_float, so that this function can be
            # passed as is to a zero-finding method like brentq or
            # newton. Since we have a good x0 guess, it is easy to
            # bracket the function in an interval where the function
            # changes sign. Therefore, brenth can be used, as suggested
            # in the scipy documentation.
            target = (angam_now + i - 1) % num_angas + 1

            # Approximate error in calculation of end time -- arbitrary
            # used to bracket the root, for brenth
            TDELTA = 0.05
            try:
                t_act = brentq(get_angam_float,
                               x0 - TDELTA,
                               x0 + TDELTA,
                               args=(angam_type, -target, ayanamsha_id, False))
            except ValueError:
                logging.warning(
                    'Unable to bracket! Using approximate t_end itself.')
                logging.warning(locals())
                t_act = approx_end
            angams_list.extend([((angam_now + i - 1) % num_angas + 1, t_act)])
    return angams_list
Example #32
0
Date = struct('Date', ['year', 'month', 'day'])
Place = struct('Place', ['latitude', 'longitude', 'timezone'])

sidereal_year = 365.256360417   # From WolframAlpha

# Hindu sunrise/sunset is calculated w.r.t middle of the sun's disk
# They are geomretic, i.e. "true sunrise/set", so refraction is not considered
_rise_flags = swe.BIT_DISC_CENTER + swe.BIT_NO_REFRACTION

# namah suryaya chandraya mangalaya ... rahuve ketuve namah
swe.KETU = swe.PLUTO  # I've mapped Pluto to Ketu
planet_list = [swe.SUN, swe.MOON, swe.MARS, swe.MERCURY, swe.JUPITER,
               swe.VENUS, swe.SATURN, swe.MEAN_NODE, # Rahu = MEAN_NODE
               swe.KETU, swe.URANUS, swe.NEPTUNE ]

revati_359_50 = lambda: swe.set_sid_mode(swe.SIDM_USER, 1926892.343164331, 0)
galc_cent_mid_mula = lambda: swe.set_sid_mode(swe.SIDM_USER, 1922011.128853056, 0)

set_ayanamsa_mode = lambda: swe.set_sid_mode(swe.SIDM_LAHIRI)
reset_ayanamsa_mode = lambda: swe.set_sid_mode(swe.SIDM_FAGAN_BRADLEY)

# Temporary function
def get_planet_name(planet):
  names = { swe.SURYA: 'Surya', swe.CHANDRA: 'Candra', swe.KUJA: 'Mangala',
            swe.BUDHA: 'Budha', swe.GURU: 'Guru', swe.SUKRA: 'Sukra',
            swe.SANI: 'Sani', swe.RAHU: 'Rahu', swe.KETU: 'Ketu', swe.PLUTO: 'Ketu'}
  return names[planet]

# Convert 23d 30' 30" to 23.508333 degrees
from_dms = lambda degs, mins, secs: degs + mins/60 + secs/3600
Example #33
0
    def Setup_eph(self, lat, long, side=1):

        swe.set_topo(lat, long)
        swe.set_sid_mode(side)
Example #34
0
    def __init__(self,
                 year,
                 month,
                 day,
                 hour,
                 geolon,
                 geolat,
                 altitude,
                 planets,
                 zodiac,
                 openastrocfg,
                 houses_override=None):
        #ephemeris path (default "/usr/share/swisseph:/usr/local/share/swisseph")
        #swe.set_ephe_path(ephe_path)

        #basic location
        self.jul_day_UT = swe.julday(year, month, day, hour)
        self.geo_loc = swe.set_topo(geolon, geolat, altitude)

        #output variables
        self.planets_sign = list(range(len(planets)))
        self.planets_degree = list(range(len(planets)))
        self.planets_degree_ut = list(range(len(planets)))
        self.planets_info_string = list(range(len(planets)))
        self.planets_retrograde = list(range(len(planets)))

        #iflag
        """
		#define SEFLG_JPLEPH         1L     // use JPL ephemeris
		#define SEFLG_SWIEPH         2L     // use SWISSEPH ephemeris, default
		#define SEFLG_MOSEPH         4L     // use Moshier ephemeris
		#define SEFLG_HELCTR         8L     // return heliocentric position
		#define SEFLG_TRUEPOS        16L     // return true positions, not apparent
		#define SEFLG_J2000          32L     // no precession, i.e. give J2000 equinox
		#define SEFLG_NONUT          64L     // no nutation, i.e. mean equinox of date
		#define SEFLG_SPEED3         128L     // speed from 3 positions (do not use it, SEFLG_SPEED is // faster and preciser.)
		#define SEFLG_SPEED          256L     // high precision speed (analyt. comp.)
		#define SEFLG_NOGDEFL        512L     // turn off gravitational deflection
		#define SEFLG_NOABERR        1024L     // turn off 'annual' aberration of light
		#define SEFLG_EQUATORIAL     2048L     // equatorial positions are wanted
		#define SEFLG_XYZ            4096L     // cartesian, not polar, coordinates
		#define SEFLG_RADIANS        8192L     // coordinates in radians, not degrees
		#define SEFLG_BARYCTR        16384L     // barycentric positions
		#define SEFLG_TOPOCTR      (32*1024L)     // topocentric positions
		#define SEFLG_SIDEREAL     (64*1024L)     // sidereal positions 		
		"""
        #check for apparent geocentric (default), true geocentric, topocentric or heliocentric
        iflag = swe.FLG_SWIEPH + swe.FLG_SPEED
        if (openastrocfg['postype'] == "truegeo"):
            iflag += swe.FLG_TRUEPOS
        elif (openastrocfg['postype'] == "topo"):
            iflag += swe.FLG_TOPOCTR
        elif (openastrocfg['postype'] == "helio"):
            iflag += swe.FLG_HELCTR

        #sidereal
        if (openastrocfg['zodiactype'] == "sidereal"):
            iflag += swe.FLG_SIDEREAL
            mode = "SIDM_" + openastrocfg['siderealmode']
            swe.set_sid_mode(getattr(swe, mode.encode("ascii")))

        #compute a planet (longitude,latitude,distance,long.speed,lat.speed,speed)
        for i in range(23):
            ret_flag = swe.calc_ut(self.jul_day_UT, i, iflag)
            for x in range(len(zodiac)):
                deg_low = float(x * 30)
                deg_high = float((x + 1) * 30)
                if ret_flag[0] >= deg_low:
                    if ret_flag[0] <= deg_high:
                        self.planets_sign[i] = x
                        self.planets_degree[i] = ret_flag[0] - deg_low
                        self.planets_degree_ut[i] = ret_flag[0]
                        #if latitude speed is negative, there is retrograde
                        if ret_flag[3] < 0:
                            self.planets_retrograde[i] = True
                        else:
                            self.planets_retrograde[i] = False

        #available house systems:
        """
		hsys= ‘P’     Placidus
				‘K’     Koch
				‘O’     Porphyrius
				‘R’     Regiomontanus
				‘C’     Campanus
				‘A’ or ‘E’     Equal (cusp 1 is Ascendant)
				‘V’     Vehlow equal (Asc. in middle of house 1)
				‘X’     axial rotation system
				‘H’     azimuthal or horizontal system
				‘T’     Polich/Page (“topocentric” system)
				‘B’     Alcabitus
				‘G’     Gauquelin sectors
				‘M’     Morinus
		"""
        #houses calculation (hsys=P for Placidus)
        #check for polar circle latitude < -66 > 66
        if houses_override:
            self.jul_day_UT = swe.julday(houses_override[0],
                                         houses_override[1],
                                         houses_override[2],
                                         houses_override[3])

        if geolat > 66.0:
            geolat = 66.0
            print("polar circle override for houses, using 66 degrees")
        elif geolat < -66.0:
            geolat = -66.0
            print("polar circle override for houses, using -66 degrees")
        #sidereal houses
        if (openastrocfg['zodiactype'] == "sidereal"):
            sh = swe.houses_ex(self.jul_day_UT, geolat, geolon,
                               openastrocfg['houses_system'].encode("ascii"),
                               swe.FLG_SIDEREAL)
        else:
            sh = swe.houses(self.jul_day_UT, geolat, geolon,
                            openastrocfg['houses_system'].encode("ascii"))
        self.houses_degree_ut = list(sh[0])
        self.houses_degree = list(range(len(self.houses_degree_ut)))
        self.houses_sign = list(range(len(self.houses_degree_ut)))
        for i in range(12):
            for x in range(len(zodiac)):
                deg_low = float(x * 30)
                deg_high = float((x + 1) * 30)
                if self.houses_degree_ut[i] >= deg_low:
                    if self.houses_degree_ut[i] <= deg_high:
                        self.houses_sign[i] = x
                        self.houses_degree[
                            i] = self.houses_degree_ut[i] - deg_low

        #compute additional points and angles
        #list index 23 is asc, 24 is Mc, 25 is Dsc, 26 is Ic
        self.planets_degree_ut[23] = self.houses_degree_ut[0]
        self.planets_degree_ut[24] = self.houses_degree_ut[9]
        self.planets_degree_ut[25] = self.houses_degree_ut[6]
        self.planets_degree_ut[26] = self.houses_degree_ut[3]
        #arabic parts
        sun, moon, asc = self.planets_degree_ut[0], self.planets_degree_ut[
            1], self.planets_degree_ut[23]
        dsc, venus = self.planets_degree_ut[25], self.planets_degree_ut[3]
        #list index 27 is day pars
        self.planets_degree_ut[27] = asc + (moon - sun)
        #list index 28 is night pars
        self.planets_degree_ut[28] = asc + (sun - moon)
        #list index 29 is South Node
        self.planets_degree_ut[29] = self.planets_degree_ut[10] - 180.0
        #list index 30 is marriage pars
        self.planets_degree_ut[30] = (asc + dsc) - venus
        #if planet degrees is greater than 360 substract 360 or below 0 add 360
        for i in range(23, 31):
            if self.planets_degree_ut[i] > 360.0:
                self.planets_degree_ut[i] = self.planets_degree_ut[i] - 360.0
            elif self.planets_degree_ut[i] < 0.0:
                self.planets_degree_ut[i] = self.planets_degree_ut[i] + 360.0
            #get zodiac sign
            for x in range(12):
                deg_low = float(x * 30.0)
                deg_high = float((x + 1.0) * 30.0)
                if self.planets_degree_ut[i] >= deg_low:
                    if self.planets_degree_ut[i] <= deg_high:
                        self.planets_sign[i] = x
                        self.planets_degree[
                            i] = self.planets_degree_ut[i] - deg_low
                        self.planets_retrograde[i] = False

        #close swiss ephemeris
        swe.close()
def main():
  city_name = sys.argv[1]
  latitude = sexastr2deci(sys.argv[2])
  longitude = sexastr2deci(sys.argv[3])
  tz = sys.argv[4]
  
  start_year = int(sys.argv[5])
  year = start_year
  jd=swisseph.julday(year,1,1,0)
  jd_start=jd

  if len(sys.argv)==7:
    script = sys.argv[6]
  else:
    script = 'deva' #Default script is devanagari
  
  swisseph.set_sid_mode(swisseph.SIDM_LAHIRI) #Force Lahiri Ayanamsha
  
  sun_month_day = jd-get_last_dhanur_transit(jd,latitude,longitude)
  
  month_start_after_set = 0
  
  template_file=open('cal_template_compre.tex')
  template_lines=template_file.readlines()
  for i in range(0,len(template_lines)-3):
    print template_lines[i][:-1]
  
  samvatsara_id = (year - 1568)%60 + 1; #distance from prabhava
  samvatsara_names = '%s–%s' % (year_names[script][samvatsara_id], 
    year_names[script][(samvatsara_id%60)+1])
  new_yr=mesha_sankranti[script]+'~('+year_names[script][(samvatsara_id%60)+1]+'-'+samvatsara[script]+')'
  
  print '\\mbox{}'
  print '{\\font\\x="Candara" at 60 pt\\x %d\\\\[0.5cm]}' % year
  print '\\mbox{\\font\\x="Sanskrit 2003:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names
  print '{\\font\\x="Candara" at 48 pt\\x \\uppercase{%s}\\\\[0.5cm]}' % city_name
  print '\hrule'


  #INITIALISE VARIABLES
  jd_sunrise=[None]*368
  jd_sunset=[None]*368
  jd_moonrise=[None]*368
  longitude_moon=[None]*368
  longitude_sun=[None]*368
  longitude_sun_set=[None]*368
  sun_month_id=[None]*368
  sun_month=[None]*368
  sun_month_rise=[None]*368
  moon_month=[None]*368
  month_data=[None]*368
  tithi_data_string=[None]*368
  tithi_sunrise=[None]*368
  nakshatram_data_string=[None]*368
  nakshatram_sunrise=[None]*368
  karanam_data_string=[None]*368
  karanam_sunrise=[None]*368
  yogam_data_string=[None]*368
  yogam_sunrise=[None]*368
  weekday=[None]*368
  sunrise=[None]*368
  sunset=[None]*368
  madhya=[None]*368
  rahu=[None]*368
  yama=[None]*368
  festival_day_list={}
  festivals=['']*368
  
  weekday_start=swisseph.day_of_week(jd)+1
  #swisseph has Mon = 0, non-intuitively!

  ##################################################
  #Compute all parameters -- latitude/longitude etc#
  ##################################################

  for d in range(-1,367):
    jd = jd_start-1+d
    [y,m,dt,t] = swisseph.revjul(jd)
    weekday = (weekday_start -1 + d)%7 
  
    local_time = pytz.timezone(tz).localize(datetime(y, m, dt, 6, 0, 0))
    #checking @ 6am local - can we do any better?
    tz_off=datetime.utcoffset(local_time).seconds/3600.0 
    #compute offset from UTC

    jd_sunrise[d+1]=swisseph.rise_trans(jd_start=jd+1,body=swisseph.SUN,
      lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
    jd_sunset[d+1]=swisseph.rise_trans(jd_start=jd+1,body=swisseph.SUN,
      lon=longitude,lat=latitude,rsmi=swisseph.CALC_SET|swisseph.BIT_DISC_CENTER)[1][0]
    jd_moonrise[d+1]=swisseph.rise_trans(jd_start=jd+1,body=swisseph.MOON,
      lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
  
    longitude_sun[d+1]=swisseph.calc_ut(jd_sunrise[d+1],swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_sunrise[d+1])
    longitude_moon[d+1]=swisseph.calc_ut(jd_sunrise[d+1],swisseph.MOON)[0]-swisseph.get_ayanamsa(jd_sunrise[d+1])
    longitude_sun_set[d+1]=swisseph.calc_ut(jd_sunset[d+1],swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_sunset[d+1])
    
    sun_month_id[d+1] = int(1+math.floor(((longitude_sun_set[d+1])%360)/30.0))
    sun_month[d+1] = int(1+math.floor(((longitude_sun_set[d+1])%360)/30.0))

    sun_month_rise[d+1] = int(1+math.floor(((longitude_sun[d+1])%360)/30.0))

    if(d<=0):
      continue

    t_sunrise=(jd_sunrise[d]-jd)*24.0+tz_off
    t_sunset=(jd_sunset[d]-jd)*24.0+tz_off

  
    #Solar month calculations
    if month_start_after_set==1:
      sun_month_day = 0
      month_start_after_set = 0
  
    if sun_month[d]!=sun_month[d+1]:
      sun_month_day = sun_month_day + 1

      if sun_month[d]!=sun_month_rise[d+1]:
        month_start_after_set=1
        [_m,sun_month_end_time] = get_angam_data_string(masa_names[script], 30, jd_sunrise[d],
          jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], longitude_moon[d+1],
          longitude_sun[d+1], [0,1], script)
 
    elif sun_month_rise[d]!=sun_month[d]:
      #mAsa pirappu!
      #sun moves into next rAsi before sunset -- check rules!
      sun_month_day = 1

      [_m,sun_month_end_time] = get_angam_data_string(masa_names[script], 30, jd_sunrise[d],
      jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], longitude_moon[d+1],
      longitude_sun[d+1], [0,1], script)
    
    else:
      sun_month_day = sun_month_day + 1
      sun_month_end_time = ''
    
    month_data[d] = '\\sunmonth{%s}{%d}{%s}' % (masa_names[script][sun_month[d]],sun_month_day,sun_month_end_time)

    #KARADAYAN NOMBU -- easy to check here
    if sun_month_end_time !='': #month ends today
      if (sun_month[d]==12 and sun_month_day==1) or (sun_month[d]==11 and sun_month_day!=1):
        festival_day_list[karadayan_nombu[script]] = [d]
    #KOODARA VALLI -- easy to check here
    if sun_month[d]==9 and sun_month_day==27:
      festival_day_list[koodaravalli[script]]= [d]

  
    #Sunrise/sunset and related stuff (like rahu, yama)
    [rhs, rms, rss] = deci2sexa(t_sunrise)  #rise hour sun, rise minute sun, rise sec sun
    [shs, sms, sss] = deci2sexa(t_sunset)   
  
    length_of_day = t_sunset-t_sunrise
    yamagandam_start = t_sunrise + (1/8.0)*(yamagandam_octets[weekday]-1)*length_of_day
    yamagandam_end = yamagandam_start + (1/8.0)*length_of_day
    rahukalam_start = t_sunrise + (1/8.0)*(rahukalam_octets[weekday]-1)*length_of_day
    rahukalam_end = rahukalam_start + (1/8.0)*length_of_day
    madhyahnikam_start = t_sunrise + (1/5.0)*length_of_day
  
    sunrise[d]  = '%02d:%02d' % (rhs,rms)
    sunset[d]   = '%02d:%02d' % (shs,sms)
    madhya[d] = print_time(madhyahnikam_start)
    rahu[d] = '%s--%s' % (print_time(rahukalam_start), print_time(rahukalam_end))
    yama[d] = '%s--%s' % (print_time(yamagandam_start),print_time(yamagandam_end))
    
    [tithi_sunrise[d],tithi_data_string[d]]=get_angam_data_string(tithi_names[script], 12, jd_sunrise[d],
      jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], longitude_moon[d+1],
      longitude_sun[d+1], [1,-1], script)
    [nakshatram_sunrise[d], nakshatram_data_string[d]]=get_angam_data_string(nakshatra_names[script], (360.0/27.0),
      jd_sunrise[d], jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], 
      longitude_moon[d+1], longitude_sun[d+1], [1,0], script)
    [karanam_sunrise[d],karanam_data_string[d]]=get_angam_data_string(karanam_names[script], 6, jd_sunrise[d],
      jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], longitude_moon[d+1],
      longitude_sun[d+1], [1,-1], script)
    [yogam_sunrise[d],yogam_data_string[d]]=get_angam_data_string(yogam_names[script], (360.0/27.0), jd_sunrise[d],
      jd_sunrise[d+1], t_sunrise, longitude_moon[d], longitude_sun[d], longitude_moon[d+1],
      longitude_sun[d+1], [1,1], script)

  #ASSIGN MOON MONTHS
  last_month_change = 1
  last_moon_month = None
  for d in range(1,367):
    #Assign moon_month for each day
    if(tithi_sunrise[d]==1):
      for i in range(last_month_change,d):
        #print '%%#Setting moon_month to sun_month_id, for i=%d:%d to %d' %(last_month_change,d-1,sun_month_id[d])
        if (sun_month_id[d]==last_moon_month):
          moon_month[i] = sun_month_id[d]%12 + 0.5
        else:
          moon_month[i] = sun_month_id[d]
      last_month_change = d 
      last_moon_month = sun_month_id[d]
    elif(tithi_sunrise[d]==2 and tithi_sunrise[d-1]==30):
      #prathama tithi was never seen @ sunrise
      for i in range(last_month_change,d):
        #print '%%@Setting moon_month to sun_month_id, for i=%d:%d to %d (last month = %d)' %(last_month_change,d-1,sun_month_id[d],last_moon_month)
        if (sun_month_id[d-1]==last_moon_month):
          moon_month[i] = sun_month_id[d-1]%12 + 0.5
        else:
          moon_month[i] = sun_month_id[d-1]
      last_month_change = d 
      last_moon_month = sun_month_id[d-1]

  for i in range(last_month_change,367):
    moon_month[i]=sun_month_id[last_month_change-1]+1
    
  #for d in range(1,367):
    #jd = jd_start-1+d
    #[y,m,dt,t] = swisseph.revjul(jd)
    #print '%%#%02d-%02d-%4d: %3d:%s (sunrise tithi=%d) {%s}' % (dt,m,y,d,moon_month[d],tithi_sunrise[d],tithi_data_string[d])

  log_file=open('cal_log_%4d.txt' % year,'w')
  for d in range(1,367):
    jd = jd_start-1+d
    [y,m,dt,t] = swisseph.revjul(jd)
    log_data = '%02d-%02d-%4d\t[%3d]\tsun_rashi=%8.3f\ttithi=%8.3f\tsun_month=%2d\tmoon_month=%4.1f\n' % (dt,m,y,d,(longitude_sun_set[d]%360)/30.0,get_angam_float(jd_sunrise[d],12.0,[1,-1]),sun_month[d],moon_month[d])
    log_file.write(log_data)


  #PRINT CALENDAR

  for d in range(1,367):
    jd = jd_start-1+d
    [y,m,dt,t] = swisseph.revjul(jd)
    weekday = (weekday_start -1 + d)%7 

    ##################
    #Festival details#
    ##################

    ###--- MONTHLY VRATAMS ---###

    #EKADASHI Vratam
    if tithi_sunrise[d]==11 or tithi_sunrise[d]==12: #One of two consecutive tithis must appear @ sunrise!
      #check for shukla ekadashi
      if (tithi_sunrise[d]==11 and tithi_sunrise[d+1]==11): 
        festivals[d+1]=sarva[script]+'~'+get_ekadashi_name(paksha='shukla',month=moon_month[d],script=script)#moon_month[d] or [d+1]?
        if moon_month[d+1]==4:
          festivals[d+1]+='\\\\'+chaturmasya_start[script]
        if moon_month[d+1]==8:
          festivals[d+1]+='\\\\'+chaturmasya_end[script]
      elif (tithi_sunrise[d]==11 and tithi_sunrise[d+1]!=11): 
        #Check dashami end time to decide for whether this is sarva/smartha
        tithi_arunodayam = get_tithi(jd_sunrise[d]-(1/15.0)*(jd_sunrise[d]-jd_sunrise[d-1])) #Two muhurtams is 1/15 of day-length
        if tithi_arunodayam==10:
          festivals[d]=smartha[script]+'~'+get_ekadashi_name(paksha='shukla',month=moon_month[d],script=script)
          festivals[d+1]=vaishnava[script]+'~'+get_ekadashi_name(paksha='shukla',month=moon_month[d],script=script)
          if moon_month[d]==4:
            festivals[d]+='\\\\'+chaturmasya_start[script]
          if moon_month[d]==8:
            festivals[d]+='\\\\'+chaturmasya_end[script]
        else:
          festivals[d]=sarva[script]+'~'+get_ekadashi_name(paksha='shukla',month=moon_month[d],script=script)
          if moon_month[d]==4:
            festivals[d]+='\\\\'+chaturmasya_start[script]
          if moon_month[d]==8:
            festivals[d]+='\\\\'+chaturmasya_end[script]
      elif (tithi_sunrise[d-1]!=11 and tithi_sunrise[d]==12):
        festivals[d]=sarva[script]+'~'+get_ekadashi_name(paksha='shukla',month=moon_month[d],script=script)
        if moon_month[d]==4:
          festivals[d]+='\\\\'+chaturmasya_start[script]
        if moon_month[d]==8:
          festivals[d]+='\\\\'+chaturmasya_end[script]
 
    if tithi_sunrise[d]==26 or tithi_sunrise[d]==27: #One of two consecutive tithis must appear @ sunrise!
      #check for krishna ekadashi
      if (tithi_sunrise[d]==26 and tithi_sunrise[d+1]==26): 
        festivals[d+1]=sarva[script]+'~'+get_ekadashi_name(paksha='krishna',month=moon_month[d],script=script)#moon_month[d] or [d+1]?
      elif (tithi_sunrise[d]==26 and tithi_sunrise[d+1]!=26): 
        #Check dashami end time to decide for whether this is sarva/smartha
        tithi_arunodayam = get_tithi(jd_sunrise[d]-(1/15.0)*(jd_sunrise[d]-jd_sunrise[d-1])) #Two muhurtams is 1/15 of day-length
        if tithi_arunodayam==25:
          festivals[d]=smartha[script]+'~'+get_ekadashi_name(paksha='krishna',month=moon_month[d],script=script)
          festivals[d+1]=vaishnava[script]+'~'+get_ekadashi_name(paksha='krishna',month=moon_month[d],script=script)
        else:
          festivals[d]=sarva[script]+'~'+get_ekadashi_name(paksha='krishna',month=moon_month[d],script=script)
      elif (tithi_sunrise[d-1]!=26 and tithi_sunrise[d]==27):
        festivals[d]=sarva[script]+'~'+get_ekadashi_name(paksha='krishna',month=moon_month[d],script=script)

    #PRADOSHA Vratam
    if tithi_sunrise[d]==12 or tithi_sunrise[d]==13:
      ldiff_set=(swisseph.calc_ut(jd_sunset[d],swisseph.MOON)[0]-swisseph.calc_ut(jd_sunset[d],swisseph.SUN)[0])%360
      ldiff_set_tmrw=(swisseph.calc_ut(jd_sunset[d+1],swisseph.MOON)[0]-swisseph.calc_ut(jd_sunset[d+1],swisseph.SUN)[0])%360
      tithi_sunset = int(1+math.floor(ldiff_set/12.0))
      tithi_sunset_tmrw = int(1+math.floor(ldiff_set_tmrw/12.0))
      if tithi_sunset<=13 and tithi_sunset_tmrw!=13:
        festivals[d]=pradosham[script]
      elif tithi_sunset_tmrw==13:
        festivals[d+1]=pradosham[script]

    if tithi_sunrise[d]==27 or tithi_sunrise[d]==28:
      ldiff_set=(swisseph.calc_ut(jd_sunset[d],swisseph.MOON)[0]-swisseph.calc_ut(jd_sunset[d],swisseph.SUN)[0])%360
      ldiff_set_tmrw=(swisseph.calc_ut(jd_sunset[d+1],swisseph.MOON)[0]-swisseph.calc_ut(jd_sunset[d+1],swisseph.SUN)[0])%360
      tithi_sunset = int(1+math.floor(ldiff_set/12.0))
      tithi_sunset_tmrw = int(1+math.floor(ldiff_set_tmrw/12.0))
      if tithi_sunset<=28 and tithi_sunset_tmrw!=28:
        festivals[d]=pradosham[script]
      elif tithi_sunset_tmrw==28:
        festivals[d+1]=pradosham[script]

    #SANKATAHARA chaturthi
    if tithi_sunrise[d]==18 or tithi_sunrise[d]==19:
      ldiff_moonrise_yest=(swisseph.calc_ut(jd_moonrise[d-1],swisseph.MOON)[0]-swisseph.calc_ut(jd_moonrise[d-1],swisseph.SUN)[0])%360
      ldiff_moonrise=(swisseph.calc_ut(jd_moonrise[d],swisseph.MOON)[0]-swisseph.calc_ut(jd_moonrise[d],swisseph.SUN)[0])%360
      ldiff_moonrise_tmrw=(swisseph.calc_ut(jd_moonrise[d+1],swisseph.MOON)[0]-swisseph.calc_ut(jd_moonrise[d+1],swisseph.SUN)[0])%360
      tithi_moonrise_yest = int(1+math.floor(ldiff_moonrise_yest/12.0))
      tithi_moonrise = int(1+math.floor(ldiff_moonrise/12.0))
      tithi_moonrise_tmrw = int(1+math.floor(ldiff_moonrise_tmrw/12.0))

      if tithi_moonrise==19:
        if tithi_moonrise_yest!=19:#otherwise yesterday would have already been assigned
          festivals[d]=chaturthi[script] 
          if moon_month[d]==5:#shravana krishna chaturthi
            festivals[d]=maha[script]+festivals[d]
      elif tithi_moonrise_tmrw==19:
          festivals[d+1]=chaturthi[script] 
          if moon_month[d]==5: #moon_month[d] and[d+1] are same, so checking [d] is enough
            festivals[d+1]=maha[script]+festivals[d+1]

    #SHASHTHI Vratam
    if tithi_sunrise[d]==5 or tithi_sunrise[d]==6:
      if tithi_sunrise[d]==6 or (tithi_sunrise[d]==5 and tithi_sunrise[d+1]==7):
        if tithi_sunrise[d-1]!=6:#otherwise yesterday would have already been assigned
          festivals[d]=shashthi[script] 
          if moon_month[d]==8:#kArtika krishna shashthi
            festivals[d]=skanda[script]+festivals[d]
      elif tithi_sunrise[d+1]==6:
          festivals[d+1]=shashthi[script] 
          if moon_month[d]==8: #moon_month[d] and[d+1] are same, so checking [d] is enough
            festivals[d+1]=skanda[script]+festivals[d+1]

    ###--- OTHER (MAJOR) FESTIVALS ---###
    #type of month | month number | type of angam (tithi|nakshatram) | angam number | min_t cut off for considering prev day (without sunrise_angam) as festival date
    purvaviddha_rules={akshaya_tritiya[script]:['moon_month',2,'tithi',3,0],
    chitra_purnima[script]:['sun_month',1,'tithi',15,0],
    durgashtami[script]:['moon_month',7,'tithi',8,0],
    mahanavami[script]:['moon_month',7,'tithi',9,0],
    vijayadashami[script]:['moon_month',7,'tithi',10,0],
    dipavali[script]:['moon_month',7,'tithi',29,0],
    shankara_jayanti[script]:['moon_month',2,'tithi',5,0],
    yajur_upakarma[script]:['moon_month',5,'tithi',15,0],
    rg_upakarma[script]:['moon_month',5,'nakshatram',22,0],
    sama_upakarma[script]:['sun_month',5,'nakshatram',13,0],
    rishi_panchami[script]:['moon_month',6,'tithi',5,0],
    ananta_chaturdashi[script]:['moon_month',6,'tithi',14,0],
    mahalaya_paksham[script]:['moon_month',6,'tithi',16,0],
    hanumat_jayanti[script]:['sun_month',9,'tithi',30,0],
    ardra_darshanam[script]:['sun_month',9,'nakshatram',6,0],
    ratha_saptami[script]:['sun_month',10,'tithi',7,0],
    goda_jayanti[script]:['sun_month',4,'nakshatram',11,0],
    adi_krittika[script]:['sun_month',4,'nakshatram',3,0],
    phalguni_uttaram[script]:['sun_month',12,'nakshatram',12,4],
    mahalaya_amavasya[script]:['moon_month',6,'tithi',30,0],
    uma_maheshvara_vratam[script]:['moon_month',6,'tithi',15,0]}

    for x in iter(purvaviddha_rules.keys()):
      rule=purvaviddha_rules[x]
      if rule[0]=='moon_month':
        if moon_month[d]==rule[1]:
          if rule[2]=='tithi':
            fday = get_festival_day_purvaviddha(rule[3],tithi_sunrise,d,jd_sunrise[d],jd_sunrise[d+1],get_tithi,rule[4])
          elif rule[2]=='nakshatram':
            fday = get_festival_day_purvaviddha(rule[3],nakshatram_sunrise,d,jd_sunrise[d],jd_sunrise[d+1],get_nakshatram,rule[4])
          if fday is not None:
            if festival_day_list.has_key(x):
              if festival_day_list[x][0]!=fday:
                #Second occurrence of a festival within a Gregorian calendar year
                festival_day_list[x]=[festival_day_list[x][0],fday]
            else:
              festival_day_list[x]=[fday]
      elif rule[0]=='sun_month':
        if sun_month[d]==rule[1]:
          if rule[2]=='tithi':
            fday = get_festival_day_purvaviddha(rule[3],tithi_sunrise,d,jd_sunrise[d],jd_sunrise[d+1],get_tithi,rule[4])
          elif rule[2]=='nakshatram':
            fday = get_festival_day_purvaviddha(rule[3],nakshatram_sunrise,d,jd_sunrise[d],jd_sunrise[d+1],get_nakshatram,rule[4])
          if fday is not None:
            if festival_day_list.has_key(x):
              if festival_day_list[x][0]!=fday:
                #Second occurrence of a festival within a Gregorian calendar year
                festival_day_list[x]=[festival_day_list[x][0],fday]
            else:
              festival_day_list[x]=[fday]
      else:
        print 'Error; unknown string in rule: %s' % (rule[0])    
        return

    #NAVARATRI START
    if moon_month[d]==7 and moon_month[d-1]==6:
      festival_day_list[navaratri_start[script]]=[d]

    #PONGAL/AYANAM
    if sun_month[d]==10 and sun_month[d-1]==9:
      festival_day_list[uttarayanam[script]]=[d]

    if sun_month[d]==4 and sun_month[d-1]==3:
      festival_day_list[dakshinayanam[script]]=[d]

    if sun_month[d]==1 and sun_month[d-1]==12:
      festival_day_list[new_yr]=[d]

    if moon_month[d]==1 and moon_month[d-1]!=1:
      festival_day_list[yugadi[script]]=[d]

    #SHRIRAMANAVAMI
    if moon_month[d]==1:
      if tithi_sunrise[d]==8 or tithi_sunrise[d]==9:
        t_11 = get_tithi(jd_sunrise[d]+(jd_sunset[d]-jd_sunrise[d])*(2.0/5.0))#madhyahna1 start
        t_12 = get_tithi(jd_sunrise[d]+(jd_sunset[d]-jd_sunrise[d])*(3.0/5.0))#madhyahna1 end 
        t_21 = get_tithi(jd_sunrise[d+1]+(jd_sunset[d+1]-jd_sunrise[d+1])*(2.0/5.0))#madhyahna2 start
        t_22 = get_tithi(jd_sunrise[d+1]+(jd_sunset[d+1]-jd_sunrise[d+1])*(3.0/5.0))#madhyahna2 end
        if t_11==9 or t_12==9:
          if t_21==9 or t_22==9:
            festival_day_list[ramanavami[script]]=[d+1]
          else:
            festival_day_list[ramanavami[script]]=[d]
 
    #JANMASHTAMI
    if moon_month[d]==5:
      if tithi_sunrise[d]==22 or tithi_sunrise[d]==23:
        t_11 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(7.0/15.0))#nishita1 start
        t_12 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(8.0/15.0))#nishita1 end
        #t_11 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(2.0/5.0))#madhyaratri1 start
        #t_12 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(3.0/5.0))#madhyaratri1 end
        t_21 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(7.0/15.0))#nishita2 start
        t_22 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(8.0/15.0))#nishita2 end
        #t_21 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(2.0/5.0))#madhyaratri2 start
        #t_22 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(3.0/5.0))#madhyaratri2 end
        if t_11==23 or t_12==23:
          if t_21==23 or t_22==23:
            festival_day_list[janmashtami[script]]=[d+1]
          else:
            festival_day_list[janmashtami[script]]=[d]

    #SHIVARATRI
    if moon_month[d]==11:
      if tithi_sunrise[d]==28 or tithi_sunrise[d]==29:
        t_11 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(7.0/15.0))#nishita1 start
        t_12 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(8.0/15.0))#nishita1 end
        t_21 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(7.0/15.0))#nishita2 start
        t_22 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(8.0/15.0))#nishita2 end
        if t_11==29 or t_12==29:
          if t_21==29 or t_22==29:
            festival_day_list[shivaratri[script]]=[d+1]
          else:
            festival_day_list[shivaratri[script]]=[d]

    #VINAYAKA CHATURTHI
    if moon_month[d]==6:
      if tithi_sunrise[d]==3 or tithi_sunrise[d]==4:
        t_11 = get_tithi(jd_sunrise[d]+(jd_sunset[d]-jd_sunrise[d])*(2.0/5.0))#madhyahna1 start
        t_12 = get_tithi(jd_sunrise[d]+(jd_sunset[d]-jd_sunrise[d])*(3.0/5.0))#madhyahna1 end 
        t_21 = get_tithi(jd_sunrise[d+1]+(jd_sunset[d+1]-jd_sunrise[d+1])*(2.0/5.0))#madhyahna2 start
        t_22 = get_tithi(jd_sunrise[d+1]+(jd_sunset[d+1]-jd_sunrise[d+1])*(3.0/5.0))#madhyahna2 end
        if t_11==4 or t_12==4:
          if t_21==4 or t_22==4:
            festival_day_list[vchaturthi[script]]=[d+1]
          else:
            festival_day_list[vchaturthi[script]]=[d]

  #Add saved festivals
  festival_day_list[gayatri_japam[script]]=[festival_day_list[yajur_upakarma[script]][0]+1]
  festival_day_list[varalakshmi_vratam[script]]=[festival_day_list[yajur_upakarma[script]][0]-((weekday_start-1+festival_day_list[yajur_upakarma[script]][0]-5)%7)]

  for x in iter(festival_day_list.keys()):
    for j in range(0,len(festival_day_list[x])):
      if festivals[festival_day_list[x][j]]!='':
        festivals[festival_day_list[x][j]]+='\\\\'
      festivals[festival_day_list[x][j]]+=x



  ###--- ECLIPSES ---###
  ###--- LUNAR ECLIPSES ---###
  swisseph.set_topo(lon=longitude,lat=latitude,alt=0.0) #Set location
  jd = jd_start
  while 1:
    next_ecl_lun=swisseph.lun_eclipse_when(jd)
    jd=next_ecl_lun[1][0]+(tz_off/24.0)
    jd_ecl_lun_start=next_ecl_lun[1][2]+(tz_off/24.0)
    jd_ecl_lun_end=next_ecl_lun[1][3]+(tz_off/24.0)
    ecl_y=swisseph.revjul(jd-1)[0]# -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
    if ecl_y!=start_year:
      break
    else:
      ecl_lun_start = swisseph.revjul(jd_ecl_lun_start)[3]
      ecl_lun_end   = swisseph.revjul(jd_ecl_lun_end)[3]
      if (jd_ecl_lun_start-(tz_off/24.0))==0.0 or (jd_ecl_lun_end-(tz_off/24.0))==0.0:
        jd=jd+20 #Move towards the next eclipse... at least the next full moon (>=25 days away)
        continue
      fday=int(math.floor(jd_ecl_lun_start)-math.floor(jd_start)+1)
      #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1]
      if (jd<(jd_sunrise[fday]+tz_off/24.0)):
        fday-=1
      if ecl_lun_start<swisseph.revjul(jd_sunrise[fday+1]+tz_off/24.0)[3]:
        ecl_lun_start+=24
      #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1],ecl_lun_start, ecl_lun_end
      jd_moonrise_ecl_day=swisseph.rise_trans(jd_start=jd_sunrise[fday],body=swisseph.MOON,
        lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]+(tz_off/24.0)
      jd_moonset_ecl_day=swisseph.rise_trans(jd_start=jd_moonrise_ecl_day,body=swisseph.MOON,
        lon=longitude,lat=latitude,rsmi=swisseph.CALC_SET|swisseph.BIT_DISC_CENTER)[1][0]+(tz_off/24.0)
      #if jd_ecl_lun_start<(jd_sunrise[fday]+(tz_off/24.0)):
      if ecl_lun_end < ecl_lun_start:
        ecl_lun_end+=24
      #print '%%', (jd_ecl_lun_start), (jd_ecl_lun_end), (jd_moonrise_ecl_day), (jd_moonset_ecl_day)
      #print '%%', swisseph.revjul(jd_ecl_lun_start), swisseph.revjul(jd_ecl_lun_end), swisseph.revjul(jd_moonrise_ecl_day), swisseph.revjul(jd_moonset_ecl_day)
      if jd_ecl_lun_end<jd_moonrise_ecl_day or jd_ecl_lun_start>jd_moonset_ecl_day:
        jd=jd+20 #Move towards the next eclipse... at least the next full moon (>=25 days away)
        continue
      lun_ecl_str = chandra_grahanam[script]+'~\\textsf{'+print_time2(ecl_lun_start)+'}{\\RIGHTarrow}\\textsf{'+print_time2(ecl_lun_end)+'}'
      if festivals[fday]!='':
        festivals[fday]+='\\\\'
      festivals[fday]+=lun_ecl_str
    jd=jd+20
      
  ###--- SOLAR ECLIPSES ---###
  swisseph.set_topo(lon=longitude,lat=latitude,alt=0.0) #Set location
  jd = jd_start
  while 1:
    next_ecl_sol=swisseph.sol_eclipse_when_loc(julday=jd,lon=longitude,lat=latitude)
    jd=next_ecl_sol[1][0]+(tz_off/24.0)
    jd_ecl_sol_start=next_ecl_sol[1][1]+(tz_off/24.0)
    jd_ecl_sol_end=next_ecl_sol[1][4]+(tz_off/24.0)
    ecl_y=swisseph.revjul(jd-1)[0]# -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
    if ecl_y!=start_year:
      break
    else:
      #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
      #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
      fday=int(math.floor(jd)-math.floor(jd_start)+1)
      if (jd<(jd_sunrise[fday]+tz_off/24.0)):
        fday-=1
      #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
      #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
      ecl_sol_start = swisseph.revjul(jd_ecl_sol_start)[3]
      ecl_sol_end   = swisseph.revjul(jd_ecl_sol_end)[3]
      if (jd_ecl_sol_start-(tz_off/24.0))==0.0 or (jd_ecl_sol_end-(tz_off/24.0))==0.0:# or jd_ecl_end<jd_sunrise[fday] or jd_ecl_start>jd_sunset[fday]:
        jd=jd+20 #Move towards the next eclipse... at least the next new moon (>=25 days away)
        continue
      if ecl_sol_end < ecl_sol_start:
        ecl_sol_end+=24
      sol_ecl_str = surya_grahanam[script]+'~\\textsf{'+print_time2(ecl_sol_start)+'}{\\RIGHTarrow}\\textsf{'+print_time2(ecl_sol_end)+'}'
      if festivals[fday]!='':
        festivals[fday]+='\\\\'
      festivals[fday]+=sol_ecl_str
    jd=jd+20
  ###--- FESTIVAL ADDITIONS COMPLETE ---###

  ###--- PRINT LIST OF FESTIVALS (Page 2) ---###
  if script=='en':
    cal = Calendar()

  print '\\newpage'
  print '\\centerline {\\LARGE {{%s}}}\\mbox{}\\\\[2cm]' % list_of_festivals[script]
  print '\\begin{center}'
  print '\\begin{minipage}[t]{0.3\\linewidth}'
  print '\\begin{center}'
  print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}cp{6cm}}'

  mlast=1
  for d in range(1,367):
    jd = jd_start-1+d
    [y,m,dt,t] = swisseph.revjul(jd)
    weekday = (weekday_start -1 + d)%7 
   
    if festivals[d]!='':
      if m!=mlast:
        mlast=m
        #print '\\hline\\\\'
        print '\\\\'
        if m==5 or m==9:
          print '\\end{tabular}'
          print '\\end{center}'
          print '\\end{minipage}\hspace{1cm}%'
          print '\\begin{minipage}[t]{0.3\\linewidth}'
          print '\\begin{center}'
          print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}l>{\\sffamily}cp{6cm}}'
          
      print '%s & %s & %s & {\\raggedright %s} \\\\' % (MON[m],dt,WDAY[weekday],festivals[d])

      if script=='en':
        event = Event()
        event.add('summary',festivals[d])
        event.add('dtstart',datetime(y,m,dt))
        event.add('dtend',datetime(y,m,dt))
        cal.add_component(event)

    if m==12 and dt==31:
      break

  print '\\end{tabular}'
  print '\\end{center}'
  print '\\end{minipage}'
  print '\\end{center}'
  print '\\clearpage'

  if script=='en':
    cal_fname = '%s-%4d.ics' %(city_name,start_year)
    cal_file = open(cal_fname,'w')
    cal_file.write(cal.as_string())
    cal_file.close()

  #Layout calendar in LATeX format
  #We use a separate loop here, because of festivals like varalakshmi
  #vratam, for which we backtrack to the previous friday from yajur
  #upakarma and change the list of festivals!

  for d in range(1,367):
    jd = jd_start-1+d
    [y,m,dt,t] = swisseph.revjul(jd)
    weekday = (weekday_start -1 + d)%7 

    if dt==1:
      if m>1:
        if weekday!=0: #Space till Sunday
          for i in range(weekday,6):
            print "{}  &"
          print "\\\\ \hline"
        print '\end{tabular}'
        print '\n\n'
  
      #Begin tabular
      print '\\begin{tabular}{|c|c|c|c|c|c|c|}'
      print '\multicolumn{7}{c}{\Large \\bfseries \sffamily %s %s}\\\\[3mm]' % (month[m],y)
      print '\hline'
      print '\\textbf{\\textsf{SUN}} & \\textbf{\\textsf{MON}} & \\textbf{\\textsf{TUE}} & \\textbf{\\textsf{WED}} & \\textbf{\\textsf{THU}} & \\textbf{\\textsf{FRI}} & \\textbf{\\textsf{SAT}} \\\\ \hline'
      #print '\\textbf{भानु} & \\textbf{इन्दु} & \\textbf{भौम} & \\textbf{बुध} & \\textbf{गुरु} & \\textbf{भृगु} & \\textbf{स्थिर} \\\\ \hline'
  
      #Blanks for previous weekdays
      for i in range(0,weekday):
        print "{}  &"

    print '\caldata{\\textcolor{%s}{%s}}{%s{%s}}{\\sundata{%s}{%s}{%s}}{\\tnyk{%s}{%s}{%s}{%s}}{\\rahuyama{%s}{%s}}{%s} ' % (daycol[weekday],
      dt,month_data[d],get_chandra_masa(moon_month[d],chandra_masa_names,script),sunrise[d],sunset[d],madhya[d],tithi_data_string[d],nakshatram_data_string[d],
      yogam_data_string[d],karanam_data_string[d],rahu[d],yama[d],festivals[d])
  
    if weekday==6:
      print "\\\\ \hline"
    else:
      print "&"
  
    if m==12 and dt==31:
      break
  
    # For debugging specific dates
    #if m==4 and dt==10:
    #  break
  
  for i in range(weekday+1,6):
    print "{}  &"
  if weekday!=6:
    print "\\\\ \hline"
  print '\end{tabular}'
  print '\n\n'
  
  print template_lines[-2][:-1]
  print template_lines[-1][:-1]
Example #36
0
Date = struct('Date', ['year', 'month', 'day'])
Place = struct('Place', ['latitude', 'longitude', 'timezone'])

sidereal_year = 365.256360417   # From WolframAlpha

# Hindu sunrise/sunset is calculated w.r.t middle of the sun's disk
# They are geomretic, i.e. "true sunrise/set", so refraction is not considered
_rise_flags = swe.BIT_DISC_CENTER + swe.BIT_NO_REFRACTION

# namah suryaya chandraya mangalaya ... rahuve ketuve namah
swe.KETU = swe.PLUTO  # I've mapped Pluto to Ketu
planet_list = [swe.SUN, swe.MOON, swe.MARS, swe.MERCURY, swe.JUPITER,
               swe.VENUS, swe.SATURN, swe.MEAN_NODE, # Rahu = MEAN_NODE
               swe.KETU, swe.URANUS, swe.NEPTUNE ]

revati_359_50 = lambda: swe.set_sid_mode(swe.SIDM_USER, 1926892.343164331, 0)
galc_cent_mid_mula = lambda: swe.set_sid_mode(swe.SIDM_USER, 1922011.128853056, 0)

set_ayanamsa_mode = lambda: swe.set_sid_mode(swe.SIDM_LAHIRI)
reset_ayanamsa_mode = lambda: swe.set_sid_mode(swe.SIDM_FAGAN_BRADLEY)

# Temporary function
def get_planet_name(planet):
  names = { swe.SURYA: 'Surya', swe.CHANDRA: 'Candra', swe.KUJA: 'Mangala',
            swe.BUDHA: 'Budha', swe.GURU: 'Guru', swe.SUKRA: 'Sukra',
            swe.SANI: 'Sani', swe.RAHU: 'Rahu', swe.KETU: 'Ketu', swe.PLUTO: 'Ketu'}
  return names[planet]

# Convert 23d 30' 30" to 23.508333 degrees
from_dms = lambda degs, mins, secs: degs + mins/60 + secs/3600
def main():
  city_name = sys.argv[1]
  latitude = sexastr2deci(sys.argv[2])
  longitude = sexastr2deci(sys.argv[3])
  tz = sys.argv[4]
  
  start_year = int(sys.argv[5])
  year = start_year
  jd=swisseph.julday(year,1,1,0)
  jd_start=jd
  start_date = datetime(year=year,month=1,day=1,hour=0,minute=0,second=0)
  
  day_of_year=0
  
  swisseph.set_sid_mode(swisseph.SIDM_LAHIRI) #Force Lahiri Ayanamsha
  
  sun_month_day = jd-get_last_dhanur_transit(jd,latitude,longitude)
  #this has to be done in a generic fashion, by scanning for the transit into dhanur of the last year!
  
  month_start_after_set = 0
  
  template_file=open('cal_template_compre.tex')
  template_lines=template_file.readlines()
  for i in range(0,len(template_lines)-3):
    print template_lines[i][:-1]
  
  samvatsara_id = (year - 1568)%60 + 1; #distance from prabhava
  samvatsara_names = '%s–%s' % (year_names[samvatsara_id], year_names[(samvatsara_id%60)+1])
  
  print '\\mbox{}'
  print '{\\font\\x="Warnock Pro" at 60 pt\\x %d\\\\[0.3cm]}' % year
  print '\\mbox{\\font\\x="Sanskrit 2003:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names
  print '{\\font\\x="Warnock Pro" at 48 pt\\x \\uppercase{%s}\\\\[0.3cm]}' % city_name
  print '\hrule'
  
  while year<=start_year:

    day_of_year = day_of_year + 1  
  
    [y,m,d,t] = swisseph.revjul(jd)
    weekday = (swisseph.day_of_week(jd) + 1)%7 #swisseph has Mon = 0, non-intuitively!
  
    local_time = pytz.timezone(tz).localize(datetime(y,m, d, 6, 0, 0)) #checking @ 6am local - can we do any better?
    tz_off=datetime.utcoffset(local_time).seconds/3600.0 #compute offset from UTC
  
    jd_rise=swisseph.rise_trans(jd_start=jd,body=swisseph.SUN,lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
    jd_rise_tmrw=swisseph.rise_trans(jd_start=jd+1,body=swisseph.SUN,lon=longitude,lat=latitude,rsmi=swisseph.CALC_RISE|swisseph.BIT_DISC_CENTER)[1][0]
    jd_set =swisseph.rise_trans(jd_start=jd,body=swisseph.SUN,lon=longitude,lat=latitude,rsmi=swisseph.CALC_SET|swisseph.BIT_DISC_CENTER)[1][0]
  
    [_y,_m,_d, t_rise]=swisseph.revjul(jd_rise+tz_off/24.0)
    [_y,_m,_d, t_set]=swisseph.revjul(jd_set+tz_off/24.0)
  
    longitude_moon=swisseph.calc_ut(jd_rise,swisseph.MOON)[0]-swisseph.get_ayanamsa(jd_rise)
    longitude_moon_tmrw=swisseph.calc_ut(jd_rise+1,swisseph.MOON)[0]-swisseph.get_ayanamsa(jd_rise+1)
  
    longitude_sun=swisseph.calc_ut(jd_rise,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_rise)
    longitude_sun_set=swisseph.calc_ut(jd_set,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_set)
    sun_month_rise = masa_names[int(1+math.floor(((longitude_sun)%360)/30.0))]
    sun_month = masa_names[int(1+math.floor(((longitude_sun_set)%360)/30.0))]
    longitude_sun_tmrw=swisseph.calc_ut(jd_rise+1,swisseph.SUN)[0]-swisseph.get_ayanamsa(jd_rise+1)
    sun_month_tmrw = masa_names[int(1+math.floor(((longitude_sun_tmrw)%360)/30.0))]
  
    daily_motion_moon = (longitude_moon_tmrw-longitude_moon)%360
    daily_motion_sun = (longitude_sun_tmrw-longitude_sun)%360
  
    #Solar month calculations
    if month_start_after_set==1:
      sun_month_day = 0
      month_start_after_set = 0
  
    if sun_month_rise!=sun_month_tmrw:
      if sun_month!=sun_month_tmrw:
        month_start_after_set=1
        sun_month_day = sun_month_day + 1
      #mAsa pirappu!
      #sun_month = sun_month_tmrw #sun moves into next rAsi before sunset -- check rules!
      else:
        sun_month_day = 1
      month_remaining = 30-(longitude_sun%30.0)
      month_end = month_remaining/daily_motion_sun*24.0
      me = deci2sexa(t_rise+month_end)
      if me[0]>=24:
        suff='(+1)'
        me[0] = me[0] - 24
      else:
        suff='\\hspace{2ex}'
      sun_month_end_time = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %02d:%02d%s}' % (last_sun_month,me[0],me[1],suff)
    else:
      sun_month_day = sun_month_day + 1
      sun_month_end_time = ''
    
    month_data = '\\sunmonth{%s}{%d}{%s}' % (sun_month,sun_month_day,sun_month_end_time)
  
    #Compute tithi details
    tithi = int(1+math.floor((longitude_moon-longitude_sun)%360 / 12.0))
    tithi_tmrw = int(1+math.floor((longitude_moon_tmrw-longitude_sun_tmrw)%360 / 12.0))

    if (tithi_tmrw-tithi)%30 > 1:
      #double change
      tithi_2=(tithi%30)+1
      if tithi_2%15 != 0:
        paksha = (paksha_names['shukla'] if tithi_2<15 else paksha_names['krishna'])
      else:
        if tithi_2 == 15:
          paksha = '\\fullmoon'
        elif tithi_2 == 30:
          paksha = '\\newmoon'
    
      if tithi_2%15 == 0:
        tithi_str_2 = paksha + tithi_names[tithi_2]
      else:
        tithi_str_2 = paksha + tithi_names[tithi_2%15]
      
      tithi_remaining_2 = 12+12-(((longitude_moon-longitude_sun)%360)%12)
      tithi_end_2 = tithi_remaining_2/(daily_motion_moon-daily_motion_sun)*24.0
      tithi_end_str_2 = print_end_time(tithi_end_2,jd_rise_tmrw-jd_rise,t_rise)
      if tithi_end_str_2 == '\\textsf{अहोरात्रम्}':
        #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
        #the second tithi cannot be 'all day'! It's ending will reflect in tomorrow's calendar
        tithi_str_2 = ''
        tithi_end_str_2 = ''
    else:
     tithi_str_2 = ''
     tithi_end_str_2 = ''
    
    if tithi%15 != 0:
      paksha = (paksha_names['shukla'] if tithi<15 else paksha_names['krishna'])
    else:
      if tithi == 15:
        paksha = '\\fullmoon'
      elif tithi == 30:
        paksha = '\\newmoon'
  
    if tithi%15 == 0:
      tithi_str = paksha + tithi_names[tithi]
    else:
      tithi_str = paksha + tithi_names[tithi%15]
    
    tithi_remaining = 12-(((longitude_moon-longitude_sun)%360)%12)
    tithi_end = tithi_remaining/(daily_motion_moon-daily_motion_sun)*24.0
    tithi_end_str = print_end_time(tithi_end,jd_rise_tmrw-jd_rise,t_rise)
  
    #Compute nakshatram details
    n_id = int(1+math.floor((longitude_moon%360) /(360.0/27)))
    n_id_tmrw = int(1+math.floor((longitude_moon_tmrw%360) /(360.0/27)))
    if (n_id_tmrw-n_id)%27 > 1:
      #there is a double change
      nakshatram_str_2 = nakshatra_names[n_id%27+1]
      nakshatram_remaining_2 = (360.0/27)+(360.0/27) - ((longitude_moon%360) % (360.0/27))
      nakshatram_end_2 = nakshatram_remaining_2/daily_motion_moon*24
      nakshatram_end_str_2 = print_end_time(nakshatram_end_2,jd_rise_tmrw-jd_rise,t_rise)
      if nakshatram_end_str_2 == '\\textsf{अहोरात्रम्}':
        #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
        #the second nakshatram cannot be 'all day'! It's ending will reflect in tomorrow's calendar
        nakshatram_str_2 = ''
        nakshatram_end_str_2 = ''
    else:
      nakshatram_str_2 = ''
      nakshatram_end_str_2 = ''
    
    nakshatram_str = nakshatra_names[n_id]
    nakshatram_remaining = (360.0/27) - ((longitude_moon%360) % (360.0/27))
    nakshatram_end = nakshatram_remaining/daily_motion_moon*24
    nakshatram_end_str = print_end_time(nakshatram_end,jd_rise_tmrw-jd_rise,t_rise)
   
    #Compute karanam details
    karanam = int(1+math.floor((longitude_moon-longitude_sun)%360 / 6.0))
    karanam_tmrw = int(1+math.floor((longitude_moon_tmrw-longitude_sun_tmrw)%360 / 6.0))

#    There cannot be more than 3 karanams in a day, because total arc ~ 12 deg and per yogam is 6 deg

    if (karanam_tmrw-karanam)%60 > 2:
      #triple change
      karanam_3=((karanam+1)%60)+1
      karanam_str_3 = karanam_names[karanam_3]
      
      karanam_remaining_3 = 6*2+6-(((longitude_moon-longitude_sun)%360)%6)
      karanam_end_3 = karanam_remaining_3/(daily_motion_moon-daily_motion_sun)*24.0
      karanam_end_str_3 = print_end_time(karanam_end_3,jd_rise_tmrw-jd_rise,t_rise)
      if karanam_end_str_3 == '\\textsf{अहोरात्रम्}':
        #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
        #the second karanam cannot be 'all day'! It's ending will reflect in tomorrow's calendar
        karanam_str_3 = ''
        karanam_end_str_3 = ''
    else:
     karanam_str_3 = ''
     karanam_end_str_3 = ''

    if (karanam_tmrw-karanam)%60 > 1:
      #double change
      karanam_2=(karanam%60)+1
      karanam_str_2 = karanam_names[karanam_2]
      
      karanam_remaining_2 = 6+6-(((longitude_moon-longitude_sun)%360)%6)
      karanam_end_2 = karanam_remaining_2/(daily_motion_moon-daily_motion_sun)*24.0
      karanam_end_str_2 = print_end_time(karanam_end_2,jd_rise_tmrw-jd_rise,t_rise)
      if karanam_end_str_2 == '\\textsf{अहोरात्रम्}':
        #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
        #the second karanam cannot be 'all day'! It's ending will reflect in tomorrow's calendar
        karanam_str_2 = ''
        karanam_end_str_2 = ''
    else:
     karanam_str_2 = ''
     karanam_end_str_2 = ''
    
    karanam_str = karanam_names[karanam]
    
    karanam_remaining = 6-(((longitude_moon-longitude_sun)%6)%6)
    karanam_end = karanam_remaining/(daily_motion_moon-daily_motion_sun)*24.0
    karanam_end_str = print_end_time(karanam_end,jd_rise_tmrw-jd_rise,t_rise)

    #Compute yogam details
    yogam = int(1+math.floor((longitude_moon+longitude_sun)%360 / (360.0/27.0)))
    yogam_tmrw = int(1+math.floor((longitude_moon_tmrw+longitude_sun_tmrw)%360 / (360.0/27.0)))

    #There cannot be more than 2 yogams in a day, because total arc = 13 deg and per yogam is 13.333 deg

    if (yogam_tmrw-yogam)%27 > 1:
      #double change
      yogam_2=(yogam%27)+1
      yogam_str_2 = yogam_names[yogam_2]
      
      yogam_remaining_2 = 2.0*(360.0/27.0)-(((longitude_moon+longitude_sun)%360)%(360.0/27.0))
      yogam_end_2 = yogam_remaining_2/(daily_motion_moon+daily_motion_sun)*24.0
      yogam_end_str_2 = print_end_time(yogam_end_2,jd_rise_tmrw-jd_rise,t_rise)
      if yogam_end_str_2 == '\\textsf{अहोरात्रम्}':
        #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
        #the second yogam cannot be 'all day'! It's ending will reflect in tomorrow's calendar
        yogam_str_2 = ''
        yogam_end_str_2 = ''
    else:
     yogam_str_2 = ''
     yogam_end_str_2 = ''
    
    yogam_str = yogam_names[yogam]
    
    yogam_remaining = (360.0/27.0)-(((longitude_moon+longitude_sun)%360)%(360.0/27.0))
    yogam_end = yogam_remaining/(daily_motion_moon+daily_motion_sun)*24.0
    yogam_end_str = print_end_time(yogam_end,jd_rise_tmrw-jd_rise,t_rise)

    #Sunrise/sunset and related stuff (like rahu, yama)
    [rh, rm, rs] = deci2sexa(t_rise) #rise_t hour, rise minute
    [sh, sm, ss] = deci2sexa(t_set) #set_t hour, set minute
  
    present_day = start_date + timedelta(days=day_of_year)
    rise_t = present_day + timedelta(hours=rh,minutes=rm)
    set_t = present_day + timedelta(hours=sh,minutes=sm)
  
    length_of_day = set_t-rise_t
    yamakandam_start = rise_t + timedelta(seconds=(1/8.0)*(yamakandam_octets[weekday]-1)*length_of_day.seconds)
    yamakandam_end = yamakandam_start + timedelta(seconds=(1/8.0)*length_of_day.seconds)
    rahukalam_start = rise_t + timedelta(seconds=(1/8.0)*(rahukalam_octets[weekday]-1)*length_of_day.seconds)
    rahukalam_end = rahukalam_start + timedelta(seconds=(1/8.0)*length_of_day.seconds)
    madhyahnikam_start = rise_t + timedelta(seconds=(1/5.0)*length_of_day.seconds)
  
    rise = '%02d:%02d' % (rh,rm)
    set = '%02d:%02d' % (sh,sm)
    madhya = print_time(madhyahnikam_start)
    rahu = '%s--%s' % (print_time(rahukalam_start), print_time(rahukalam_end))
    yama = '%s--%s' % (print_time(yamakandam_start),print_time(yamakandam_end))
    
    if nakshatram_end_str_2!='':
      nakshatram_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (nakshatram_str,nakshatram_end_str,nakshatram_str_2,nakshatram_end_str_2)
    else:
      nakshatram_data_string = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (nakshatram_str,nakshatram_end_str)

    if tithi_end_str_2!='':
      tithi_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (tithi_str,tithi_end_str,tithi_str_2,tithi_end_str_2)
    else:
      tithi_data_string = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (tithi_str,tithi_end_str)

    if karanam_end_str_3!='':
      karanam_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\\\\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (karanam_str,karanam_end_str,karanam_str_2,karanam_end_str_2,karanam_str_3,karanam_end_str_3)
    elif karanam_end_str_2!='':
      karanam_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (karanam_str,karanam_end_str,karanam_str_2,karanam_end_str_2)
    else:
      karanam_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (karanam_str,karanam_end_str)

    if yogam_end_str_2!='':
      yogam_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (yogam_str,yogam_end_str,yogam_str_2,yogam_end_str_2)
    else:
      yogam_data_string = '\\mbox{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (yogam_str,yogam_end_str)

    #Layout calendar in LATeX format
    if d==1:
      if m>1:
        if weekday!=0: #Space till Sunday
          for i in range(weekday,6):
            print "{}  &"
          print "\\\\ \hline"
        print '\end{tabular}'
        print '\n\n'
  
      #Begin tabular
      print '\\begin{tabular}{|c|c|c|c|c|c|c|}'
      print '\multicolumn{7}{c}{\Large \\bfseries %s %s}\\\\[3mm]' % (month[m],y)
      print '\hline'
      print '\\textbf{SUN} & \\textbf{MON} & \\textbf{TUE} & \\textbf{WED} & \\textbf{THU} & \\textbf{FRI} & \\textbf{SAT} \\\\ \hline'
      #print '\\textbf{भानु} & \\textbf{इन्दु} & \\textbf{भौम} & \\textbf{बुध} & \\textbf{गुरु} & \\textbf{भृगु} & \\textbf{स्थिर} \\\\ \hline'
  
      #Blanks for previous weekdays
      for i in range(0,weekday):
        print "{}  &"

    print '\caldata{\\textcolor{%s}{%s}}{%s}{\\sundata{%s}{%s}{%s}}{\\tnyk{%s}{%s}{%s}{%s}}{\\textsf{राहु}~%s~~\\textsf{यम}~%s} ' % (daycol[weekday],d,month_data,rise,set,madhya,tithi_data_string,nakshatram_data_string,yogam_data_string,karanam_data_string,rahu,yama)
  
    if weekday==6:
      print "\\\\ \hline"
    else:
      print "&"
  
    jd = jd + 1

    last_sun_month = sun_month

    if m==12 and d==31:
      year = year + 1
  
    # For debugging specific dates
    #if m==4 and d==10:
    #  break
  
  for i in range(weekday+1,6):
    print "{}  &"
  if weekday!=6:
    print "\\\\ \hline"
  print '\end{tabular}'
  print '\n\n'
  
  print template_lines[-2][:-1]
  print template_lines[-1][:-1]
def main():
    city_name = sys.argv[1]
    latitude = sexastr2deci(sys.argv[2])
    longitude = sexastr2deci(sys.argv[3])
    tz = sys.argv[4]

    start_year = int(sys.argv[5])
    year = start_year
    jd = swisseph.julday(year, 1, 1, 0)
    jd_start = jd

    if len(sys.argv) == 7:
        script = sys.argv[6]
    else:
        script = 'deva'  #Default script is devanagari

    swisseph.set_sid_mode(swisseph.SIDM_LAHIRI)  #Force Lahiri Ayanamsha

    sun_month_day = jd - get_last_dhanur_transit(jd, latitude, longitude)

    month_start_after_set = 0

    template_file = open('cal_template_compre.tex')
    template_lines = template_file.readlines()
    for i in range(0, len(template_lines) - 3):
        print template_lines[i][:-1]

    samvatsara_id = (year - 1568) % 60 + 1
    #distance from prabhava
    samvatsara_names = '%s–%s' % (year_names[script][samvatsara_id],
                                  year_names[script][(samvatsara_id % 60) + 1])
    new_yr = mesha_sankranti[script] + '~(' + year_names[script][
        (samvatsara_id % 60) + 1] + '-' + samvatsara[script] + ')'

    print '\\mbox{}'
    print '{\\font\\x="Candara" at 60 pt\\x %d\\\\[0.5cm]}' % year
    print '\\mbox{\\font\\x="Sanskrit 2003:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names
    print '{\\font\\x="Candara" at 48 pt\\x \\uppercase{%s}\\\\[0.5cm]}' % city_name
    print '\hrule'

    #INITIALISE VARIABLES
    jd_sunrise = [None] * 368
    jd_sunset = [None] * 368
    jd_moonrise = [None] * 368
    longitude_moon = [None] * 368
    longitude_sun = [None] * 368
    longitude_sun_set = [None] * 368
    sun_month_id = [None] * 368
    sun_month = [None] * 368
    sun_month_rise = [None] * 368
    moon_month = [None] * 368
    month_data = [None] * 368
    tithi_data_string = [None] * 368
    tithi_sunrise = [None] * 368
    nakshatram_data_string = [None] * 368
    nakshatram_sunrise = [None] * 368
    karanam_data_string = [None] * 368
    karanam_sunrise = [None] * 368
    yogam_data_string = [None] * 368
    yogam_sunrise = [None] * 368
    weekday = [None] * 368
    sunrise = [None] * 368
    sunset = [None] * 368
    madhya = [None] * 368
    rahu = [None] * 368
    yama = [None] * 368
    festival_day_list = {}
    festivals = [''] * 368

    weekday_start = swisseph.day_of_week(jd) + 1
    #swisseph has Mon = 0, non-intuitively!

    ##################################################
    #Compute all parameters -- latitude/longitude etc#
    ##################################################

    for d in range(-1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        local_time = pytz.timezone(tz).localize(datetime(y, m, dt, 6, 0, 0))
        #checking @ 6am local - can we do any better?
        tz_off = datetime.utcoffset(local_time).seconds / 3600.0
        #compute offset from UTC

        jd_sunrise[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.SUN,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_RISE | swisseph.BIT_DISC_CENTER)[1][0]
        jd_sunset[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.SUN,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_SET | swisseph.BIT_DISC_CENTER)[1][0]
        jd_moonrise[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.MOON,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_RISE | swisseph.BIT_DISC_CENTER)[1][0]

        longitude_sun[d + 1] = swisseph.calc_ut(
            jd_sunrise[d + 1], swisseph.SUN)[0] - swisseph.get_ayanamsa(
                jd_sunrise[d + 1])
        longitude_moon[d + 1] = swisseph.calc_ut(
            jd_sunrise[d + 1], swisseph.MOON)[0] - swisseph.get_ayanamsa(
                jd_sunrise[d + 1])
        longitude_sun_set[d + 1] = swisseph.calc_ut(
            jd_sunset[d + 1], swisseph.SUN)[0] - swisseph.get_ayanamsa(
                jd_sunset[d + 1])

        sun_month_id[d + 1] = int(1 + math.floor((
            (longitude_sun_set[d + 1]) % 360) / 30.0))
        sun_month[d + 1] = int(1 + math.floor((
            (longitude_sun_set[d + 1]) % 360) / 30.0))

        sun_month_rise[d + 1] = int(1 + math.floor((
            (longitude_sun[d + 1]) % 360) / 30.0))

        if (d <= 0):
            continue

        t_sunrise = (jd_sunrise[d] - jd) * 24.0 + tz_off
        t_sunset = (jd_sunset[d] - jd) * 24.0 + tz_off

        #Solar month calculations
        if month_start_after_set == 1:
            sun_month_day = 0
            month_start_after_set = 0

        if sun_month[d] != sun_month[d + 1]:
            sun_month_day = sun_month_day + 1

            if sun_month[d] != sun_month_rise[d + 1]:
                month_start_after_set = 1
                [_m, sun_month_end_time] = get_angam_data_string(
                    masa_names[script], 30, jd_sunrise[d], jd_sunrise[d + 1],
                    t_sunrise, longitude_moon[d], longitude_sun[d],
                    longitude_moon[d + 1], longitude_sun[d + 1], [0, 1],
                    script)

        elif sun_month_rise[d] != sun_month[d]:
            #mAsa pirappu!
            #sun moves into next rAsi before sunset -- check rules!
            sun_month_day = 1

            [_m, sun_month_end_time] = get_angam_data_string(
                masa_names[script], 30, jd_sunrise[d], jd_sunrise[d + 1],
                t_sunrise, longitude_moon[d], longitude_sun[d],
                longitude_moon[d + 1], longitude_sun[d + 1], [0, 1], script)

        else:
            sun_month_day = sun_month_day + 1
            sun_month_end_time = ''

        month_data[d] = '\\sunmonth{%s}{%d}{%s}' % (masa_names[script][
            sun_month[d]], sun_month_day, sun_month_end_time)

        #KARADAYAN NOMBU -- easy to check here
        if sun_month_end_time != '':  #month ends today
            if (sun_month[d] == 12
                    and sun_month_day == 1) or (sun_month[d] == 11
                                                and sun_month_day != 1):
                festival_day_list[karadayan_nombu[script]] = [d]

        #Sunrise/sunset and related stuff (like rahu, yama)
        [rhs, rms, rss] = deci2sexa(
            t_sunrise)  #rise hour sun, rise minute sun, rise sec sun
        [shs, sms, sss] = deci2sexa(t_sunset)

        length_of_day = t_sunset - t_sunrise
        yamagandam_start = t_sunrise + (1 / 8.0) * (
            yamagandam_octets[weekday] - 1) * length_of_day
        yamagandam_end = yamagandam_start + (1 / 8.0) * length_of_day
        rahukalam_start = t_sunrise + (1 / 8.0) * (rahukalam_octets[weekday] -
                                                   1) * length_of_day
        rahukalam_end = rahukalam_start + (1 / 8.0) * length_of_day
        madhyahnikam_start = t_sunrise + (1 / 5.0) * length_of_day

        sunrise[d] = '%02d:%02d' % (rhs, rms)
        sunset[d] = '%02d:%02d' % (shs, sms)
        madhya[d] = print_time(madhyahnikam_start)
        rahu[d] = '%s--%s' % (print_time(rahukalam_start),
                              print_time(rahukalam_end))
        yama[d] = '%s--%s' % (print_time(yamagandam_start),
                              print_time(yamagandam_end))

        [tithi_sunrise[d], tithi_data_string[d]] = get_angam_data_string(
            tithi_names[script], 12, jd_sunrise[d], jd_sunrise[d + 1],
            t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, -1], script)
        [nakshatram_sunrise[d],
         nakshatram_data_string[d]] = get_angam_data_string(
             nakshatra_names[script], (360.0 / 27.0), jd_sunrise[d],
             jd_sunrise[d + 1], t_sunrise, longitude_moon[d], longitude_sun[d],
             longitude_moon[d + 1], longitude_sun[d + 1], [1, 0], script)
        [karanam_sunrise[d], karanam_data_string[d]] = get_angam_data_string(
            karanam_names[script], 6, jd_sunrise[d], jd_sunrise[d + 1],
            t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, -1], script)
        [yogam_sunrise[d], yogam_data_string[d]] = get_angam_data_string(
            yogam_names[script], (360.0 / 27.0), jd_sunrise[d],
            jd_sunrise[d + 1], t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, 1], script)

    #ASSIGN MOON MONTHS
    last_month_change = 1
    last_moon_month = None
    for d in range(1, 367):
        #Assign moon_month for each day
        if (tithi_sunrise[d] == 1):
            for i in range(last_month_change, d):
                #print '%%#Setting moon_month to sun_month_id, for i=%d:%d to %d' %(last_month_change,d-1,sun_month_id[d])
                if (sun_month_id[d] == last_moon_month):
                    moon_month[i] = sun_month_id[d] % 12 + 0.5
                else:
                    moon_month[i] = sun_month_id[d]
            last_month_change = d
            last_moon_month = sun_month_id[d]
        elif (tithi_sunrise[d] == 2 and tithi_sunrise[d - 1] == 30):
            #prathama tithi was never seen @ sunrise
            for i in range(last_month_change, d):
                #print '%%@Setting moon_month to sun_month_id, for i=%d:%d to %d (last month = %d)' %(last_month_change,d-1,sun_month_id[d],last_moon_month)
                if (sun_month_id[d - 1] == last_moon_month):
                    moon_month[i] = sun_month_id[d - 1] % 12 + 0.5
                else:
                    moon_month[i] = sun_month_id[d - 1]
            last_month_change = d
            last_moon_month = sun_month_id[d - 1]

    for i in range(last_month_change, 367):
        moon_month[i] = sun_month_id[last_month_change - 1] + 1

    #for d in range(1,367):
    #jd = jd_start-1+d
    #[y,m,dt,t] = swisseph.revjul(jd)
    #print '%%#%02d-%02d-%4d: %3d:%s (sunrise tithi=%d) {%s}' % (dt,m,y,d,moon_month[d],tithi_sunrise[d],tithi_data_string[d])

    log_file = open('cal_log_%4d.txt' % year, 'w')
    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        log_data = '%02d-%02d-%4d\t[%3d]\tsun_rashi=%8.3f\ttithi=%8.3f\tsun_month=%2d\tmoon_month=%4.1f\n' % (
            dt, m, y, d, (longitude_sun_set[d] % 360) / 30.0,
            get_angam_float(jd_sunrise[d], 12.0,
                            [1, -1]), sun_month[d], moon_month[d])
        log_file.write(log_data)

    #PRINT CALENDAR

    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        ##################
        #Festival details#
        ##################

        ###--- MONTHLY VRATAMS ---###

        #EKADASHI Vratam
        if tithi_sunrise[d] == 11 or tithi_sunrise[
                d] == 12:  #One of two consecutive tithis must appear @ sunrise!
            #check for shukla ekadashi[script]
            if (tithi_sunrise[d] == 11 and tithi_sunrise[d + 1] == 11):
                festivals[d + 1] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='shukla', month=moon_month[d],
                    script=script)  #moon_month[d] or [d+1]?
                if moon_month[d + 1] == 4:
                    festivals[d + 1] += '\\\\' + chaturmasya_start[script]
                if moon_month[d + 1] == 8:
                    festivals[d + 1] += '\\\\' + chaturmasya_end[script]
            elif (tithi_sunrise[d] == 11 and tithi_sunrise[d + 1] != 11):
                #Check dashami end time to decide for whether this is sarva[script]/smartha[script]
                tithi_arunodayam = get_tithi(
                    jd_sunrise[d] - (1 / 15.0) *
                    (jd_sunrise[d] - jd_sunrise[d - 1])
                )  #Two muhurtams is 1/15 of day-length
                if tithi_arunodayam == 10:
                    festivals[d] = smartha[script] + '~' + get_ekadashi_name(
                        paksha='shukla', month=moon_month[d], script=script)
                    festivals[d +
                              1] = vaishnava[script] + '~' + get_ekadashi_name(
                                  paksha='shukla',
                                  month=moon_month[d],
                                  script=script)
                    if moon_month[d] == 4:
                        festivals[d] += '\\\\' + chaturmasya_start[script]
                    if moon_month[d] == 8:
                        festivals[d] += '\\\\' + chaturmasya_end[script]
                else:
                    festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                        paksha='shukla', month=moon_month[d], script=script)
                    if moon_month[d] == 4:
                        festivals[d] += '\\\\' + chaturmasya_start[script]
                    if moon_month[d] == 8:
                        festivals[d] += '\\\\' + chaturmasya_end[script]
            elif (tithi_sunrise[d - 1] != 11 and tithi_sunrise[d] == 12):
                festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='shukla', month=moon_month[d], script=script)
                if moon_month[d] == 4:
                    festivals[d] += '\\\\' + chaturmasya_start[script]
                if moon_month[d] == 8:
                    festivals[d] += '\\\\' + chaturmasya_end[script]

        if tithi_sunrise[d] == 26 or tithi_sunrise[
                d] == 27:  #One of two consecutive tithis must appear @ sunrise!
            #check for krishna ekadashi[script]
            if (tithi_sunrise[d] == 26 and tithi_sunrise[d + 1] == 26):
                festivals[d + 1] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='krishna', month=moon_month[d],
                    script=script)  #moon_month[d] or [d+1]?
            elif (tithi_sunrise[d] == 26 and tithi_sunrise[d + 1] != 26):
                #Check dashami end time to decide for whether this is sarva[script]/smartha[script]
                tithi_arunodayam = get_tithi(
                    jd_sunrise[d] - (1 / 15.0) *
                    (jd_sunrise[d] - jd_sunrise[d - 1])
                )  #Two muhurtams is 1/15 of day-length
                if tithi_arunodayam == 25:
                    festivals[d] = smartha[script] + '~' + get_ekadashi_name(
                        paksha='krishna', month=moon_month[d], script=script)
                    festivals[d +
                              1] = vaishnava[script] + '~' + get_ekadashi_name(
                                  paksha='krishna',
                                  month=moon_month[d],
                                  script=script)
                else:
                    festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                        paksha='krishna', month=moon_month[d], script=script)
            elif (tithi_sunrise[d - 1] != 26 and tithi_sunrise[d] == 27):
                festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='krishna', month=moon_month[d], script=script)

        #PRADOSHA Vratam
        if tithi_sunrise[d] == 12 or tithi_sunrise[d] == 13:
            ldiff_set = (swisseph.calc_ut(jd_sunset[d], swisseph.MOON)[0] -
                         swisseph.calc_ut(jd_sunset[d], swisseph.SUN)[0]) % 360
            ldiff_set_tmrw = (
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.SUN)[0]) % 360
            tithi_sunset = int(1 + math.floor(ldiff_set / 12.0))
            tithi_sunset_tmrw = int(1 + math.floor(ldiff_set_tmrw / 12.0))
            if tithi_sunset <= 13 and tithi_sunset_tmrw != 13:
                festivals[d] = pradosham[script]
            elif tithi_sunset_tmrw == 13:
                festivals[d + 1] = pradosham[script]

        if tithi_sunrise[d] == 27 or tithi_sunrise[d] == 28:
            ldiff_set = (swisseph.calc_ut(jd_sunset[d], swisseph.MOON)[0] -
                         swisseph.calc_ut(jd_sunset[d], swisseph.SUN)[0]) % 360
            ldiff_set_tmrw = (
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.SUN)[0]) % 360
            tithi_sunset = int(1 + math.floor(ldiff_set / 12.0))
            tithi_sunset_tmrw = int(1 + math.floor(ldiff_set_tmrw / 12.0))
            if tithi_sunset <= 28 and tithi_sunset_tmrw != 28:
                festivals[d] = pradosham[script]
            elif tithi_sunset_tmrw == 28:
                festivals[d + 1] = pradosham[script]

        #SANKATAHARA chaturthi[script]
        if tithi_sunrise[d] == 18 or tithi_sunrise[d] == 19:
            ldiff_moonrise_yest = (
                swisseph.calc_ut(jd_moonrise[d - 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d - 1], swisseph.SUN)[0]) % 360
            ldiff_moonrise = (
                swisseph.calc_ut(jd_moonrise[d], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d], swisseph.SUN)[0]) % 360
            ldiff_moonrise_tmrw = (
                swisseph.calc_ut(jd_moonrise[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d + 1], swisseph.SUN)[0]) % 360
            tithi_moonrise_yest = int(1 +
                                      math.floor(ldiff_moonrise_yest / 12.0))
            tithi_moonrise = int(1 + math.floor(ldiff_moonrise / 12.0))
            tithi_moonrise_tmrw = int(1 +
                                      math.floor(ldiff_moonrise_tmrw / 12.0))

            if tithi_moonrise == 19:
                if tithi_moonrise_yest != 19:  #otherwise yesterday would have already been assigned
                    festivals[d] = chaturthi[script]
                    if moon_month[d] == 5:  #shravana krishna chaturthi[script]
                        festivals[d] = maha[script] + festivals[d]
            elif tithi_moonrise_tmrw == 19:
                festivals[d + 1] = chaturthi[script]
                if moon_month[
                        d] == 5:  #moon_month[d] and[d+1] are same, so checking [d] is enough
                    festivals[d + 1] = maha[script] + festivals[d + 1]

        #SHASHTHI Vratam
        if tithi_sunrise[d] == 5 or tithi_sunrise[d] == 6:
            if tithi_sunrise[d] == 6 or (tithi_sunrise[d] == 5
                                         and tithi_sunrise[d + 1] == 7):
                if tithi_sunrise[
                        d -
                        1] != 6:  #otherwise yesterday would have already been assigned
                    festivals[d] = shashthi[script]
                    if moon_month[d] == 8:  #kArtika krishna shashthi[script]
                        festivals[d] = skanda[script] + festivals[d]
            elif tithi_sunrise[d + 1] == 6:
                festivals[d + 1] = shashthi[script]
                if moon_month[
                        d] == 8:  #moon_month[d] and[d+1] are same, so checking [d] is enough
                    festivals[d + 1] = skanda[script] + festivals[d + 1]

        ###--- OTHER (MAJOR) FESTIVALS ---###
        #type of month | month number | type of angam (tithi|nakshatram) | angam number | min_t cut off for considering prev day (without sunrise_angam) as festival date
        purvaviddha_rules = {
            akshaya_tritiya[script]: ['moon_month', 2, 'tithi', 3, 0],
            chitra_purnima[script]: ['sun_month', 1, 'tithi', 15, 0],
            durgashtami[script]: ['moon_month', 7, 'tithi', 8, 0],
            mahanavami[script]: ['moon_month', 7, 'tithi', 9, 0],
            vijayadashami[script]: ['moon_month', 7, 'tithi', 10, 0],
            dipavali[script]: ['moon_month', 7, 'tithi', 29, 0],
            shankara_jayanti[script]: ['moon_month', 2, 'tithi', 5, 0],
            yajur_upakarma[script]: ['moon_month', 5, 'tithi', 15, 0],
            rg_upakarma[script]: ['moon_month', 5, 'nakshatram', 22, 0],
            sama_upakarma[script]: ['sun_month', 5, 'nakshatram', 13, 0],
            rishi_panchami[script]: ['moon_month', 6, 'tithi', 5, 0],
            ananta_chaturdashi[script]: ['moon_month', 6, 'tithi', 14, 0],
            mahalaya_paksham[script]: ['moon_month', 6, 'tithi', 16, 0],
            hanumat_jayanti[script]: ['sun_month', 9, 'tithi', 30, 0],
            ardra_darshanam[script]: ['sun_month', 9, 'nakshatram', 6, 0],
            ratha_saptami[script]: ['sun_month', 10, 'tithi', 7, 0],
            goda_jayanti[script]: ['sun_month', 4, 'nakshatram', 11, 0],
            adi_krittika[script]: ['sun_month', 4, 'nakshatram', 3, 0],
            phalguni_uttaram[script]: ['sun_month', 12, 'nakshatram', 12, 4],
            mahalaya_amavasya[script]: ['moon_month', 6, 'tithi', 30, 0],
            uma_maheshvara_vratam[script]: ['moon_month', 6, 'tithi', 15, 0]
        }

        for x in iter(purvaviddha_rules.keys()):
            rule = purvaviddha_rules[x]
            if rule[0] == 'moon_month':
                if moon_month[d] == rule[1]:
                    if rule[2] == 'tithi':
                        fday = get_festival_day_purvaviddha(
                            rule[3], tithi_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_tithi, rule[4])
                    elif rule[2] == 'nakshatram':
                        fday = get_festival_day_purvaviddha(
                            rule[3], nakshatram_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_nakshatram, rule[4])
                    if fday is not None:
                        if festival_day_list.has_key(x):
                            if festival_day_list[x][0] != fday:
                                #Second occurrence of a festival within a Gregorian calendar year
                                festival_day_list[x] = [
                                    festival_day_list[x][0], fday
                                ]
                        else:
                            festival_day_list[x] = [fday]
            elif rule[0] == 'sun_month':
                if sun_month[d] == rule[1]:
                    if rule[2] == 'tithi':
                        fday = get_festival_day_purvaviddha(
                            rule[3], tithi_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_tithi, rule[4])
                    elif rule[2] == 'nakshatram':
                        fday = get_festival_day_purvaviddha(
                            rule[3], nakshatram_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_nakshatram, rule[4])
                    if fday is not None:
                        if festival_day_list.has_key(x):
                            if festival_day_list[x][0] != fday:
                                #Second occurrence of a festival within a Gregorian calendar year
                                festival_day_list[x] = [
                                    festival_day_list[x][0], fday
                                ]
                        else:
                            festival_day_list[x] = [fday]
            else:
                print 'Error; unknown string in rule: %s' % (rule[0])
                return

        #NAVARATRI START
        if moon_month[d] == 7 and moon_month[d - 1] == 6:
            festival_day_list[navaratri_start[script]] = [d]

        #PONGAL/AYANAM
        if sun_month[d] == 10 and sun_month[d - 1] == 9:
            festival_day_list[uttarayanam[script]] = [d]

        if sun_month[d] == 4 and sun_month[d - 1] == 3:
            festival_day_list[dakshinayanam[script]] = [d]

        if sun_month[d] == 1 and sun_month[d - 1] == 12:
            festival_day_list[new_yr] = [d]

        if moon_month[d] == 1 and moon_month[d - 1] != 1:
            festival_day_list[yugadi[script]] = [d]

        #SHRIRAMANAVAMI
        if moon_month[d] == 1:
            if tithi_sunrise[d] == 8 or tithi_sunrise[d] == 9:
                t_11 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (2.0 / 5.0))  #madhyahna1 start
                t_12 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (3.0 / 5.0))  #madhyahna1 end
                t_21 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (2.0 / 5.0))  #madhyahna2 start
                t_22 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (3.0 / 5.0))  #madhyahna2 end
                if t_11 == 9 or t_12 == 9:
                    if t_21 == 9 or t_22 == 9:
                        festival_day_list[ramanavami[script]] = [d + 1]
                    else:
                        festival_day_list[ramanavami[script]] = [d]

        #JANMASHTAMI
        if moon_month[d] == 5:
            if tithi_sunrise[d] == 22 or tithi_sunrise[d] == 23:
                t_11 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (7.0 / 15.0))  #nishita1 start
                t_12 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (8.0 / 15.0))  #nishita1 end
                #t_11 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(2.0/5.0))#madhyaratri1 start
                #t_12 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(3.0/5.0))#madhyaratri1 end
                t_21 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (7.0 / 15.0))  #nishita2 start
                t_22 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (8.0 / 15.0))  #nishita2 end
                #t_21 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(2.0/5.0))#madhyaratri2 start
                #t_22 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(3.0/5.0))#madhyaratri2 end
                if t_11 == 23 or t_12 == 23:
                    if t_21 == 23 or t_22 == 23:
                        festival_day_list[janmashtami[script]] = [d + 1]
                    else:
                        festival_day_list[janmashtami[script]] = [d]

        #SHIVARATRI
        if moon_month[d] == 11:
            if tithi_sunrise[d] == 28 or tithi_sunrise[d] == 29:
                t_11 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (7.0 / 15.0))  #nishita1 start
                t_12 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (8.0 / 15.0))  #nishita1 end
                t_21 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (7.0 / 15.0))  #nishita2 start
                t_22 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (8.0 / 15.0))  #nishita2 end
                if t_11 == 29 or t_12 == 29:
                    if t_21 == 29 or t_22 == 29:
                        festival_day_list[shivaratri[script]] = [d + 1]
                    else:
                        festival_day_list[shivaratri[script]] = [d]

        #VINAYAKA CHATURTHI
        if moon_month[d] == 6:
            if tithi_sunrise[d] == 3 or tithi_sunrise[d] == 4:
                t_11 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (2.0 / 5.0))  #madhyahna1 start
                t_12 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (3.0 / 5.0))  #madhyahna1 end
                t_21 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (2.0 / 5.0))  #madhyahna2 start
                t_22 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (3.0 / 5.0))  #madhyahna2 end
                if t_11 == 4 or t_12 == 4:
                    if t_21 == 4 or t_22 == 4:
                        festival_day_list[vchaturthi[script]] = [d + 1]
                    else:
                        festival_day_list[vchaturthi[script]] = [d]

    #Add saved festivals
    festival_day_list[gayatri_japam[script]] = [
        festival_day_list[yajur_upakarma[script]][0] + 1
    ]
    festival_day_list[varalakshmi_vratam[script]] = [
        festival_day_list[yajur_upakarma[script]][0] -
        ((weekday_start - 1 + festival_day_list[yajur_upakarma[script]][0] - 5)
         % 7)
    ]
    #KARADAYAN_NOMBU
    for x in iter(festival_day_list.keys()):
        for j in range(0, len(festival_day_list[x])):
            if festivals[festival_day_list[x][j]] != '':
                festivals[festival_day_list[x][j]] += '\\\\'
            festivals[festival_day_list[x][j]] += x

    ###--- ECLIPSES ---###
    ###--- LUNAR ECLIPSES ---###
    swisseph.set_topo(lon=longitude, lat=latitude, alt=0.0)  #Set location
    jd = jd_start
    while 1:
        next_ecl_lun = swisseph.lun_eclipse_when(jd)
        jd = next_ecl_lun[1][0] + (tz_off / 24.0)
        jd_ecl_lun_start = next_ecl_lun[1][2] + (tz_off / 24.0)
        jd_ecl_lun_end = next_ecl_lun[1][3] + (tz_off / 24.0)
        ecl_y = swisseph.revjul(
            jd - 1
        )[0]  # -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
        if ecl_y != start_year:
            break
        else:
            ecl_lun_start = swisseph.revjul(jd_ecl_lun_start)[3]
            ecl_lun_end = swisseph.revjul(jd_ecl_lun_end)[3]
            if (jd_ecl_lun_start -
                (tz_off / 24.0)) == 0.0 or (jd_ecl_lun_end -
                                            (tz_off / 24.0)) == 0.0:
                jd = jd + 20  #Move towards the next eclipse... at least the next full moon (>=25 days away)
                continue
            fday = int(math.floor(jd_ecl_lun_start) - math.floor(jd_start) + 1)
            #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1]
            if (jd < (jd_sunrise[fday] + tz_off / 24.0)):
                fday -= 1
            if ecl_lun_start < swisseph.revjul(jd_sunrise[fday + 1] +
                                               tz_off / 24.0)[3]:
                ecl_lun_start += 24
            #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1],ecl_lun_start, ecl_lun_end
            jd_moonrise_ecl_day = swisseph.rise_trans(
                jd_start=jd_sunrise[fday],
                body=swisseph.MOON,
                lon=longitude,
                lat=latitude,
                rsmi=swisseph.CALC_RISE
                | swisseph.BIT_DISC_CENTER)[1][0] + (tz_off / 24.0)
            jd_moonset_ecl_day = swisseph.rise_trans(
                jd_start=jd_moonrise_ecl_day,
                body=swisseph.MOON,
                lon=longitude,
                lat=latitude,
                rsmi=swisseph.CALC_SET
                | swisseph.BIT_DISC_CENTER)[1][0] + (tz_off / 24.0)
            #if jd_ecl_lun_start<(jd_sunrise[fday]+(tz_off/24.0)):
            if ecl_lun_end < ecl_lun_start:
                ecl_lun_end += 24
            #print '%%', (jd_ecl_lun_start), (jd_ecl_lun_end), (jd_moonrise_ecl_day), (jd_moonset_ecl_day)
            #print '%%', swisseph.revjul(jd_ecl_lun_start), swisseph.revjul(jd_ecl_lun_end), swisseph.revjul(jd_moonrise_ecl_day), swisseph.revjul(jd_moonset_ecl_day)
            if jd_ecl_lun_end < jd_moonrise_ecl_day or jd_ecl_lun_start > jd_moonset_ecl_day:
                jd = jd + 20  #Move towards the next eclipse... at least the next full moon (>=25 days away)
                continue
            lun_ecl_str = chandra_grahanam[script] + '~\\textsf{' + print_time2(
                ecl_lun_start) + '}{\\RIGHTarrow}\\textsf{' + print_time2(
                    ecl_lun_end) + '}'
            if festivals[fday] != '':
                festivals[fday] += '\\\\'
            festivals[fday] += lun_ecl_str
        jd = jd + 20

    ###--- SOLAR ECLIPSES ---###
    swisseph.set_topo(lon=longitude, lat=latitude, alt=0.0)  #Set location
    jd = jd_start
    while 1:
        next_ecl_sol = swisseph.sol_eclipse_when_loc(julday=jd,
                                                     lon=longitude,
                                                     lat=latitude)
        jd = next_ecl_sol[1][0] + (tz_off / 24.0)
        jd_ecl_sol_start = next_ecl_sol[1][1] + (tz_off / 24.0)
        jd_ecl_sol_end = next_ecl_sol[1][4] + (tz_off / 24.0)
        ecl_y = swisseph.revjul(
            jd - 1
        )[0]  # -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
        if ecl_y != start_year:
            break
        else:
            #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
            #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
            fday = int(math.floor(jd) - math.floor(jd_start) + 1)
            if (jd < (jd_sunrise[fday] + tz_off / 24.0)):
                fday -= 1
            #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
            #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
            ecl_sol_start = swisseph.revjul(jd_ecl_sol_start)[3]
            ecl_sol_end = swisseph.revjul(jd_ecl_sol_end)[3]
            if (jd_ecl_sol_start - (tz_off / 24.0)) == 0.0 or (
                    jd_ecl_sol_end - (tz_off / 24.0)
            ) == 0.0:  # or jd_ecl_end<jd_sunrise[fday] or jd_ecl_start>jd_sunset[fday]:
                jd = jd + 20  #Move towards the next eclipse... at least the next new moon (>=25 days away)
                continue
            if ecl_sol_end < ecl_sol_start:
                ecl_sol_end += 24
            sol_ecl_str = surya_grahanam[script] + '~\\textsf{' + print_time2(
                ecl_sol_start) + '}{\\RIGHTarrow}\\textsf{' + print_time2(
                    ecl_sol_end) + '}'
            if festivals[fday] != '':
                festivals[fday] += '\\\\'
            festivals[fday] += sol_ecl_str
        jd = jd + 20
    ###--- FESTIVAL ADDITIONS COMPLETE ---###

    ###--- PRINT LIST OF FESTIVALS (Page 2) ---###
    if script == 'en':
        cal = Calendar()

    print '\\newpage'
    print '\\centerline {\\LARGE {{%s}}}\\mbox{}\\\\[2cm]' % list_of_festivals[
        script]
    print '\\begin{center}'
    print '\\begin{minipage}[t]{0.3\\linewidth}'
    print '\\begin{center}'
    print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}cp{6cm}}'

    mlast = 1
    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        if festivals[d] != '':
            if m != mlast:
                mlast = m
                #print '\\hline\\\\'
                print '\\\\'
                if m == 5 or m == 9:
                    print '\\end{tabular}'
                    print '\\end{center}'
                    print '\\end{minipage}\hspace{1cm}%'
                    print '\\begin{minipage}[t]{0.3\\linewidth}'
                    print '\\begin{center}'
                    print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}l>{\\sffamily}cp{6cm}}'

            print '%s & %s & %s & {\\raggedright %s} \\\\' % (
                MON[m], dt, WDAY[weekday], festivals[d])

            if script == 'en':
                event = Event()
                event.add('summary', festivals[d])
                event.add('dtstart', datetime(y, m, dt))
                event.add('dtend', datetime(y, m, dt))
                cal.add_component(event)

        if m == 12 and dt == 31:
            break

    print '\\end{tabular}'
    print '\\end{center}'
    print '\\end{minipage}'
    print '\\end{center}'
    print '\\clearpage'

    if script == 'en':
        cal_fname = '%s-%4d.ics' % (city_name, start_year)
        cal_file = open(cal_fname, 'w')
        cal_file.write(cal.as_string())
        cal_file.close()

    #Layout calendar in LATeX format
    #We use a separate loop here, because of festivals like varalakshmi
    #vratam, for which we backtrack to the previous friday from yajur
    #upakarma and change the list of festivals!

    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        if dt == 1:
            if m > 1:
                if weekday != 0:  #Space till Sunday
                    for i in range(weekday, 6):
                        print "{}  &"
                    print "\\\\ \hline"
                print '\end{tabular}'
                print '\n\n'

            #Begin tabular
            print '\\begin{tabular}{|c|c|c|c|c|c|c|}'
            print '\multicolumn{7}{c}{\Large \\bfseries \sffamily %s %s}\\\\[3mm]' % (
                month[m], y)
            print '\hline'
            print '\\textbf{\\textsf{SUN}} & \\textbf{\\textsf{MON}} & \\textbf{\\textsf{TUE}} & \\textbf{\\textsf{WED}} & \\textbf{\\textsf{THU}} & \\textbf{\\textsf{FRI}} & \\textbf{\\textsf{SAT}} \\\\ \hline'
            #print '\\textbf{भानु} & \\textbf{इन्दु} & \\textbf{भौम} & \\textbf{बुध} & \\textbf{गुरु} & \\textbf{भृगु} & \\textbf{स्थिर} \\\\ \hline'

            #Blanks for previous weekdays
            for i in range(0, weekday):
                print "{}  &"

        print '\caldata{\\textcolor{%s}{%s}}{%s{%s}}{\\sundata{%s}{%s}{%s}}{\\tnyk{%s}{%s}{%s}{%s}}{\\rahuyama{%s}{%s}}{%s} ' % (
            daycol[weekday], dt, month_data[d],
            get_chandra_masa(moon_month[d], chandra_masa_names, script),
            sunrise[d], sunset[d], madhya[d], tithi_data_string[d],
            nakshatram_data_string[d], yogam_data_string[d],
            karanam_data_string[d], rahu[d], yama[d], festivals[d])

        if weekday == 6:
            print "\\\\ \hline"
        else:
            print "&"

        if m == 12 and dt == 31:
            break

        # For debugging specific dates
        #if m==4 and dt==10:
        #  break

    for i in range(weekday + 1, 6):
        print "{}  &"
    if weekday != 6:
        print "\\\\ \hline"
    print '\end{tabular}'
    print '\n\n'

    print template_lines[-2][:-1]
    print template_lines[-1][:-1]
Example #39
0
def main():
    city_name = sys.argv[1]
    latitude = sexastr2deci(sys.argv[2])
    longitude = sexastr2deci(sys.argv[3])
    tz = sys.argv[4]

    start_year = int(sys.argv[5])
    year = start_year
    jd = swisseph.julday(year, 1, 1, 0)
    jd_start = jd
    start_date = datetime(year=year,
                          month=1,
                          day=1,
                          hour=0,
                          minute=0,
                          second=0)

    day_of_year = 0

    swisseph.set_sid_mode(swisseph.SIDM_LAHIRI)  #Force Lahiri Ayanamsha

    sun_month_day = jd - get_last_dhanur_transit(jd, latitude, longitude)
    #this has to be done in a generic fashion, by scanning for the transit into dhanur of the last year!

    month_start_after_set = 0

    template_file = open('cal_template.tex')
    template_lines = template_file.readlines()
    for i in range(0, len(template_lines) - 3):
        print template_lines[i][:-1]

    samvatsara_id = (year - 1568) % 60 + 1
    #distance from prabhava
    samvatsara_names = '%s–%s' % (year_names[samvatsara_id],
                                  year_names[(samvatsara_id % 60) + 1])

    print '\\mbox{}'
    print '{\\font\\x="Warnock Pro" at 60 pt\\x %d\\\\[0.3cm]}' % year
    print '\\mbox{\\font\\x="Sanskrit 2003:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names
    print '{\\font\\x="Warnock Pro" at 48 pt\\x \\uppercase{%s}\\\\[0.3cm]}' % city_name
    print '\hrule'

    while year <= start_year:

        day_of_year = day_of_year + 1

        [y, m, d, t] = swisseph.revjul(jd)
        weekday = (swisseph.day_of_week(jd) +
                   1) % 7  #swisseph has Mon = 0, non-intuitively!

        local_time = pytz.timezone(tz).localize(datetime(
            y, m, d, 6, 0, 0))  #checking @ 6am local - can we do any better?
        tz_off = datetime.utcoffset(
            local_time).seconds / 3600.0  #compute offset from UTC

        jd_rise = swisseph.rise_trans(jd_start=jd,
                                      body=swisseph.SUN,
                                      lon=longitude,
                                      lat=latitude,
                                      rsmi=swisseph.CALC_RISE
                                      | swisseph.BIT_DISC_CENTER)[1][0]
        jd_rise_tmrw = swisseph.rise_trans(jd_start=jd + 1,
                                           body=swisseph.SUN,
                                           lon=longitude,
                                           lat=latitude,
                                           rsmi=swisseph.CALC_RISE
                                           | swisseph.BIT_DISC_CENTER)[1][0]
        jd_set = swisseph.rise_trans(jd_start=jd,
                                     body=swisseph.SUN,
                                     lon=longitude,
                                     lat=latitude,
                                     rsmi=swisseph.CALC_SET
                                     | swisseph.BIT_DISC_CENTER)[1][0]

        [_y, _m, _d, t_rise] = swisseph.revjul(jd_rise + tz_off / 24.0)
        [_y, _m, _d, t_set] = swisseph.revjul(jd_set + tz_off / 24.0)

        longitude_moon = swisseph.calc_ut(
            jd_rise, swisseph.MOON)[0] - swisseph.get_ayanamsa(jd_rise)
        longitude_moon_tmrw = swisseph.calc_ut(
            jd_rise + 1, swisseph.MOON)[0] - swisseph.get_ayanamsa(jd_rise + 1)

        longitude_sun = swisseph.calc_ut(
            jd_rise, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_rise)
        longitude_sun_set = swisseph.calc_ut(
            jd_set, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_set)
        sun_month_rise = masa_names[int(1 + math.floor((
            (longitude_sun) % 360) / 30.0))]
        sun_month = masa_names[int(1 + math.floor((
            (longitude_sun_set) % 360) / 30.0))]
        longitude_sun_tmrw = swisseph.calc_ut(
            jd_rise + 1, swisseph.SUN)[0] - swisseph.get_ayanamsa(jd_rise + 1)
        sun_month_tmrw = masa_names[int(1 + math.floor((
            (longitude_sun_tmrw) % 360) / 30.0))]

        daily_motion_moon = (longitude_moon_tmrw - longitude_moon) % 360
        daily_motion_sun = (longitude_sun_tmrw - longitude_sun) % 360

        #Solar month calculations
        if month_start_after_set == 1:
            sun_month_day = 0
            month_start_after_set = 0

        if sun_month_rise != sun_month_tmrw:
            if sun_month != sun_month_tmrw:
                month_start_after_set = 1
                sun_month_day = sun_month_day + 1
            #mAsa pirappu!
            #sun_month = sun_month_tmrw #sun moves into next rAsi before sunset -- check rules!
            else:
                sun_month_day = 1
            month_remaining = 30 - (longitude_sun % 30.0)
            month_end = month_remaining / daily_motion_sun * 24.0
            me = deci2sexa(t_rise + month_end)
            if me[0] >= 24:
                suff = '(+1)'
                me[0] = me[0] - 24
            else:
                suff = '\\hspace{2ex}'
            sun_month_end_time = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %02d:%02d%s}' % (
                last_sun_month, me[0], me[1], suff)
        else:
            sun_month_day = sun_month_day + 1
            sun_month_end_time = ''

        month_data = '\\sunmonth{%s}{%d}{%s}' % (sun_month, sun_month_day,
                                                 sun_month_end_time)
        #print '%%@%f:%d-%d-%d: rise=%s, set=%s, tmrw=%s' %(jd,y,m,d,sun_month_rise,sun_month,sun_month_tmrw)

        #Compute tithi details
        tithi = int(1 +
                    math.floor((longitude_moon - longitude_sun) % 360 / 12.0))
        tithi_tmrw = int(1 + math.floor(
            (longitude_moon_tmrw - longitude_sun_tmrw) % 360 / 12.0))

        if (tithi_tmrw - tithi) % 30 > 1:
            #double change
            tithi_2 = (tithi % 30) + 1
            if tithi_2 % 15 != 0:
                paksha = ('shukla' if tithi_2 < 15 else 'krishna')
            else:
                if tithi_2 == 15:
                    paksha = 'fullmoon'
                elif tithi_2 == 30:
                    paksha = 'newmoon'

            if tithi_2 % 15 == 0:
                tithi_str_2 = paksha + tithi_names[tithi_2]
            else:
                tithi_str_2 = paksha + tithi_names[tithi_2 % 15]

            tithi_remaining_2 = 12 + 12 - ((
                (longitude_moon - longitude_sun) % 360) % 12)
            tithi_end_2 = tithi_remaining_2 / (daily_motion_moon -
                                               daily_motion_sun) * 24.0
            tithi_end_str_2 = print_end_time(tithi_end_2,
                                             jd_rise_tmrw - jd_rise, t_rise)
            if tithi_end_str_2 == '\\textsf{अहोरात्रम्}':
                #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
                #the second tithi cannot be 'all day'! It's ending will reflect in tomorrow's calendar
                tithi_str_2 = ''
                tithi_end_str_2 = ''
        else:
            tithi_str_2 = ''
            tithi_end_str_2 = ''

        if tithi % 15 != 0:
            paksha = ('shukla' if tithi < 15 else 'krishna')
        else:
            if tithi == 15:
                paksha = 'fullmoon'
            elif tithi == 30:
                paksha = 'newmoon'

        if tithi % 15 == 0:
            tithi_str = paksha + tithi_names[tithi]
        else:
            tithi_str = paksha + tithi_names[tithi % 15]

        tithi_remaining = 12 - (((longitude_moon - longitude_sun) % 360) % 12)
        tithi_end = tithi_remaining / (daily_motion_moon -
                                       daily_motion_sun) * 24.0
        tithi_end_str = print_end_time(tithi_end, jd_rise_tmrw - jd_rise,
                                       t_rise)

        #Compute nakshatram details
        n_id = int(1 + math.floor((longitude_moon % 360) / (360.0 / 27)))
        n_id_tmrw = int(1 + math.floor((longitude_moon_tmrw % 360) /
                                       (360.0 / 27)))
        if (n_id_tmrw - n_id) % 27 > 1:
            #there is a double change
            nakshatram_str_2 = nakshatra_names[n_id % 27 + 1]
            nakshatram_remaining_2 = (360.0 / 27) + (360.0 / 27) - (
                (longitude_moon % 360) % (360.0 / 27))
            nakshatram_end_2 = nakshatram_remaining_2 / daily_motion_moon * 24
            nakshatram_end_str_2 = print_end_time(nakshatram_end_2,
                                                  jd_rise_tmrw - jd_rise,
                                                  t_rise)
            if nakshatram_end_str_2 == '\\textsf{अहोरात्रम्}':
                #needs correction, owing to the fact that we compute longitude every 24h, rather than at next sunrise
                #the second nakshatram cannot be 'all day'! It's ending will reflect in tomorrow's calendar
                nakshatram_str_2 = ''
                nakshatram_end_str_2 = ''
        else:
            nakshatram_str_2 = ''
            nakshatram_end_str_2 = ''

        nakshatram_str = nakshatra_names[n_id]
        nakshatram_remaining = (360.0 / 27) - ((longitude_moon % 360) %
                                               (360.0 / 27))
        nakshatram_end = nakshatram_remaining / daily_motion_moon * 24
        nakshatram_end_str = print_end_time(nakshatram_end,
                                            jd_rise_tmrw - jd_rise, t_rise)

        #Sunrise/sunset and related stuff (like rahu, yama)
        [rh, rm, rs] = deci2sexa(t_rise)  #rise_t hour, rise minute
        [sh, sm, ss] = deci2sexa(t_set)  #set_t hour, set minute

        present_day = start_date + timedelta(days=day_of_year)
        rise_t = present_day + timedelta(hours=rh, minutes=rm)
        set_t = present_day + timedelta(hours=sh, minutes=sm)

        length_of_day = set_t - rise_t
        yamakandam_start = rise_t + timedelta(
            seconds=(1 / 8.0) *
            (yamakandam_octets[weekday] - 1) * length_of_day.seconds)
        yamakandam_end = yamakandam_start + timedelta(seconds=(1 / 8.0) *
                                                      length_of_day.seconds)
        rahukalam_start = rise_t + timedelta(seconds=(1 / 8.0) *
                                             (rahukalam_octets[weekday] - 1) *
                                             length_of_day.seconds)
        rahukalam_end = rahukalam_start + timedelta(seconds=(1 / 8.0) *
                                                    length_of_day.seconds)
        madhyahnikam_start = rise_t + timedelta(seconds=(1 / 5.0) *
                                                length_of_day.seconds)

        rise = '%02d:%02d' % (rh, rm)
        set = '%02d:%02d' % (sh, sm)
        madhya = print_time(madhyahnikam_start)
        rahu = '%s--%s' % (print_time(rahukalam_start),
                           print_time(rahukalam_end))
        yama = '%s--%s' % (print_time(yamakandam_start),
                           print_time(yamakandam_end))

        #Layout calendar in LATeX format
        if d == 1:
            if m > 1:
                if weekday != 0:  #Space till Sunday
                    for i in range(weekday, 6):
                        print "{}  &"
                    print "\\\\ \hline"
                print '\end{tabular}'
                print '\n\n'

            #Begin tabular
            print '\\begin{tabular}{|c|c|c|c|c|c|c|}'
            print '\multicolumn{7}{c}{\Large \\bfseries %s %s}\\\\[3mm]' % (
                month[m], y)
            print '\hline'
            print '\\textbf{SUN} & \\textbf{MON} & \\textbf{TUE} & \\textbf{WED} & \\textbf{THU} & \\textbf{FRI} & \\textbf{SAT} \\\\ \hline'
            #print '\\textbf{भानु} & \\textbf{इन्दु} & \\textbf{भौम} & \\textbf{बुध} & \\textbf{गुरु} & \\textbf{भृगु} & \\textbf{स्थिर} \\\\ \hline'

            #Blanks for previous weekdays
            for i in range(0, weekday):
                print "{}  &"

        #Create nakshatram data string
        nEmpty = 0

        if nakshatram_end_str_2 != '':
            nakshatram_data_string = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (
                nakshatram_str, nakshatram_end_str, nakshatram_str_2,
                nakshatram_end_str_2)
        else:
            nakshatram_data_string = '{\\textsf{%s} {\\tiny \\RIGHTarrow} %s}' % (
                nakshatram_str, nakshatram_end_str)
            nEmpty = nEmpty + 1

        if tithi_end_str_2 != '':
            tithi_data_string = '{\\textsf{\\%s} {\\tiny \\RIGHTarrow} %s}{\\textsf{\\%s} {\\tiny \\RIGHTarrow} %s}' % (
                tithi_str, tithi_end_str, tithi_str_2, tithi_end_str_2)
        else:
            tithi_data_string = '{\\textsf{\\%s} {\\tiny \\RIGHTarrow} %s}' % (
                tithi_str, tithi_end_str)
            nEmpty = nEmpty + 1

        empty_str = ''
        for i in range(0, nEmpty):
            empty_str = empty_str + '{}'

        print '\caldata{\\textcolor{%s}{%s}}{%s}{\\sundata{%s}{%s}{%s}}%s%s%s{\\textsf{राहु}~%s~~\\textsf{यम}~%s} ' % (
            daycol[weekday], d, month_data, rise, set, madhya,
            tithi_data_string, nakshatram_data_string, empty_str, rahu, yama)

        if weekday == 6:
            print "\\\\ \hline"
        else:
            print "&"

        jd = jd + 1

        last_sun_month = sun_month

        if m == 12 and d == 31:
            year = year + 1

        # For debugging specific dates
        #if m==4 and d==10:
        #  break

    for i in range(weekday + 1, 6):
        print "{}  &"
    if weekday != 6:
        print "\\\\ \hline"
    print '\end{tabular}'
    print '\n\n'

    #print '\\input{%d-%s.tex}' % (year,city_name)
    print template_lines[-2][:-1]
    print template_lines[-1][:-1]
Example #40
0
# from flatlib.geopos import GeoPos
# import flatlib.const as const
# from flatlib.chart import Chart

# now = Datetime('2009/07/15', '05:30')
# pos = GeoPos(13.0827, 80.2707)  # chennai
now = swe.julday(2019, 8, 26, .5, swe.GREG_CAL)

ts = skyfield.api.load.timescale()
planets = skyfield.api.load('de421.bsp')

# for k in range(0,39):
#     swe.set_sid_mode(k)
#     ayanamsa = swe.get_ayanamsa(now)
#     print(swe.get_ayanamsa_name(k),ayanamsa)
swe.set_sid_mode(swe.SIDM_LAHIRI)
# chart = Chart(now, pos, hsys=const.HOUSES_EQUAL)
# sun = chart.getObject(const.SUN)
# moon = chart.getObject(const.MOON)
chennai = skyfield.api.Topos('13.0827 N', '80.2707 E')
t0 = ts.utc(2019, 4, 14)
t1 = ts.utc(2020, 4, 14)
t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(planets, chennai))

now = t[0].tt
ayanamsa = swe.get_ayanamsa(now)

sun = swe.calc(now, swe.SUN, swe.FLG_SIDEREAL)
moon = swe.calc(now, swe.MOON, swe.FLG_SIDEREAL)
mars = swe.calc(now, swe.MARS, swe.FLG_SIDEREAL)
mercury = swe.calc(now, swe.MERCURY, swe.FLG_SIDEREAL)