-
Notifications
You must be signed in to change notification settings - Fork 10
/
pycalcal.nw
9380 lines (7954 loc) · 331 KB
/
pycalcal.nw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% draft is convinient to show over/under boxes,
% BUT it does NOT inlude graphics nor create links
%\documentclass[a4paper,draft,pdftex]{report}
\documentclass[a4paper,pdftex]{report}
\usepackage{fp}
% for proper typesetting of angles...but it lacks h/m/s forms
\usepackage{siunitx}
\def\dms{\ang[angle-symbol-over-decimal=true]} % a synomim
% waiting for siunitx extension for h/m/s...
\usepackage{euro}
\newcommand\phour[1]{\hbox{$#1^{\rm h}$}}
\newcommand\pmin[1]{\hbox{$#1^{\rm m}$}}
\def\fsec{$\hbox{.\!\!^{\rm s}$}}
\newcommand*\hms[3]{{%
\EUROFORMAT{main}{\in}%
\EUROFORMAT{in}{\val}%
\EUROFORMAT{EUR}{\form{\,}{\,\fsec}{}\round{-10}}%
\ensuremath{%
\phour{#1}\,\pmin{#2}\,\EURO{EUR}{#3}}}}
\newcommand*{\manualmark}{%
\if@chapter\let\chaptermark\@gobble\fi
\let\sectionmark\@gobble
\let\subsectionmark\@gobble
\let\subsubsectionmark\@gobble
\let\paragraphmark\@gobble
\let\subparagraphmark\@gobble
\let\@mkboth\@gobbletwo
\@automarkfalse
}
%% Define a new 'leo' style for the package that will use a smaller font.
\makeatletter
\def\url@leostyle{%
\@ifundefined{selectfont}{\def\UrlFont{\sf}}{\def\UrlFont{\small\ttfamily}}}
\makeatother
%% Now actually use the newly defined style.
\usepackage{wasysym}
%%\usepackage[a4paper,top=3cm,bottom=3cm,left=3.5cm,right=3.5cm,%
%%bindingoffset=5mm]{geometry}
%%% NOWEB style
\usepackage{noweb}
% the followin nowebstyle (1) options sholud be concatenated
% and separated by only a comma (','):
% shift: Shift text to the left so that long code lines will not extend off
% the right-hand side of the page.
% externalindex: Use an index generated with noindex(1).
% webnumbering: Number chunks consecutively, in WEB style, instead of
% using sub-page numbers.
% longxref: small paragraphs after each chunk, as in Knuth, for chunk
% cross-reference.
% subscriptidents: identifiers in code, including quoted code will be
% subscripted with the chunk number of its definition.
% longchunks: When expanding \nowebchunks, show page numbers of definitions
% and uses of each chunk.
% smallcode: Set code in LaTeX \small font instead of \normalsize.
\noweboptions{externalindex,webnumbering,longxref,longchunks,smallcode}
\usepackage[a4paper,top=3cm,bottom=3cm,left=3.5cm,right=3.5cm,%
bindingoffset=5mm]{geometry}
% for index production
\usepackage{makeidx}
\usepackage{showidx}
\makeindex
%%\usepackage{microtype}
\usepackage{lmodern}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
% include the "ulem" package for strikethrough font
% and strike through like this:
% \sout{Bill Clinton} G.W. Bush is the pres.
\usepackage{ulem}
% drop down initial letter
\usepackage{lettrine}
%\usepackage{appendix}
% figures template
%% \begin{figure}
%% \rule{\textwidth}{0.005in}
%% \begin{center}\framebox{Fee Foe Fi Fum \ldots}\end{center}
%% \caption{A very nice figure indeed}\label{very-nice-figure}
%% \rule{\textwidth}{0.005in}
%% \end{figure}
%% macros
\def\[{\ifhmode\ \fi$[\mkern-2mu[$}
\def\]{$]\mkern-2mu]$}
% to avoid problems in pre_markup substitution...
\def\snippet{\# see lines x-y in file}
\def\nw{\textsc{Noweb}}
\def\py{\textsc{Python}}
\def\cl{\textsc{Common LISP}}
\def\pcc{\textsc{PyCalCal}}
\def\thankstext{I want to thank my wife, Gilda, for the patience
of having looked after all kids and things while I was
\textit{playing} with this project. I also want to thank
Prof.~Reingold for his his prompt reply to all my questions.
Finally my gratitude goes to my parents, Alida and Mario, for the
sacrifice they endevoured in order to allow me get inspired by
Science.}
\title{\textsc{Pycalcal} -- Literate Calendars in \py}
\author{Enrico Spinielli\thanks{\thankstext}}
\usepackage[pdftex]{graphicx}
% hyperref must be the last package to include
\usepackage{hyperref}
\hypersetup{%
pageanchor=true,
plainpages=false,
pdfpagelabels,
pagebackref,
pdfdisplaydoctitle=true,
urlcolor=blue,
linktocpage,
a4paper=true,
colorlinks=true,
breaklinks=true,
pdftex,
pdftitle={Pycalcal - Literate Calendars in Python},
pdfauthor={Enrico Spinielli},
pdfsubject={Calendrical algorithms in Python},
pdfkeywords={calendar, algorithms, python, literate programming},
pdfcreator = {LaTeX with hyperref package},
pdfproducer = {pdfLaTeX}}
\urlstyle{leostyle}
%\setcounter{tocdepth}{0} % indice fino a section
% for code highlight
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{espin}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=espin}
\begin{document}
\maketitle
\cleardoublepage %%% start again on odd page
%
% Table of Contents:
\pagenumbering{roman} %%% Roman page numbers for ToC
\setcounter{page}{1}
\pdfbookmark[1]{Contents}{toc} %%% additional bookmark for ToC
\thispagestyle{plain} %%% uses the above defined fancy
%%% page-header
\tableofcontents
\markboth{Table of Contents}{Table of Contents} %%% for the page
%%% header
\cleardoublepage %%% start again on odd page
\pagenumbering{arabic} %%% from now on Arabic page numbers
\setcounter{page}{1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Literate \rlap{Calendrical Calculations}}
\label{sec:goal}
%\lettrine[lhang=1, nindent=0pt, lines=3]{I}{n}
% \lettrine[lines=3]{T}{his}
This document describes a \py~\cite{computer:language:python}
implementation of the calendrical algorithms described in
the book \textit{Calendrical Calculations}~\cite{calendar:calcal}.
According to the authors, the book is \textit{the companion} text of
the algorithms implemented in the \cl\ package \texttt{CC3}.
The source code for \texttt{CC3}, \texttt{calendrica-3.0.cl}, is made
available electronically by the publisher, see \cite{calendar:calcal}.
I provide full reference to the original \cl\ and credit (and deep
respect) to its authors, Prof.s~Dershowitz and Reingold.
On the (long) way to completing this project, I experimented with
Scons~\cite{scons}, Test-Driven Development~\cite{tdd} and
web applications~\cite{google:appengine}.
I tackled this task the Literate Programming way~\cite{literate:lp}
using the \nw~tool.~\cite{literate:lps, noweb:distro}
As such all code and documentation is generated from
a single source file and prefixed with the following warning:
<<generated code warning>>=
AUTOMATICALLY GENERATED FROM pycalcal.nw: ANY CHANGES WILL BE OVERWRITTEN.
@
\section{Usage and examples}
\label{sec:usage}
This section is about providing some examples of use of \pcc.
\subsection{Gregorian calendar examples}
New year's week day name for (Gregorian) 2021:
\begin{lstlisting}[language=Python]
>>> DAYS_OF_WEEK_NAMES[day_of_week_from_fixed(gregorian_new_year(2021))]
'Friday'
\end{lstlisting}
List Friday 13th in (Gragorian) 2026:
\begin{lstlisting}[language=Python]
>>> for d in unlucky_fridays_in_range(gregorian_year_range(2026)):
... g = gregorian_from_fixed(d)
... print('Friday 13th %s %s' % (GREGORIAN_MONTHS_OF_YEAR_NAMES[g[1]], g[0]))
...
Friday 13th November 2026
Friday 13th March 2026
Friday 13th February 2026
\end{lstlisting}
Pay day, i.e. last Friday of the month, in 2025:
\begin{lstlisting}[language=Python]
>>> for d in unlucky_fridays_in_range(gregorian_year_range(2026)):
... g = gregorian_from_fixed(d)
... print('Friday 13th %s %s' % (GREGORIAN_MONTHS_OF_YEAR_NAMES[g[1]], g[0]))
...
Friday 13th November 2026
Friday 13th March 2026
Friday 13th February 2026
\end{lstlisting}
\subsection{Chinese calendar examples}
\subsection{Ebrew calendar examples}
\subsection{Islamic calendar examples}
\subsection{Civil and religious festivities examples}
\section{Structure}
\label{sec:structure}
The software is for now a single piece of text (a.k.a. a \py~file):
<<*>>=
<<pycalcal.py>>
@ It is organised as follows:
<<pycalcal.py>>=
<<testa>>
<<global import statements>>
<<basic code>>
<<egyptian and armenian calendars>>
<<gregorian calendar>>
<<julian calendar>>
<<iso calendar>>
<<coptic and ethiopic calendars>>
<<ecclesiastical calendars>>
<<islamic calendar>>
<<hebrew calendar>>
<<mayan calendars>>
<<old hindu calendars>>
<<balinese calendar>>
<<time and astronomy>>
<<astronomical lunar calendars>>
<<persian calendar>>
<<bahai calendar>>
<<french revolutionary calendar>>
<<chinese calendar>>
<<modern hindu calendars>>
<<tibetan calendar>>
<<coda>>
@ There is as well a companion file with unit tests inspired by the
examples spread in the book~\cite{calendar:calcal}, its Appendix C or
devised by myself.
<<pycalcaltests.py>>=
# <<generated code warning>>
<<LICENSE>>
from pycalcal import *
from appendixCUnitTest import AppendixCTable1TestCaseBase
from appendixCUnitTest import AppendixCTable2TestCaseBase
from appendixCUnitTest import AppendixCTable3TestCaseBase
from appendixCUnitTest import AppendixCTable4TestCaseBase
from appendixCUnitTest import AppendixCTable5TestCaseBase
import unittest
<<basic code unit test>>
<<egyptian and armenian calendars unit test>>
<<gregorian calendar unit test>>
<<iso calendar unit test>>
<<julian calendar unit test>>
<<coptic and ethiopic calendars unit test>>
<<ecclesiastical calendars unit test>>
<<islamic calendar unit test>>
<<hebrew calendar unit test>>
<<mayan calendars unit test>>
<<old hindu calendars unit test>>
<<balinese calendar unit test>>
<<time and astronomy unit test>>
<<persian calendar unit test>>
<<bahai calendar unit test>>
<<french revolutionary calendar unit test>>
<<chinese calendar unit test>>
<<modern hindu calendars unit test>>
<<tibetan calendar unit test>>
<<astronomical lunar calendars unit test>>
<<execute tests>>
@ The code for tests execution is:
<<execute tests>>=
if __name__ == "__main__":
unittest.main()
@
Given I also want to be able to run a single unit tests part in isolation, i.e.
when working on Persian calendar I just want to run the Persian
calendar's tests, I generate a unit tests file per each part.
Here is an example of how the unit tests are templated for an hypotetical
\texttt{xyzzy} calendar/section:
\begin{verbatim}
@<<xyzzyUnitTest.py>>=
# @<<generated code warning>>
@<<import for testing>>
from appendixCUnitTest import AppendixCTable1TestCaseBase
@<<xyzzy unit test>>
@<<execute tests>>
\end{verbatim}
@ The following imports are to be used:
<<import for testing>>=
from pycalcal import *
import unittest
@
\section{Copyright and Legalise}
\label{sec:copyleft}
My copyright notice is intended to make this work accessible and free
to everybody for any type of use (i.e. commercial, educational
\ldots).
I took an MIT License.
<<LICENSE>>=
# Copyright (c) 2009 Enrico Spinielli
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
@ But remember that Dershowitz and Reingold have Copyrighted their
algorithms!
<<copyright Dershowitz and Reingold>>=
# PLEASE READ THE COPYRIGHT IN THE FILE THAT INSPIRED THIS WORK
# see lines 6-80 in calendrica-3.0.cl
<<testa>>=
"""Python implementation of Dershowitz and Reingold 'Calendrica Calculations'.
Python implementation of calendrical algorithms as described in Common
Lisp in calendrical-3.0.cl (and errata as made available by the authors.)
The companion book is Dershowitz and Reingold 'Calendrica Calculations',
3rd Ed., 2008, Cambridge University Press.
License: MIT License for my work, but read the one
for calendrica-3.0.cl which inspired this work.
Author: Enrico Spinielli
"""
<<LICENSE>>
# <<generated code warning>>
@ The following is where I control the project version number
in a centralised way. The version is number is composed of 3
integers separated by a dot, '.' which stand for
\begin{quote}
@<major version>.<minor version>.<increment>
\end{quote}
@ Then version number \texttt{0.9.2} means revision $2$ of project
version $0.9$.
<<project version>>=
1.0.0
@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{The Calendars}
\label{ch:cals}
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Scaffolding}
\label{sec:scaff}
\lettrine[lines=3]{T}{he} accuracy of the algorthms presented require
definition of constants and calculations that span many bits.
I enable true division feature as in PEP~238~\cite{python:PEP238}
in order to smoothly express simple constants as defined in the \cl\ code,
i.e. \texttt{1/360}
<<global import statements>>=
# use true division
from __future__ import division
@
In order to insure the same precision of computations as in \cl\ code
where numbers are postfixed with \texttt{L0}, meaning 50-bit precision,
I use the \texttt{mpmath} library~\cite{math:multiprecision} and set
the precision accordingly\index{floating-point arithmetic}.
<<global import statements>>=
# Precision in bits, for places where CL postfixes numbers with L0, meaning
# at least 50 bits of precision
from mpmath import *
mp.prec = 50
@
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Basics}
\label{sec:basic}
The following are general definitions, algorithms and helper functions
that will be used to perform a lot of the various calculations for the
subsequent calendars.
@
\subsection{Implementation}
Some computations have meaningless results in certain circumstances,
they will return a predefined value, \texttt{BOGUS}, to mark this case.
<<basic code>>=
################################
# basic calendrical algorithms #
################################
# see lines 244-247 in calendrica-3.0.cl
`BOGUS = 'bogus'
@
Some \cl\ functions are available under other names and/or in
additional packages in \py\ or with a different semantic,
so they are aliased or loaded or (re)defined accordingly.
This is the case for \texttt{quotient}, \texttt{floor} and
\texttt{round}, the \cl\ versions return integers while in
\py\ they can return a float if (at least) one of the arguments
is a float.
<<basic code>>=
# see lines 249-252 in calendrica-3.0.cl
# m // n
# The following
# from operator import floordiv as `quotient
# is not ok, the corresponding CL code
# uses CL 'floor' which always returns an integer
# (the floating point equivalent is 'ffloor'), while
# 'quotient' from operator module (or corresponding //)
# can return a float if at least one of the operands
# is a float...so I redefine it (and 'floor' and 'round' as well: in CL
# they always return an integer.)
def `quotient(m, n):
"""Return the whole part of m/n towards negative infinity."""
return ifloor(m / n)
@ For \texttt{floor} and \texttt{round} I decided to make it
explicit the fact that they return an integer and named
them with a prefixed \textit{i} (for integer):
<<basic code>>=
# I (re)define floor: in CL it always returns an integer.
# I make it explicit the fact it returns an integer by
# naming it ifloor
def `ifloor(n):
"""Return the whole part of m/n."""
from math import floor
return int(floor(n))
# I (re)define round: in CL it always returns an integer.
# I make it explicit the fact it returns an integer by
# naming it iround
def `iround(n):
"""Return the whole part of m/n."""
from builtins import round
return int(round(n))
# m % n (this works as described in book for negative integres)
# It is interesting to note that
# mod(1.5, 1)
# returns the decimal part of 1.5, so 0.5; given a moment 'm'
# mod(m, 1)
# returns the time of the day
from operator import `mod
# see lines 254-257 in calendrica-3.0.cl
def `amod(x, y):
"""Return the same as a % b with b instead of 0."""
return y + (mod(x, -y))
@ The following definitions are a translation in \py\ of \cl\
macros\index{Macro}. Macro definition is a very powerful tool but
it does not exist in the \py\ language.
The principles of the algorithms described in~\cite{calendar:calcal}
is to quickly get an approximation and then refine it to get
the correct result.
\texttt{next} and \texttt{final} are used in the \textit{refine} phase.
<<basic code>>=
# see lines 259-264 in calendrica-3.0.cl
def `next(i, p):
"""Return first integer greater or equal to initial index, i,
such that condition, p, holds."""
return i if p(i) else next(i + 1, p)
<<basic code tests>>=
<<test next>>
<<test next>>=
def testNext(self):
self.assertEqual(next(0, lambda i: i == 3), 3)
self.assertEqual(next(0, lambda i: i == 0), 0)
<<basic code>>=
# see lines 266-271 in calendrica-3.0.cl
def `final(i, p):
"""Return last integer greater or equal to initial index, i,
such that condition, p, holds."""
return i - 1 if not p(i) else final(i + 1, p)
<<basic code tests>>=
<<test final>>
<<test final>>=
def `testFinal(self):
self.assertEqual(final(0, lambda i: i == 3), -1)
self.assertEqual(final(0, lambda i: i < 3), 2)
self.assertEqual(final(0, lambda i: i < 0), -1)
@
The following functions are used mainly in the astronomical algorithms
in order to evaluate polynomial approximations of equations of motion.
<<basic code>>=
# see lines 273-281 in calendrica-3.0.cl
def `summa(f, k, p):
"""Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0.
This is a tail recursive implementation."""
return 0 if not p(k) else f(k) + summa(f, k + 1, p)
def `altsumma(f, k, p):
"""Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0.
This is an implementation of the Summation formula from Kahan,
see Theorem 8 in Goldberg, David 'What Every Computer Scientist
Should Know About Floating-Point Arithmetic', ACM Computer Survey,
Vol. 23, No. 1, March 1991."""
if not p(k):
return 0
else:
S = f(k)
C = 0
j = k + 1
while p(j):
Y = f(j) - C
T = S + Y
C = (T - S) - Y
S = T
j += 1
return S
<<basic code tests>>=
<<test summa>>
<<test summa>>=
def `testSumma(self):
self.assertEqual(summa(lambda x: 1, 1, lambda i: i<=4), 4)
self.assertEqual(summa(lambda x: 1, 0, lambda i: i>=4), 0)
self.assertEqual(summa(lambda x: x**2, 1, lambda i: i<=4), 30)
def `testAltSumma(self):
# I should add more tests with floating point arithmetic...
self.assertEqual(altsumma(lambda x: 1.0, 1, lambda i: i<=4), 4)
self.assertEqual(altsumma(lambda x: 1.0, 0, lambda i: i>=4), 0)
self.assertEqual(altsumma(lambda x: x**2, 1, lambda i: i<=4), 30)
@
\texttt{binary\_search} is looking for a value of a function within an
interval given a precision criteria to satify.
<<basic code>>=
# see lines 283-293 in calendrica-3.0.cl
def `binary_search(lo, hi, p, e):
"""Bisection search for x in [lo, hi] such that condition 'e' holds.
p determines when to go left."""
x = (lo + hi) / 2
if p(lo, hi):
return x
elif e(x):
return binary_search(lo, x, p, e)
else:
return binary_search(x, hi, p, e)
<<basic code tests>>=
<<test binary search>>
<<test binary search>>=
def `testBinarySearch(self):
fminusy = lambda x, y: fx(x) - y
p = lambda a, b: abs(fminusy(0.5 * (a+b), y)) <= 10**-5
e = lambda x: fminusy(x, y) >= 0
# function y = f(x), f(x) = x, y0 = 1.0; solution is x0 = 1.0
fx = lambda x: x
y = 1.0
x0 = 1.0
self.assertTrue(binary_search(0.0, 3.1, p, e) - x0 <= 10 ** -5)
# new function y = f(x), f(x) = x**2 - 4*x + 4, y0 = 0.0; solution x0=2.0
y = 0.0
x0 = 2.0
fx = lambda x: x**2 -4 * x + 4.0
self.assertTrue(binary_search(1.5, 2.5, p, e) - x0 <= 10 ** -5)
<<basic code>>=
# see lines 295-302 in calendrica-3.0.cl
def `invert_angular(f, y, a, b, prec=10 ** -5):
"""Find inverse of angular function 'f' at 'y' within interval [a,b].
Default precision is 0.00001"""
return binary_search(a, b,
(lambda l, h: ((h - l) <= prec)),
(lambda x: mod((f(x) - y), 360) < 180))
#def `invert_angular(f, y, a, b):
# from scipy.optimize import brentq
# return(brentq((lambda x: mod(f(x) - y), 360)), a, b, xtol=error)
<<basic code tests>>=
<<test invert angular>>
<<test invert angular>>=
def `testInvertAngular(self):
from math import tan, radians
# find angle theta such that tan(theta) = 1
# assert that theta - pi/4 <= 10**-5
self.assertTrue(invert_angular(tan,
1.0,
0,
radians(60.0)) - radians(45.0) <= 10**-5)
@
\texttt{sigma} is used expecially for astronomical formulas in order
to go thru tables of value, see~\ref{sec:astro}.
This implementation is really horrible...but I will not touch it untill I will
have time and courage to go thru understanding it again!
<<basic code>>=
# see lines 304-313 in calendrica-3.0.cl
def `sigma(l, b):
"""Return the sum of body 'b' for indices i1..in
running simultaneously thru lists l1..ln.
List 'l' is of the form [[i1 l1]..[in ln]]"""
# 'l' is a list of 'n' lists of the same lenght 'L' [l1, l2, l3, ...]
# 'b' is a lambda with 'n' args
# 'sigma' sums all 'L' applications of 'b' to the relevant tuple of args
# >>> a = [ 1, 2, 3, 4]
# >>> b = [ 5, 6, 7, 8]
# >>> c = [ 9,10,11,12]
# >>> l = [a,b,c]
# >>> z = zip(*l)
# >>> z
# [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
# >>> b = lambda x, y, z: x * y * z
# >>> b(*z[0]) # apply b to first elem of i
# 45
# >>> temp = []
# >>> z = zip(*l)
# >>> for e in z: temp.append(b(*e))
# >>> temp
# [45, 120, 231, 384]
# >>> from operator import add
# >>> reduce(add, temp)
# 780
return sum(b(*e) for e in zip(*l))
<<basic code tests>>=
<<test sigma>>
<<test sigma>>=
def `testSigma(self):
a = [ 1, 2, 3, 4]
b = [ 5, 6, 7, 8]
c = [ 9,10,11,12]
ell = [a,b,c]
bi = lambda x, y, z: x * y * z
self.assertEqual(sigma(ell, bi), 780)
<<basic code>>=
# see lines 315-321 in calendrica-3.0.cl
from copy import copy
def `poly(x, a):
"""Calculate polynomial with coefficients 'a' at point x.
The polynomial is a[0] + a[1] * x + a[2] * x^2 + ...a[n-1]x^(n-1)
the result is
a[0] + x(a[1] + x(a[2] +...+ x(a[n-1])...)"""
# This implementation is also known as Horner's Rule.
n = len(a) - 1
p = a[n]
for i in range(1, n+1):
p = p * x + a[n-i]
return p
<<basic code tests>>=
<<test poly>>
<<test poly>>=
def `testPoly(self):
self.assertEqual(poly(0, [2, 2, 1]), 2)
self.assertEqual(poly(1, [2, 2, 1]), 5)
@
Now it is time to begin with calendars: let's define the instant in
time when time is counted from:
%'
<<basic code>>=
# see lines 323-329 in calendrica-3.0.cl
# Epoch definition. I took it out explicitly from rd().
def `epoch():
"""Epoch definition. For Rata Diem, R.D., it is 0 (but any other reference
would do.)"""
return 0
def `rd(tee):
"""Return rata diem (number of days since epoch) of moment in time, tee."""
return tee - epoch()
@ And here are some other basilar (and arbitrary) definitions: days of the
week, date and time data structures.
The days of the week constants are defined
as constants from $1$ to $7$, where Sunday is (arbitrarily) assigned $0$.
<<basic code>>=
# see lines 331-334 in calendrica-3.0.cl
`SUNDAY = 0
# see lines 10-15 in calendrica-3.0.errata.cl
`MONDAY = 1
# see lines 17-20 in calendrica-3.0.errata.cl
`TUESDAY = 2
# see lines 22-25 in calendrica-3.0.errata.cl
`WEDNESDAY = 3
# see lines 27-30 in calendrica-3.0.errata.cl
`THURSDAY = 4
# see lines 32-35 in calendrica-3.0.errata.cl
`FRIDAY = 5
# see lines 37-40 in calendrica-3.0.errata.cl
`SATURDAY = SUNDAY + 6
DAYS_OF_WEEK_NAMES = {
SUNDAY : "Sunday",
MONDAY : "Monday",
TUESDAY : "Tuesday",
WEDNESDAY : "Wednesday",
THURSDAY : "Thursday",
FRIDAY : "Friday",
SATURDAY : "Saturday"}
# see lines 366-369 in calendrica-3.0.cl
def `day_of_week_from_fixed(date):
"""Return day of the week from a fixed date 'date'."""
return mod(date - rd(0) - SUNDAY, 7)
<<basic code>>=
# see lines 371-374 in calendrica-3.0.cl
def `standard_month(date):
"""Return the month of date 'date'."""
return date[1]
# see lines 376-379 in calendrica-3.0.cl
def `standard_day(date):
"""Return the day of date 'date'."""
return date[2]
# see lines 381-384 in calendrica-3.0.cl
def `standard_year(date):
"""Return the year of date 'date'."""
return date[0]
# see lines 386-388 in calendrica-3.0.cl
def `time_of_day(hour, minute, second):
"""Return the time of day data structure."""
return [hour, minute, second]
# see lines 390-392 in calendrica-3.0.cl
def `hour(clock):
"""Return the hour of clock time 'clock'."""
return clock[0]
# see lines 394-396 in calendrica-3.0.cl
def `minute(clock):
"""Return the minutes of clock time 'clock'."""
return clock[1]
# see lines 398-400 in calendrica-3.0.cl
def `seconds(clock):
"""Return the seconds of clock time 'clock'."""
return clock[2]
@ The following functions convert from moment to fixed date,
extract the time of the day from a moment.
<<basic code>>=
# see lines 402-405 in calendrica-3.0.cl
def `fixed_from_moment(tee):
"""Return fixed date from moment 'tee'."""
return ifloor(tee)
# see lines 407-410 in calendrica-3.0.cl
def `time_from_moment(tee):
"""Return time from moment 'tee'."""
return mod(tee, 1)
# see lines 412-419 in calendrica-3.0.cl
def `clock_from_moment(tee):
"""Return clock time hour:minute:second from moment 'tee'."""
time = time_from_moment(tee)
hour = ifloor(time * 24)
minute = ifloor(mod(time * 24 * 60, 60))
second = mod(time * 24 * 60 * 60, 60)
return time_of_day(hour, minute, second)
<<basic code tests>>=
<<test clock from moment>>
<<test clock from moment>>=
def `testClockFromMoment(self):
c = clock_from_moment(3.5)
self.assertEqual(hour(c), 12)
self.assertEqual(minute(c), 0)
self.assertAlmostEqual(seconds(c), 0, 2)
c = clock_from_moment(3.75)
self.assertEqual(hour(c), 18)
self.assertEqual(minute(c), 0)
self.assertAlmostEqual(seconds(c), 0, 2)
c = clock_from_moment(3.8)
self.assertEqual(hour(c), 19)
self.assertEqual(minute(c), 11)
self.assertAlmostEqual(seconds(c), 59.9999, 2)
<<basic code>>=
# see lines 421-427 in calendrica-3.0.cl
def `time_from_clock(hms):
"""Return time of day from clock time 'hms'."""
h = hour(hms)
m = minute(hms)
s = seconds(hms)
return(1/24 * (h + ((m + (s / 60)) / 60)))
<<basic code tests>>=
<<test time from clock>>
<<test time from clock>>=
def `testTimeFromClock(self):
self.assertAlmostEqual(time_from_clock([12, 0, 0]), 0.5, 2)
self.assertAlmostEqual(time_from_clock([18, 0, 0]), 0.75, 2)
self.assertAlmostEqual(time_from_clock([19, 12, 0]), 0.8, 2)
@ Here we define the angular data structure and relative helper
functions.
<<basic code>>=
# see lines 429-431 in calendrica-3.0.cl
def `degrees_minutes_seconds(d, m, s):
"""Return the angular data structure."""
return [d, m, s]
# see lines 433-440 in calendrica-3.0.cl
def `angle_from_degrees(alpha):
"""Return an angle in degrees:minutes:seconds from angle,
'alpha' in degrees."""
d = ifloor(alpha)
m = ifloor(60 * mod(alpha, 1))
s = mod(alpha * 60 * 60, 60)
return degrees_minutes_seconds(d, m, s)
@
These helper functions are used to deal with intervals and ranges of events:
<<basic code>>=
# see lines 502-510 in calendrica-3.0.cl
def `list_range(ell, range):
"""Return those moments in list ell that occur in range 'range'."""
return list(filter(lambda x: is_in_range(x, range), ell))
# see lines 482-485 in calendrica-3.0.cl
def `interval(t0, t1):
"""Return the range data structure."""
return [t0, t1]
# see lines 487-490 in calendrica-3.0.cl
def `start(range):
"""Return the start of range 'range'."""
return range[0]
# see lines 492-495 in calendrica-3.0.cl
def `end(range):
"""Return the end of range 'range'."""
return range[1]
# see lines 497-500 in calendrica-3.0.cl
def `is_in_range(tee, range):
"""Return True if moment 'tee' falls within range 'range',
False otherwise."""
return start(range) <= tee <= end(range)
@
Julian days are of basic importance expecially in Astronomy.
<<basic code>>=
# see lines 442-445 in calendrica-3.0.cl
`JD_EPOCH = rd(mpf(-1721424.5))
# see lines 447-450 in calendrica-3.0.cl
def `moment_from_jd(jd):
"""Return the moment corresponding to the Julian day number 'jd'."""
return jd + JD_EPOCH
# see lines 452-455 in calendrica-3.0.cl
def `jd_from_moment(tee):
"""Return the Julian day number corresponding to moment 'tee'."""
return tee - JD_EPOCH
# see lines 457-460 in calendrica-3.0.cl
def `fixed_from_jd(jd):
"""Return the fixed date corresponding to Julian day number 'jd'."""
return ifloor(moment_from_jd(jd))
# see lines 462-465 in calendrica-3.0.cl
def `jd_from_fixed(date):
"""Return the Julian day number corresponding to fixed date 'rd'."""
return jd_from_moment(date)