swisseph-wasm 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
1
+ # SwissEph Examples
2
+
3
+ This directory contains practical examples demonstrating how to use the SwissEph WebAssembly library for various astronomical and astrological calculations.
4
+
5
+ ## Examples Overview
6
+
7
+ ### 1. `basic-usage.js`
8
+ Fundamental operations and core functionality:
9
+ - Basic planetary position calculations
10
+ - Multiple planet calculations
11
+ - Time zone handling
12
+ - Sidereal vs tropical comparisons
13
+ - Date conversion functions
14
+ - Degree utilities
15
+ - Library information
16
+
17
+ **Run with:**
18
+ ```bash
19
+ node examples/basic-usage.js
20
+ ```
21
+
22
+ ### 2. `birth-chart.js`
23
+ Complete birth chart calculation system:
24
+ - Full birth chart calculator class
25
+ - Planetary positions with zodiac signs
26
+ - House calculations
27
+ - Additional astrological points (nodes, Lilith, Chiron)
28
+ - Aspect calculations
29
+ - Professional-grade chart interpretation
30
+
31
+ **Run with:**
32
+ ```bash
33
+ node examples/birth-chart.js
34
+ ```
35
+
36
+ ### 3. `advanced-features.js` *(Coming Soon)*
37
+ Advanced astronomical calculations:
38
+ - Eclipse predictions
39
+ - Rise/set/transit times
40
+ - Fixed star positions
41
+ - Topocentric calculations
42
+ - Atmospheric refraction
43
+ - Coordinate transformations
44
+
45
+ ### 4. `web-integration.js` *(Coming Soon)*
46
+ Browser integration examples:
47
+ - HTML/JavaScript integration
48
+ - Real-time calculations
49
+ - Interactive charts
50
+ - Performance optimization
51
+ - Error handling in web environments
52
+
53
+ ## Quick Start
54
+
55
+ ### Basic Planetary Position
56
+ ```javascript
57
+ import SwissEph from '../src/swisseph.js';
58
+
59
+ const swe = new SwissEph();
60
+ await swe.initSwissEph();
61
+
62
+ const jd = swe.julday(2023, 6, 15, 12.0);
63
+ const sunPos = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH);
64
+
65
+ console.log(`Sun longitude: ${sunPos[0]}°`);
66
+ swe.close();
67
+ ```
68
+
69
+ ### Birth Chart Calculation
70
+ ```javascript
71
+ import { BirthChartCalculator } from './examples/birth-chart.js';
72
+
73
+ const calculator = new BirthChartCalculator();
74
+
75
+ const chart = await calculator.calculateBirthChart({
76
+ year: 1990, month: 5, day: 15,
77
+ hour: 14, minute: 30, timezone: -5,
78
+ latitude: 40.7128, longitude: -74.0060
79
+ });
80
+
81
+ console.log(chart.planets);
82
+ calculator.destroy();
83
+ ```
84
+
85
+ ## Example Output
86
+
87
+ ### Basic Planetary Positions
88
+ ```
89
+ === Basic Planetary Position ===
90
+ Julian Day: 2460110.0
91
+ Sun Position:
92
+ Longitude: 84.123456°
93
+ Latitude: 0.000123°
94
+ Distance: 1.015678 AU
95
+ Speed: 0.958765°/day
96
+ Zodiac: 24.12° Gemini
97
+ ```
98
+
99
+ ### Birth Chart
100
+ ```
101
+ PLANETARY POSITIONS:
102
+ ===================
103
+ ☉ Sun : 24.12° Taurus (54.12°)
104
+ ☽ Moon : 15.67° Scorpio (225.67°)
105
+ ☿ Mercury : 8.45° Gemini (68.45°)
106
+ ♀ Venus : 2.89° Cancer (92.89°)
107
+ ♂ Mars : 18.34° Virgo (168.34°)
108
+ ♃ Jupiter : 12.78° Pisces (342.78°)
109
+ ♄ Saturn : 25.91° Capricorn (295.91°)
110
+ ♅ Uranus : 7.23° Capricorn (277.23°)
111
+ ♆ Neptune : 11.45° Capricorn (281.45°)
112
+ ♇ Pluto : 16.78° Scorpio (226.78°)
113
+
114
+ MAJOR ASPECTS:
115
+ ==============
116
+ Sun ☌ Mercury: Conjunction (orb: 2.34°)
117
+ Moon ☍ Venus: Opposition (orb: 3.21°)
118
+ Mars △ Jupiter: Trine (orb: 1.87°)
119
+ ```
120
+
121
+ ## Common Patterns
122
+
123
+ ### Error Handling
124
+ ```javascript
125
+ async function safeCalculation() {
126
+ let swe = null;
127
+ try {
128
+ swe = new SwissEph();
129
+ await swe.initSwissEph();
130
+ // calculations here
131
+ return result;
132
+ } catch (error) {
133
+ console.error('Calculation failed:', error);
134
+ return null;
135
+ } finally {
136
+ if (swe) swe.close();
137
+ }
138
+ }
139
+ ```
140
+
141
+ ### Batch Processing
142
+ ```javascript
143
+ async function calculateMultipleDates(dates) {
144
+ const swe = new SwissEph();
145
+ await swe.initSwissEph();
146
+
147
+ const results = [];
148
+ for (const date of dates) {
149
+ const jd = swe.julday(date.year, date.month, date.day, date.hour);
150
+ const pos = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH);
151
+ results.push({ date, position: pos[0] });
152
+ }
153
+
154
+ swe.close();
155
+ return results;
156
+ }
157
+ ```
158
+
159
+ ### Reusable Calculator Class
160
+ ```javascript
161
+ class AstrologyCalculator {
162
+ constructor() {
163
+ this.swe = null;
164
+ this.initialized = false;
165
+ }
166
+
167
+ async init() {
168
+ if (!this.initialized) {
169
+ this.swe = new SwissEph();
170
+ await this.swe.initSwissEph();
171
+ this.initialized = true;
172
+ }
173
+ }
174
+
175
+ async calculate(params) {
176
+ await this.init();
177
+ // calculations here
178
+ }
179
+
180
+ destroy() {
181
+ if (this.swe) {
182
+ this.swe.close();
183
+ this.swe = null;
184
+ this.initialized = false;
185
+ }
186
+ }
187
+ }
188
+ ```
189
+
190
+ ## Running Examples
191
+
192
+ ### Prerequisites
193
+ - Node.js 14+ or modern browser
194
+ - ES6 modules support
195
+
196
+ ### Command Line
197
+ ```bash
198
+ # Run basic usage examples
199
+ node examples/basic-usage.js
200
+
201
+ # Run birth chart example
202
+ node examples/birth-chart.js
203
+
204
+ # Run specific function
205
+ node -e "import('./examples/basic-usage.js').then(m => m.basicPlanetaryPosition())"
206
+ ```
207
+
208
+ ### Browser
209
+ ```html
210
+ <script type="module">
211
+ import { runAllExamples } from './examples/basic-usage.js';
212
+ runAllExamples();
213
+ </script>
214
+ ```
215
+
216
+ ## Tips for Development
217
+
218
+ 1. **Always initialize**: Call `await swe.initSwissEph()` before calculations
219
+ 2. **Clean up**: Always call `swe.close()` when done
220
+ 3. **Handle time zones**: Convert to UTC before calculations
221
+ 4. **Validate inputs**: Check date ranges and parameter validity
222
+ 5. **Use constants**: Use library constants instead of magic numbers
223
+ 6. **Batch operations**: Reuse SwissEph instance for multiple calculations
224
+ 7. **Error handling**: Wrap calculations in try-catch blocks
225
+
226
+ ## Performance Considerations
227
+
228
+ - Initialize once, calculate many times
229
+ - Use appropriate calculation flags
230
+ - Clean up resources properly
231
+ - Consider WebWorkers for heavy calculations
232
+ - Cache results when appropriate
233
+
234
+ ## Further Reading
235
+
236
+ - [Main Documentation](../DOCUMENTATION.md)
237
+ - [Quick Reference](../QUICK_REFERENCE.md)
238
+ - [Test Suite](../tests/README.md)
239
+ - [Swiss Ephemeris Documentation](https://www.astro.com/swisseph/swephprg.htm)
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Basic Usage Examples for SwissEph Library
3
+ *
4
+ * This file demonstrates fundamental operations with the Swiss Ephemeris
5
+ * WebAssembly library including planetary calculations, time conversions,
6
+ * and coordinate transformations.
7
+ */
8
+
9
+ import SwissEph from '../src/swisseph.js';
10
+
11
+ /**
12
+ * Example 1: Basic Planetary Position Calculation
13
+ * Calculates the position of the Sun for a specific date and time
14
+ */
15
+ async function basicPlanetaryPosition() {
16
+ console.log('=== Basic Planetary Position ===');
17
+
18
+ const swe = new SwissEph();
19
+ await swe.initSwissEph();
20
+
21
+ try {
22
+ // Calculate Julian Day for June 15, 2023, 12:00 UTC
23
+ const jd = swe.julday(2023, 6, 15, 12.0);
24
+ console.log(`Julian Day: ${jd}`);
25
+
26
+ // Calculate Sun position
27
+ const sunPosition = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH);
28
+
29
+ console.log(`Sun Position:`);
30
+ console.log(` Longitude: ${sunPosition[0].toFixed(6)}°`);
31
+ console.log(` Latitude: ${sunPosition[1].toFixed(6)}°`);
32
+ console.log(` Distance: ${sunPosition[2].toFixed(6)} AU`);
33
+ console.log(` Speed: ${sunPosition[3].toFixed(6)}°/day`);
34
+
35
+ // Convert longitude to zodiac sign
36
+ const sign = Math.floor(sunPosition[0] / 30);
37
+ const degree = sunPosition[0] % 30;
38
+ const signs = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo',
39
+ 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces'];
40
+
41
+ console.log(` Zodiac: ${degree.toFixed(2)}° ${signs[sign]}`);
42
+
43
+ } finally {
44
+ swe.close();
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Example 2: Multiple Planet Calculation
50
+ * Calculates positions for all major planets
51
+ */
52
+ async function multiplePlanets() {
53
+ console.log('\n=== Multiple Planet Positions ===');
54
+
55
+ const swe = new SwissEph();
56
+ await swe.initSwissEph();
57
+
58
+ try {
59
+ const jd = swe.julday(2023, 6, 15, 12.0);
60
+
61
+ const planets = [
62
+ { id: swe.SE_SUN, name: 'Sun' },
63
+ { id: swe.SE_MOON, name: 'Moon' },
64
+ { id: swe.SE_MERCURY, name: 'Mercury' },
65
+ { id: swe.SE_VENUS, name: 'Venus' },
66
+ { id: swe.SE_MARS, name: 'Mars' },
67
+ { id: swe.SE_JUPITER, name: 'Jupiter' },
68
+ { id: swe.SE_SATURN, name: 'Saturn' },
69
+ { id: swe.SE_URANUS, name: 'Uranus' },
70
+ { id: swe.SE_NEPTUNE, name: 'Neptune' },
71
+ { id: swe.SE_PLUTO, name: 'Pluto' }
72
+ ];
73
+
74
+ console.log('Planet Positions for June 15, 2023:');
75
+
76
+ for (const planet of planets) {
77
+ const position = swe.calc_ut(jd, planet.id, swe.SEFLG_SWIEPH);
78
+ console.log(`${planet.name.padEnd(10)}: ${position[0].toFixed(2)}°`);
79
+ }
80
+
81
+ } finally {
82
+ swe.close();
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Example 3: Time Zone Conversion
88
+ * Demonstrates proper handling of time zones
89
+ */
90
+ async function timeZoneExample() {
91
+ console.log('\n=== Time Zone Conversion ===');
92
+
93
+ const swe = new SwissEph();
94
+ await swe.initSwissEph();
95
+
96
+ try {
97
+ // Birth time: May 15, 1990, 2:30 PM in New York (UTC-5)
98
+ const year = 1990;
99
+ const month = 5;
100
+ const day = 15;
101
+ const hour = 14; // 2 PM
102
+ const minute = 30;
103
+ const timezone = -5; // UTC-5 (Eastern Daylight Time)
104
+
105
+ // Convert to UTC
106
+ const utcHour = hour + minute / 60 - timezone;
107
+ const jd = swe.julday(year, month, day, utcHour);
108
+
109
+ console.log(`Local time: ${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour}:${minute.toString().padStart(2, '0')} (UTC${timezone})`);
110
+ console.log(`UTC time: ${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${utcHour.toFixed(2)}`);
111
+ console.log(`Julian Day: ${jd}`);
112
+
113
+ // Calculate Sun position for this time
114
+ const sunPos = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH);
115
+ console.log(`Sun position: ${sunPos[0].toFixed(2)}°`);
116
+
117
+ } finally {
118
+ swe.close();
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Example 4: Sidereal vs Tropical Comparison
124
+ * Shows the difference between tropical and sidereal calculations
125
+ */
126
+ async function siderealVsTropical() {
127
+ console.log('\n=== Sidereal vs Tropical Comparison ===');
128
+
129
+ const swe = new SwissEph();
130
+ await swe.initSwissEph();
131
+
132
+ try {
133
+ const jd = swe.julday(2023, 6, 15, 12.0);
134
+
135
+ // Tropical calculation (default)
136
+ const tropical = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH);
137
+
138
+ // Set Lahiri ayanamsa for sidereal calculation
139
+ swe.set_sid_mode(swe.SE_SIDM_LAHIRI, 0, 0);
140
+
141
+ // Sidereal calculation
142
+ const sidereal = swe.calc_ut(jd, swe.SE_SUN, swe.SEFLG_SWIEPH | swe.SEFLG_SIDEREAL);
143
+
144
+ // Get ayanamsa value
145
+ const ayanamsa = swe.get_ayanamsa(jd);
146
+
147
+ console.log(`Tropical Sun position: ${tropical[0].toFixed(6)}°`);
148
+ console.log(`Sidereal Sun position: ${sidereal[0].toFixed(6)}°`);
149
+ console.log(`Ayanamsa (Lahiri): ${ayanamsa.toFixed(6)}°`);
150
+ console.log(`Difference: ${(tropical[0] - sidereal[0]).toFixed(6)}°`);
151
+
152
+ } finally {
153
+ swe.close();
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Example 5: Date Conversion Functions
159
+ * Demonstrates various date and time conversion utilities
160
+ */
161
+ async function dateConversions() {
162
+ console.log('\n=== Date Conversion Functions ===');
163
+
164
+ const swe = new SwissEph();
165
+ await swe.initSwissEph();
166
+
167
+ try {
168
+ // Calculate Julian Day
169
+ const jd = swe.julday(2023, 6, 15, 12.5);
170
+ console.log(`Julian Day for 2023-06-15 12:30: ${jd}`);
171
+
172
+ // Convert back to calendar date
173
+ const date = swe.revjul(jd, swe.SE_GREG_CAL);
174
+ console.log(`Reverse conversion: ${date.year}-${date.month}-${date.day} ${date.hour.toFixed(2)}`);
175
+
176
+ // UTC to Julian Day conversion
177
+ const utcResult = swe.utc_to_jd(2023, 6, 15, 12, 30, 0, swe.SE_GREG_CAL);
178
+ console.log(`UTC to JD - ET: ${utcResult.julianDayET}, UT: ${utcResult.julianDayUT}`);
179
+
180
+ // Calculate sidereal time
181
+ const sidTime = swe.sidtime(jd);
182
+ console.log(`Sidereal time: ${sidTime.toFixed(6)} hours`);
183
+
184
+ // Calculate Delta T
185
+ const deltaT = swe.deltat(jd);
186
+ console.log(`Delta T: ${deltaT.toFixed(2)} seconds`);
187
+
188
+ // Day of week
189
+ const dayOfWeek = swe.day_of_week(jd);
190
+ const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
191
+ console.log(`Day of week: ${days[dayOfWeek]}`);
192
+
193
+ } finally {
194
+ swe.close();
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Example 6: Degree Utilities
200
+ * Shows how to work with degree values and conversions
201
+ */
202
+ async function degreeUtilities() {
203
+ console.log('\n=== Degree Utilities ===');
204
+
205
+ const swe = new SwissEph();
206
+ await swe.initSwissEph();
207
+
208
+ try {
209
+ const degrees = 123.456789;
210
+
211
+ // Normalize degrees
212
+ console.log(`Original: ${degrees}°`);
213
+ console.log(`Normalized: ${swe.degnorm(degrees)}°`);
214
+ console.log(`Normalized (370°): ${swe.degnorm(370)}°`);
215
+ console.log(`Normalized (-10°): ${swe.degnorm(-10)}°`);
216
+
217
+ // Split degrees into components
218
+ const split = swe.split_deg(degrees, swe.SE_SPLIT_DEG_ROUND_SEC);
219
+ console.log(`Split degrees:`);
220
+ console.log(` Degrees: ${split.degree}°`);
221
+ console.log(` Minutes: ${split.min}'`);
222
+ console.log(` Seconds: ${split.second.toFixed(0)}"`);
223
+ console.log(` Zodiac sign: ${split.sign} (0=Aries, 1=Taurus, etc.)`);
224
+
225
+ // Zodiacal format
226
+ const zodiacal = swe.split_deg(degrees, swe.SE_SPLIT_DEG_ZODIACAL);
227
+ const signs = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo',
228
+ 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces'];
229
+ console.log(`Zodiacal: ${zodiacal.degree}° ${zodiacal.min}' ${zodiacal.second.toFixed(0)}" ${signs[zodiacal.sign]}`);
230
+
231
+ } finally {
232
+ swe.close();
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Example 7: Library Information
238
+ * Shows how to get version and other library information
239
+ */
240
+ async function libraryInfo() {
241
+ console.log('\n=== Library Information ===');
242
+
243
+ const swe = new SwissEph();
244
+ await swe.initSwissEph();
245
+
246
+ try {
247
+ // Get version
248
+ const version = swe.version();
249
+ console.log(`Swiss Ephemeris version: ${version}`);
250
+
251
+ // Get planet names
252
+ console.log('\nPlanet names:');
253
+ for (let i = 0; i <= 9; i++) {
254
+ const name = swe.get_planet_name(i);
255
+ console.log(` ${i}: ${name}`);
256
+ }
257
+
258
+ // Show some constants
259
+ console.log('\nImportant constants:');
260
+ console.log(` AU to km: ${swe.SE_AUNIT_TO_KM}`);
261
+ console.log(` AU to light-year: ${swe.SE_AUNIT_TO_LIGHTYEAR}`);
262
+ console.log(` AU to parsec: ${swe.SE_AUNIT_TO_PARSEC}`);
263
+
264
+ } finally {
265
+ swe.close();
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Run all examples
271
+ */
272
+ async function runAllExamples() {
273
+ console.log('SwissEph Basic Usage Examples\n');
274
+
275
+ await basicPlanetaryPosition();
276
+ await multiplePlanets();
277
+ await timeZoneExample();
278
+ await siderealVsTropical();
279
+ await dateConversions();
280
+ await degreeUtilities();
281
+ await libraryInfo();
282
+
283
+ console.log('\n=== All examples completed ===');
284
+ }
285
+
286
+ // Export functions for use in other modules
287
+ export {
288
+ basicPlanetaryPosition,
289
+ multiplePlanets,
290
+ timeZoneExample,
291
+ siderealVsTropical,
292
+ dateConversions,
293
+ degreeUtilities,
294
+ libraryInfo,
295
+ runAllExamples
296
+ };
297
+
298
+ // Run examples if this file is executed directly
299
+ if (import.meta.url === `file://${process.argv[1]}`) {
300
+ runAllExamples().catch(console.error);
301
+ }