Skip to content

Module airball.stars

The following documentation was automatically generated from the docstrings.

airball.stars.Star

This is the AIRBALL Star class. It encapsulates the relevant parameters for a given star. Only the mass is a quantity intrinsic to the object. The impact parameter, velocity, inclination, argument of periastron, and longitude of the ascending node quantities are defined with respect to the host star and plane passing through the star.

Parameters:

Name Type Description Default
m float

The mass of the star. Default units are in solMass.

required
b float

The impact parameter of the star. Default units are in AU.

required
v float

The velocity at infinity of the star. Default units are in km/s.

required
inc float

The inclination of the star. Default units are in radians.

'isotropic'
omega float

The argument of the periastron of the star. Default units are in radians.

'isotropic'
Omega float

The longitude of the ascending node of the star. Default units are in radians.

'isotropic'
UNIT_SYSTEM list

The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].

[]

Attributes:

Name Type Description
m Quantity

The mass of the star. Default units are in solMass.

b Quantity

The impact parameter of the star. Default units are in AU.

v Quantity

The velocity at infinity of the star. Default units are in km/s.

inc Quantity

The inclination of the star. Default units are in radians.

omega Quantity

The argument of the periastron of the star. Default units are in radians.

Omega Quantity

The longitude of the ascending node of the star. Default units are in radians.

units UnitSet

The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].

impulse_gradient Quantity

The impulse gradient of the star. Default units are in km/s/AU.

params list

A list of the parameters of the star in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

param_values list

A list of the values of the parameters of the star in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

Examples:

import airball

star = airball.Star(m=1.0, b=1.0, v=1.0, inc=0.0, omega=0.0, Omega=0.0)
import airball

star = airball.Star(m=1.0, b=1.0, v=1.0, inc="isotropic", omega="isotropic", Omega="isotropic")
import airball

star = airball.Star(m=1.0, b=1.0, v=1.0)
Source code in src/airball/stars.py
 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
class Star:
    """
    This is the AIRBALL Star class.
    It encapsulates the relevant parameters for a given star. Only the mass is a quantity intrinsic to the object. The impact parameter, velocity, inclination, argument of periastron, and longitude of the ascending node quantities are defined with respect to the host star and plane passing through the star.

    Args:
      m (float): The mass of the star. Default units are in solMass.
      b (float): The impact parameter of the star. Default units are in AU.
      v (float): The velocity at infinity of the star. Default units are in km/s.
      inc (float, optional): The inclination of the star. Default units are in radians.
      omega (float, optional): The argument of the periastron of the star. Default units are in radians.
      Omega (float, optional): The longitude of the ascending node of the star. Default units are in radians.
      UNIT_SYSTEM (list, optional): The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].

    Attributes:
      m (astropy.units.Quantity): The mass of the star. Default units are in solMass.
      b (astropy.units.Quantity): The impact parameter of the star. Default units are in AU.
      v (astropy.units.Quantity): The velocity at infinity of the star. Default units are in km/s.
      inc (astropy.units.Quantity): The inclination of the star. Default units are in radians.
      omega (astropy.units.Quantity): The argument of the periastron of the star. Default units are in radians.
      Omega (astropy.units.Quantity): The longitude of the ascending node of the star. Default units are in radians.
      units (airball.tools.UnitSet): The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].
      impulse_gradient (astropy.units.Quantity): The impulse gradient of the star. Default units are in km/s/AU.
      params (list): A list of the parameters of the star in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.
      param_values (list): A list of the values of the parameters of the star in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

    Examples:
      ```python
      import airball

      star = airball.Star(m=1.0, b=1.0, v=1.0, inc=0.0, omega=0.0, Omega=0.0)
      ```

      ```python
      import airball

      star = airball.Star(m=1.0, b=1.0, v=1.0, inc="isotropic", omega="isotropic", Omega="isotropic")
      ```

      ```python
      import airball

      star = airball.Star(m=1.0, b=1.0, v=1.0)
      ```
    """

    def __init__(
        self,
        m: float | _u.Quantity,
        b: float | _u.Quantity,
        v: float | _u.Quantity,
        inc: float | _u.Quantity | str = "isotropic",
        omega: float | _u.Quantity | str = "isotropic",
        Omega: float | _u.Quantity | str = "isotropic",
        UNIT_SYSTEM=[],
        **kwargs,
    ) -> None:
        self.units = _u.UnitSet(UNIT_SYSTEM)

        seed = kwargs.get("seed", _np.random.randint(0, int(2**32 - 3)))
        if inc == "isotropic" or inc is None:
            inc = 2 * _np.arcsin(_np.sqrt(_uniform.rvs(size=1, random_state=seed + 1)))[0]
        if omega == "isotropic" or omega is None:
            omega = _uniform.rvs(loc=0, scale=(2.0 * _np.pi), size=1, random_state=seed + 2)[0]
        if Omega == "isotropic" or Omega is None:
            Omega = _uniform.rvs(loc=-_np.pi, scale=(2.0 * _np.pi), size=1, random_state=seed + 3)[0]
        if inc == "uniform" or inc is None:
            inc = _uniform.rvs(loc=-_np.pi, scale=(2.0 * _np.pi), size=1, random_state=seed + 1)[0]
        if omega == "uniform" or omega is None:
            omega = _uniform.rvs(loc=-_np.pi, scale=(2.0 * _np.pi), size=1, random_state=seed + 2)[0]
        if Omega == "uniform" or Omega is None:
            Omega = _uniform.rvs(loc=-_np.pi, scale=(2.0 * _np.pi), size=1, random_state=seed + 3)[0]

        self.mass = m
        self.impact_parameter = b
        self.velocity = v
        self.inc = inc
        self.argument_periastron = omega
        self.longitude_ascending_node = Omega

    @property
    def UNIT_SYSTEM(self):
        return self.units.UNIT_SYSTEM

    @UNIT_SYSTEM.setter
    def UNIT_SYSTEM(self, UNIT_SYSTEM):
        self.units.UNIT_SYSTEM = UNIT_SYSTEM

    @property
    def N(self):
        return 1

    @property
    def m(self):
        return self._mass.to(self.units["mass"])

    @m.setter
    def m(self, value):
        self._mass = _tools.verify_unit(value, self.units["mass"])

    @property
    def mass(self):
        return self.m

    @mass.setter
    def mass(self, value):
        self.m = value

    @property
    def b(self):
        return self._impact_parameter.to(self.units["length"])

    @b.setter
    def b(self, value):
        self._impact_parameter = _tools.verify_unit(value, self.units["length"])

    @property
    def impact_parameter(self):
        return self.b

    @impact_parameter.setter
    def impact_parameter(self, value):
        self.b = value

    @property
    def v(self):
        return self._velocity.to(self.units["velocity"])

    @v.setter
    def v(self, value):
        self._velocity = _tools.verify_unit(value, self.units["velocity"])

    @property
    def velocity(self):
        return self.v

    @velocity.setter
    def velocity(self, value):
        self.v = value

    @property
    def inc(self):
        return self._inclination.to(self.units["angle"])

    @inc.setter
    def inc(self, value):
        self._inclination = _tools.verify_unit(value, self.units["angle"])

    @property
    def inclination(self):
        return self.inc

    @inclination.setter
    def inclination(self, value):
        self.inc = value

    @property
    def omega(self):
        return self._argument_periastron.to(self.units["angle"])

    @omega.setter
    def omega(self, value):
        self._argument_periastron = _tools.verify_unit(value, self.units["angle"])

    @property
    def argument_periastron(self):
        return self.omega

    @argument_periastron.setter
    def argument_periastron(self, value):
        self.omega = value

    @property
    def Omega(self):
        return self._longitude_ascending_node.to(self.units["angle"])

    @Omega.setter
    def Omega(self, value):
        self._longitude_ascending_node = _tools.verify_unit(value, self.units["angle"])

    @property
    def longitude_ascending_node(self):
        return self.Omega

    @longitude_ascending_node.setter
    def longitude_ascending_node(self, value):
        self.Omega = value

    @property
    def impulse_gradient(self):
        # Calculate the impulse gradient for a flyby star.
        G = 1 * _u.au**3 / _u.solMass / _u.yr2pi**2
        return ((2.0 * G * self.m) / (self.v * self.b**2.0)).to(_u.km / _u.s / _u.au)

    @property
    def params(self):
        # Returns a list of the parameters of the Stars (with units) in order of:
        # Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega
        return [self.m, self.b, self.v, self.inc, self.omega, self.Omega]

    @property
    def param_values(self):
        # Returns a list of the parameters of the Stars in order of:
        # Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega
        return _np.array(
            [
                self.m.value,
                self.b.value,
                self.v.value,
                self.inc.value,
                self.omega.value,
                self.Omega.value,
            ]
        )

    def eccentricity(self, sim):
        return self.e(sim)

    def e(self, sim):
        sim_units = _tools.rebound_units(sim)
        G = sim.G * sim_units["length"] ** 3 / sim_units["mass"] / sim_units["time"] ** 2
        mu = G * (_tools.system_mass(sim) * sim_units["mass"] + self.m)

        numerator = self.b * self.v * self.v
        return _np.sqrt(1 + (numerator / mu) ** 2.0)

    def periastron(self, sim):
        return self.q(sim)

    def q(self, sim):
        sim_units = _tools.rebound_units(sim)
        G = sim.G * sim_units["length"] ** 3 / sim_units["mass"] / sim_units["time"] ** 2
        mu = G * (_tools.system_mass(sim) * sim_units["mass"] + self.m)

        numerator = self.b * self.v * self.v
        star_e = _np.sqrt(1 + (numerator / mu) ** 2.0)
        return self.b * _np.sqrt((star_e - 1.0) / (star_e + 1.0))

    def save(self, filename):
        """
        Save the current instance of the Star class to a file using pickle.

        Args:
          filename (str): The name of the file to save the instance to. The file will be saved in binary format.

        Example:
          ```python
          import airball

          star = airball.Star(m=1, b=250, v=1)
          star.save("my_special.star")
          ```
        """
        if not isinstance(filename, (str, Path)):
            raise ValueError("Filename must be a string or Path.")
        with open(filename, "wb") as pfile:
            _pickle.dump(self, pfile, protocol=_pickle.HIGHEST_PROTOCOL)

    def copy(self) -> "Star":
        """Returns a deep copy of the Star object."""
        return _deepcopy(self)

    @classmethod
    def from_file(cls, filename):
        """
        Load an instance of the Star class from a file using pickle.

        Args:
          filename (str): The name of the file to load the instance from. The file should be in binary format, pickled.

        Returns:
          loaded_star (Star): The loaded instance of the Star class.

        Example:
          ```python
          import airball

          stars = airball.Star.from_file("my_special.star")
          ```
        """
        try:
            if not isinstance(filename, (str, Path)):
                raise ValueError("Filename must be a string or Path.")
            with open(filename, "rb") as pfile:
                pickled = _pickle.load(pfile)
            dic = pickled.__dict__
            newStar = Star(
                m=dic["_mass"],
                b=dic["_impact_parameter"],
                v=dic["_velocity"],
                inc=dic["_inclination"],
                omega=dic["_argument_periastron"],
                Omega=dic["_longitude_ascending_node"],
                UNIT_SYSTEM=dic["units"],
            )
        except:  # noqa: E722
            raise Exception("Invalid filename.")
        return newStar

    def stats(self, returned=False):
        # Prints a summary of the current stats of the Star.
        s = f"<{self.__module__}.{type(self).__name__} object at {hex(id(self))}, "
        s += f"m= {self.mass:1.4g}, "
        s += f"b= {self.impact_parameter:1.4g}, "
        s += f"v= {self.velocity:1.4g}, "
        s += f"inc= {self.inc:1.4g}, "
        s += f"omega= {self.omega:1.4g}, "
        s += f"Omega= {self.Omega:1.4g}>"
        if returned:
            return s
        else:
            print(s)

    def __str__(self):
        return self.stats(returned=True)

    def __repr__(self):
        return self.stats(returned=True)

    def __len__(self):
        return NotImplemented

    def __eq__(self, other):
        # Overrides the default implementation
        if isinstance(other, Star):
            data = (
                (self.m == other.m)
                and (self.b == other.b)
                and (self.v == other.v)
                and (self.inc == other.inc)
                and (self.omega == other.omega)
                and (self.Omega == other.Omega)
            )
            properties = self.units == other.units
            return data and properties
        return NotImplemented

    def __hash__(self):
        # Overrides the default implementation.
        data = []
        for d in sorted(self.__dict__.items()):
            try:
                data.append((d[0], tuple(d[1])))
            except:  # noqa: E722
                data.append(d)
        data = tuple(data)
        return hash(data)
copy()

Returns a deep copy of the Star object.

Source code in src/airball/stars.py
275
276
277
def copy(self) -> "Star":
    """Returns a deep copy of the Star object."""
    return _deepcopy(self)
from_file(filename) classmethod

Load an instance of the Star class from a file using pickle.

Parameters:

Name Type Description Default
filename str

The name of the file to load the instance from. The file should be in binary format, pickled.

required

Returns:

Name Type Description
loaded_star Star

The loaded instance of the Star class.

Example
import airball

stars = airball.Star.from_file("my_special.star")
Source code in src/airball/stars.py
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
@classmethod
def from_file(cls, filename):
    """
    Load an instance of the Star class from a file using pickle.

    Args:
      filename (str): The name of the file to load the instance from. The file should be in binary format, pickled.

    Returns:
      loaded_star (Star): The loaded instance of the Star class.

    Example:
      ```python
      import airball

      stars = airball.Star.from_file("my_special.star")
      ```
    """
    try:
        if not isinstance(filename, (str, Path)):
            raise ValueError("Filename must be a string or Path.")
        with open(filename, "rb") as pfile:
            pickled = _pickle.load(pfile)
        dic = pickled.__dict__
        newStar = Star(
            m=dic["_mass"],
            b=dic["_impact_parameter"],
            v=dic["_velocity"],
            inc=dic["_inclination"],
            omega=dic["_argument_periastron"],
            Omega=dic["_longitude_ascending_node"],
            UNIT_SYSTEM=dic["units"],
        )
    except:  # noqa: E722
        raise Exception("Invalid filename.")
    return newStar
save(filename)

Save the current instance of the Star class to a file using pickle.

Parameters:

Name Type Description Default
filename str

The name of the file to save the instance to. The file will be saved in binary format.

required
Example
import airball

star = airball.Star(m=1, b=250, v=1)
star.save("my_special.star")
Source code in src/airball/stars.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def save(self, filename):
    """
    Save the current instance of the Star class to a file using pickle.

    Args:
      filename (str): The name of the file to save the instance to. The file will be saved in binary format.

    Example:
      ```python
      import airball

      star = airball.Star(m=1, b=250, v=1)
      star.save("my_special.star")
      ```
    """
    if not isinstance(filename, (str, Path)):
        raise ValueError("Filename must be a string or Path.")
    with open(filename, "wb") as pfile:
        _pickle.dump(self, pfile, protocol=_pickle.HIGHEST_PROTOCOL)

airball.stars.Stars

Bases: MutableMapping

This class allows the user to access stars like an array using the star's index. Allows for negative indices and slicing. The implementation uses astropy.Quantity and numpy ndarrays underneath and only generates a airball.Star object when a single Star is requested.

Parameters:

Name Type Description Default
m list, ndarray, or Quantity

The masses of the stars. Default units are in solMass.

required
b list, ndarray, or Quantity

The impact parameters of the stars. Default units are in AU.

required
v list, ndarray, or Quantity

The velocities at infinity of the stars. Default units are in km/s.

required
inc list, ndarray, or Quantity

The inclinations of the stars. Default units are in radians.

required
omega list, ndarray, or Quantity

The arguments of the periastron of the stars. Default units are in radians.

required
Omega list, ndarray, or Quantity

The longitudes of the ascending node of the stars. Default units are in radians.

required
UNIT_SYSTEM list

The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].

required
size int

The number of stars to generate. Default is None.

required
environment Environment

The environment to generate the stars in (if size > 1). env is an alias. Default is None.

required
filename str

The name of the file to load the instance from. The file should be in binary format. Default is None.

None

Attributes:

Name Type Description
m Quantity

The masses of the stars. Default units are in solMass.

b Quantity

The impact parameters of the stars. Default units are in AU.

v Quantity

The velocities at infinity of the stars. Default units are in km/s.

inc Quantity

The inclinations of the stars. Default units are in radians.

omega Quantity

The arguments of the periastron of the stars. Default units are in radians.

Omega Quantity

The longitudes of the ascending node of the stars. Default units are in radians.

units UnitSet

The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].

median_mass Quantity

The median mass of the stars. Default units are in solMass.

mean_mass Quantity

The mean mass of the stars. Default units are in solMass.

N int

The number of stars.

shape tuple

The shape of the stars array.

params list

A list of the parameters of the stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

param_values list

A list of the values of the parameters of the stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

Examples:

# Explicitly specify the stellar parameters.
import airball

stars_from_params1 = airball.Stars(
    m=[1.0, 1.0, 1.0],
    b=[1.0, 1.0, 1.0],
    v=[1.0, 1.0, 1.0],
    inc=[0.0, 0.0, 0.0],
    omega=[0.0, 0.0, 0.0],
    Omega=[0.0, 0.0, 0.0],
)
stars_from_params2 = airball.Stars(m=[1.0, 1.0, 1.0], b=[1.0, 1.0, 1.0], v=[1.0, 1.0, 1.0])  # random orientation angles
stars_from_params3 = airball.Stars(
    m=1, b=200, v=5, omega=0, Omega=0, size=100
)  # 100 identical stars with isotropically random inclinations
stars_from_params4 = airball.Stars(
    m=[1.0, 1.0, 1.0], b=[1.0, 1.0, 1.0], v=[1.0, 1.0, 1.0], inc="uniform", omega="uniform", Omega="uniform"
)  # uniformly random orientation angles
# Randomly generate the stellar parameters from a given environment.
import airball

stars_from_env1 = airball.Stars(environment=airball.OpenCluster(), size=3)
stars_from_env2 = airball.Stars(env=airball.LocalNeighborhood(), size=5)
stars_from_env3 = airball.Stars(airball.GlobularCluster(), size=9)
# Load the stellar parameters from a file.
import airball

stars_from_file1 = airball.Stars(filename="open_cluster.stars")
stars_from_file2 = airball.Stars("open_cluster.stars")
Source code in src/airball/stars.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
class Stars(MutableMapping):
    """
    This class allows the user to access stars like an array using the star's index.
    Allows for negative indices and slicing.
    The implementation uses astropy.Quantity and numpy ndarrays underneath and only generates a airball.Star object when a single Star is requested.

    Args:
      m (list, ndarray, or Quantity): The masses of the stars. Default units are in solMass.
      b (list, ndarray, or Quantity): The impact parameters of the stars. Default units are in AU.
      v (list, ndarray, or Quantity): The velocities at infinity of the stars. Default units are in km/s.
      inc (list, ndarray, or Quantity, optional): The inclinations of the stars. Default units are in radians.
      omega (list, ndarray, or Quantity, optional): The arguments of the periastron of the stars. Default units are in radians.
      Omega (list, ndarray, or Quantity, optional): The longitudes of the ascending node of the stars. Default units are in radians.
      UNIT_SYSTEM (list, optional): The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].
      size (int, optional): The number of stars to generate. Default is None.
      environment (airball.Environment, optional): The environment to generate the stars in (if `size` > 1). `env` is an alias. Default is None.
      filename (str, optional): The name of the file to load the instance from. The file should be in binary format. Default is None.

    Attributes:
      m (astropy.units.Quantity): The masses of the stars. Default units are in solMass.
      b (astropy.units.Quantity): The impact parameters of the stars. Default units are in AU.
      v (astropy.units.Quantity): The velocities at infinity of the stars. Default units are in km/s.
      inc (astropy.units.Quantity): The inclinations of the stars. Default units are in radians.
      omega (astropy.units.Quantity): The arguments of the periastron of the stars. Default units are in radians.
      Omega (astropy.units.Quantity): The longitudes of the ascending node of the stars. Default units are in radians.
      units (airball.tools.UnitSet): The unit system to use for the parameters. Default is [u.solMass, u.AU, u.km/u.s, u.rad].
      median_mass (astropy.units.Quantity): The median mass of the stars. Default units are in solMass.
      mean_mass (astropy.units.Quantity): The mean mass of the stars. Default units are in solMass.
      N (int): The number of stars.
      shape (tuple): The shape of the stars array.
      params (list): A list of the parameters of the stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.
      param_values (list): A list of the values of the parameters of the stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega.

    Examples:
      ```python
      # Explicitly specify the stellar parameters.
      import airball

      stars_from_params1 = airball.Stars(
          m=[1.0, 1.0, 1.0],
          b=[1.0, 1.0, 1.0],
          v=[1.0, 1.0, 1.0],
          inc=[0.0, 0.0, 0.0],
          omega=[0.0, 0.0, 0.0],
          Omega=[0.0, 0.0, 0.0],
      )
      stars_from_params2 = airball.Stars(m=[1.0, 1.0, 1.0], b=[1.0, 1.0, 1.0], v=[1.0, 1.0, 1.0])  # random orientation angles
      stars_from_params3 = airball.Stars(
          m=1, b=200, v=5, omega=0, Omega=0, size=100
      )  # 100 identical stars with isotropically random inclinations
      stars_from_params4 = airball.Stars(
          m=[1.0, 1.0, 1.0], b=[1.0, 1.0, 1.0], v=[1.0, 1.0, 1.0], inc="uniform", omega="uniform", Omega="uniform"
      )  # uniformly random orientation angles
      ```

      ```python
      # Randomly generate the stellar parameters from a given environment.
      import airball

      stars_from_env1 = airball.Stars(environment=airball.OpenCluster(), size=3)
      stars_from_env2 = airball.Stars(env=airball.LocalNeighborhood(), size=5)
      stars_from_env3 = airball.Stars(airball.GlobularCluster(), size=9)
      ```

      ```python
      # Load the stellar parameters from a file.
      import airball

      stars_from_file1 = airball.Stars(filename="open_cluster.stars")
      stars_from_file2 = airball.Stars("open_cluster.stars")
      ```
    """

    def __init__(self, filename=None, **kwargs) -> None:
        try:
            self.units = _u.UnitSet(kwargs["UNIT_SYSTEM"])
            del kwargs["UNIT_SYSTEM"]
        except KeyError:
            try:
                self.units = kwargs["units"]
            except KeyError:
                self.units = _u.UnitSet()

        if filename is not None:
            # Initialize Stars from file.
            if isinstance(filename, (str, Path)):
                try:
                    loaded = Stars._load(filename)
                    self.__dict__ = loaded.__dict__
                except:  # noqa: E722
                    raise Exception("Invalid filename.")
                return
            # If filename is a Star object, then initialize Stars with the same parameters.
            elif isinstance(filename, Star):
                self._shape = (kwargs.get("size", 1),)
                self._m = (_np.ones(self.shape) * filename.m) << self.units["mass"]
                self._b = (_np.ones(self.shape) * filename.b) << self.units["length"]
                self._v = (_np.ones(self.shape) * filename.v) << self.units["velocity"]
                self._inc = (_np.ones(self.shape) * filename.inc) << self.units["angle"]
                self._omega = (_np.ones(self.shape) * filename.omega) << self.units["angle"]
                self._Omega = (_np.ones(self.shape) * filename.Omega) << self.units["angle"]
                self.environment = None
                return

        # If nothing is specified, return an empty Stars object.
        if not kwargs:
            self._m = _np.array([]) << self.units["mass"]
            self._b = _np.array([]) << self.units["length"]
            self._v = _np.array([]) << self.units["velocity"]
            self._inc = _np.array([]) << self.units["angle"]
            self._omega = _np.array([]) << self.units["angle"]
            self._Omega = _np.array([]) << self.units["angle"]
            self._shape = (0,)
            self.environment = None
            return

        # Determine the number of stars to generate.
        self._shape = (0,)
        for key in kwargs:
            try:
                if isinstance(kwargs[key], _u.Quantity):
                    shape = kwargs[key].shape
                    N = 0
                    if len(shape) >= 1:
                        N = _np.prod(shape)
                    else:
                        shape = (0,)
                    if N > self.N:
                        self._shape = shape
                elif _tools.isList(kwargs[key]):
                    if _np.prod(_np.shape(kwargs[key])) > self.N:
                        self._shape = _np.shape(kwargs[key])
                else:
                    pass
            except TypeError as err:
                print(err)
                self._shape = (len(kwargs[key]),)
            except Exception as err:
                raise err

        # if 'size' in kwargs and self.N != 0:
        #   raise OverspecifiedParametersException('If lists are given then size cannot be specified.')
        if "size" in kwargs:
            if isinstance(kwargs["size"], tuple):
                self._shape = tuple([int(i) for i in kwargs["size"]])
            else:
                self._shape = (int(kwargs["size"]),)
        elif self.N == 0:
            self._shape = ()  # raise UnspecifiedParameterException('If no lists of parameters are given then size must be specified.')
        else:
            pass  # No errors or issues, continue.

        # Initialize Stars from environment.
        self.environment = kwargs.get("environment", None)
        if (("environment" in kwargs or "env" in kwargs) or isinstance(filename, _env.StellarEnvironment)) and "size" in kwargs:
            if self.N <= 1:
                raise InvalidValueForKeyException("If a generating environment is given then size must be greater than 1.")
            if "environment" in kwargs:
                se = kwargs["environment"]
                del kwargs["environment"]
            elif "env" in kwargs:
                se = kwargs["env"]
                del kwargs["env"]
            else:
                se = filename
                del filename
            stars = se.random_stars(**kwargs)
            self.__dict__ = stars.__dict__
            return

        # Initialize Stars from kwargs.
        keys = ["m", "b", "v"]
        units = ["mass", "length", "velocity"]
        unspecifiedParameterExceptions = [
            "Mass, m, must be specified.",
            "Impact Parameter, b, must be specified.",
            "Velocity, v, must be specified.",
        ]

        for k, u, upe in zip(keys, units, unspecifiedParameterExceptions):
            try:
                # Check to see if was key is given.
                value = kwargs[k]
                # Check if shape matches other key values.
                if len(value) != len(self):
                    raise ListLengthException(f"Difference of {len(value)} and {len(self)} for {k}.")
                # Length of value matches other key values, check if value is a list.
                elif isinstance(value, list):
                    # Value is a list, try to turn list of Quantities into a ndarray Quantity.
                    try:
                        quantityValue = _np.array([v.to(self.units[u]).value for v in value]) << self.units[u]
                    # Value was not a list of Quantities, turn list into ndarray and make a Quantity.
                    except:  # noqa: E722
                        quantityValue = _np.array(value) << self.units[u]
                # Value was not a list, check to see if value is an ndarray.
                elif isinstance(value, _np.ndarray):
                    # Assume ndarray is a Quantity and try to convert ndarray into given units.
                    try:
                        quantityValue = value.to(self.units[u])
                    # ndarray is not a Quantity so turn ndarray into a Quantity.
                    except:  # noqa: E722
                        quantityValue = value << self.units[u]
                # Value implements __len__, but is not a list or ndarray.
                else:
                    raise IncompatibleListException()
            # This key is necessary and must be specified, raise and Exception.
            except KeyError:
                raise UnspecifiedParameterException(upe)
            # Value is not a list, so assume it is an int or float and generate an ndarray of the given value.
            except TypeError:
                value = value.to(self.units[u]) if _tools.isQuantity(value) else value * self.units[u]
                quantityValue = _np.ones(self.shape) * value
            # Catch any additional Exceptions.
            except Exception as err:
                raise err
            # Store Quantity Value as class property.
            if k == "m":
                self._m = quantityValue
            elif k == "b":
                self._b = quantityValue
            elif k == "v":
                self._v = quantityValue
            else:
                raise _tools.InvalidKeyException()
            # Double check for consistent shapes.
            if self._shape is not None:
                if quantityValue.shape != self._shape:
                    raise ListLengthException(f"Difference of {quantityValue.shape} and {self._shape} for {k}.")
            else:
                self._shape = quantityValue.shape

        seed = kwargs.get("seed", _np.random.randint(0, int(2**32 - 3)))
        for seedOffset, k in enumerate(["inc", "omega", "Omega"]):
            try:
                # Check to see if was key is given.
                value = kwargs[k]
                # Check to see if value for key is string.
                if isinstance(value, str):
                    # Value is a string, check to see if value for key is valid.
                    # Values 'isotropic' or 'uniform' for key are valid, now generate an array of values for key.
                    if value == "isotropic":
                        # Set the distributions for the orientation angles.
                        if k == "inc":
                            quantityValue = (
                                2.0
                                * _np.arcsin(
                                    _np.sqrt(
                                        _uniform.rvs(
                                            size=self.shape,
                                            random_state=(seed + seedOffset),
                                        )
                                    )
                                )
                                << self.units["angle"]
                            )
                        elif k == "omega":
                            quantityValue = (
                                _uniform.rvs(
                                    loc=0,
                                    scale=(2.0 * _np.pi),
                                    size=self.shape,
                                    random_state=(seed + seedOffset),
                                )
                                << self.units["angle"]
                            )
                        elif k == "Omega":
                            quantityValue = (
                                _uniform.rvs(
                                    loc=-_np.pi,
                                    scale=(2.0 * _np.pi),
                                    size=self.shape,
                                    random_state=(seed + seedOffset),
                                )
                                << self.units["angle"]
                            )
                    elif value == "uniform":
                        quantityValue = (
                            _uniform.rvs(
                                loc=-_np.pi,
                                scale=(2.0 * _np.pi),
                                size=self.shape,
                                random_state=(seed + seedOffset),
                            )
                            << self.units["angle"]
                        )
                    else:
                        raise InvalidValueForKeyException()
                # Value is not a string, check if length matches other key values.
                elif len(value) != len(self):
                    raise ListLengthException(f"Difference of {len(value)} and {len(self)} for {k}.")
                # Length of value matches other key values, check if value is a list.
                elif isinstance(value, list):
                    # Value is a list, try to turn list of Quantities into a ndarray Quantity.
                    try:
                        quantityValue = _np.array([v.to(self.units["angle"]).value for v in value]) * self.units["angle"]
                    # Value was not a list of Quantities, turn list into ndarray and make a Quantity.
                    except:  # noqa: E722
                        quantityValue = _np.array(value) * self.units["angle"]
                # Value was not a list, check to see if value is an ndarray.
                elif isinstance(value, _np.ndarray):
                    # Assume ndarray is a Quantity and try to convert ndarray into given units.
                    try:
                        quantityValue = value.to(self.units["angle"])
                    # ndarray is not a Quantity so turn ndarray into a Quantity.
                    except:  # noqa: E722
                        quantityValue = value * self.units["angle"]
                # Value implements __len__, but is not a list or ndarray.
                else:
                    raise IncompatibleListException()
            # Key does not exist, assume the user wants an array of values to automatically be generated isotropically.
            except KeyError:
                if k == "inc":
                    quantityValue = (
                        2.0 * _np.arcsin(_np.sqrt(_uniform.rvs(size=self.shape, random_state=(seed + seedOffset))))
                        << self.units["angle"]
                    )
                elif k == "omega":
                    quantityValue = (
                        _uniform.rvs(
                            loc=0,
                            scale=(2.0 * _np.pi),
                            size=self.shape,
                            random_state=(seed + seedOffset),
                        )
                        << self.units["angle"]
                    )
                elif k == "Omega":
                    quantityValue = (
                        _uniform.rvs(
                            loc=-_np.pi,
                            scale=(2.0 * _np.pi),
                            size=self.shape,
                            random_state=(seed + seedOffset),
                        )
                        << self.units["angle"]
                    )
            # Value is not a list, so assume it is an int or float and generate an ndarray of the given value.
            except TypeError:
                value = value.to(self.units["angle"]) if _tools.isQuantity(value) else value * self.units["angle"]
                quantityValue = _np.ones(self.shape) * value
            # Catch any additional Exceptions.
            except Exception as err:
                raise err
            # Store Quantity Value as class property.
            if k == "inc":
                self._inc = quantityValue
            elif k == "omega":
                self._omega = quantityValue
            elif k == "Omega":
                self._Omega = quantityValue
            else:
                raise _tools.InvalidKeyException()
            # Double check for consistent shapes.
            if self.shape is not None:
                if quantityValue.shape != self.shape:
                    raise ListLengthException(f"Difference of {quantityValue.shape} and {self.shape} for {k}.")
            else:
                self._shape = quantityValue.shape

    @property
    def N(self):
        """The total number of Stars."""
        return _np.prod(self.shape)

    @property
    def shape(self):
        """The shape of the Stars arrays."""
        return self._shape

    @property
    def median_mass(self):
        """The median mass of the Stars."""
        return _np.median([mass.value for mass in self.m]) << self.units["mass"]

    @property
    def mean_mass(self):
        """The mean mass of the Stars."""
        return _np.mean([mass.value for mass in self.m]) << self.units["mass"]

    @property
    def m(self):
        return self._m << self.units["mass"]

    @m.setter
    def m(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._m = _tools.verify_unit(value, self.units["mass"])

    @property
    def mass(self):
        """
        Set the masses of the Stars, alias of `m` (default units: Msun).

        Args:
          value (list, ndarray, or Quantity): The new mass values. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.m

    @mass.setter
    def mass(self, value):
        try:
            self.m = value
        except Exception as err:
            raise err

    @property
    def b(self):
        return self._b << self.units["length"]

    @b.setter
    def b(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._b = _tools.verify_unit(value, self.units["length"])

    @property
    def impact_parameter(self):
        """
        Set the impact parameters of the Stars, alias of `b` (default units: AU).

        Args:
          value (list, ndarray, or Quantity): The new impact parameter values. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.b

    @impact_parameter.setter
    def impact_parameter(self, value):
        try:
            self.b = value
        except Exception as err:
            raise err

    @property
    def v(self):
        return self._v << self.units["velocity"]

    @v.setter
    def v(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._v = _tools.verify_unit(value, self.units["velocity"])

    @property
    def velocity(self):
        """
        Set the velocities at infinity of the Stars, alias of `v` (default units: km/s).

        Args:
          value (list, ndarray, or Quantity): The new velocity values. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.v

    @velocity.setter
    def velocity(self, value):
        try:
            self.v = value
        except Exception as err:
            raise err

    @property
    def inc(self):
        return self._inc << self.units["angle"]

    @inc.setter
    def inc(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._inc = _tools.verify_unit(value, self.units["angle"])

    @property
    def inclination(self):
        """
        The inclinations of the Stars, alias of `inc` (default units: radians).

        Args:
          value (list, ndarray, or Quantity): The new inclination values. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.inc

    @inclination.setter
    def inclination(self, value):
        try:
            self.inc = value
        except Exception as err:
            raise err

    @property
    def omega(self):
        return self._omega << self.units["angle"]

    @omega.setter
    def omega(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._omega = _tools.verify_unit(value, self.units["angle"])

    @property
    def argument_periastron(self):
        """
        The argument of periastron of the Stars, alias of `omega` (default units: radians).

        Args:
          value (list, ndarray, or Quantity): The new values for the argument of periastron. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.omega

    @argument_periastron.setter
    def argument_periastron(self, value):
        try:
            self.omega = value
        except Exception as err:
            raise err

    @property
    def Omega(self):
        return self._Omega << self.units["angle"]

    @Omega.setter
    def Omega(self, value):
        try:
            if _np.shape(value) != self.shape:
                raise ListLengthException(f"Difference of {_np.shape(value)} and {self.shape}.")
        except (TypeError, AttributeError):
            raise IncompatibleListException()
        self._Omega = _tools.verify_unit(value, self.units["angle"])

    @property
    def longitude_ascending_node(self):
        """
        The longitude of the ascending node of the Stars, alias of `Omega` (default units: radians).

        Args:
          value (list, ndarray, or Quantity): The new longitude of the ascending node values. Can be set with a list such that len(value) == len(Stars).

        Raises:
          ListLengthException: If the length of the provided list does not match the number of Stars.
          IncompatibleListException: If the provided list is not compatible.
        """
        return self.Omega

    @longitude_ascending_node.setter
    def longitude_ascending_node(self, value):
        try:
            self.Omega = value
        except Exception as err:
            raise err

    @property
    def impulse_gradient(self):
        """
        Calculate the impulse gradient for a flyby star.

        $$\\frac{2GM_\\star}{V_\\star b_\\star^2}$$
        """
        G = 1 * _u.au**3 / _u.solMass / _u.yr2pi**2
        return ((2.0 * G * self.m) / (self.v * self.b**2.0)).to(_u.km / _u.s / _u.au)

    @property
    def params(self):
        """
        A list of the parameters of the Stars (with units) in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

        `[m, b, v, inc, omega, Omega]`
        """
        return [self.m, self.b, self.v, self.inc, self.omega, self.Omega]

    @property
    def param_values(self):
        """
        A list of the values of the parameters of the Stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

        `[m.value, b.value, v.value, inc.value, omega.value, Omega.value]`
        """
        return _np.array(
            [
                self.m.value,
                self.b.value,
                self.v.value,
                self.inc.value,
                self.omega.value,
                self.Omega.value,
            ]
        )

    @property
    def param_dict(self):
        """
        A dictionary of the values of the parameters of the Stars including: Mass, "m"; Impact Parameter, "b"; Velocity, "v"; Inclination, "inc"; Argument of the Periastron, "omega"; and Longitude of the Ascending Node, "Omega".

        `{"m": stars.m, "b": stars.b, "v": stars.v, "inc": stars.inc, "omega": stars.omega, "Omega": stars.Omega}`
        """
        return {
            "m": self.m,
            "b": self.b,
            "v": self.v,
            "inc": self.inc,
            "omega": self.omega,
            "Omega": self.Omega,
        }

    @property
    def labels(self):
        """
        A list of labels for the parameters of the Stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

        `["Mass", "Impact Parameter", "Velocity", "Inclination", "Argument of the Periastron", "Longitude of the Ascending Node"]`
        """
        return [
            "Mass",
            "Impact Parameter",
            "Velocity",
            "Inclination",
            "Argument of the Periastron",
            "Longitude of the Ascending Node",
        ]

    def eccentricity(self, sim):
        """
        The eccentricity of the Stars, alias for `e(sim)`.

        Args:
          sim (Simulation): The REBOUND Simulation to use for calculating the eccentricity.

        Returns:
          eccentricity (ndarray): The eccentricity of the Stars.
        """
        return self.e(sim)

    def e(self, sim):
        units = _tools.rebound_units(sim)
        G = sim.G * units.length**3 / units.mass / units.time**2
        mu = G * (_tools.system_mass(sim) * units.mass + self.m)

        numerator = self.b * self.v * self.v
        return _np.sqrt(1 + (numerator / mu) ** 2.0)

    def periastron(self, sim):
        """
        The periastron of the Stars, alias for `q(sim)`.

        Args:
          sim (Simulation): The REBOUND Simulation to use for calculating the periastron.

        Returns:
          periastron (ndarray): The periastron of the Stars.
        """
        return self.q(sim)

    def q(self, sim):
        sim_units = _tools.rebound_units(sim)
        G = sim.G * sim_units["length"] ** 3 / sim_units["mass"] / sim_units["time"] ** 2
        mu = G * (_tools.system_mass(sim) * sim_units["mass"] + self.m)

        numerator = self.b * self.v * self.v
        star_e = _np.sqrt(1 + (numerator / mu) ** 2.0)
        return self.b * _np.sqrt((star_e - 1.0) / (star_e + 1.0))

    def copy(self):
        """Returns a deep copy of the Stars."""
        return _deepcopy(self)

    def sort(self, key, sim=None, argsort=False):
        # Alias for `sortby`.
        return self.sortby(key, sim, argsort)

    def argsort(self, key, sim=None):
        # Alias for `sortby(argsort=True)`.
        return self.sortby(key, sim, argsort=True)

    def argsortby(self, key, sim=None):
        # Alias for `sortby(argsort=True)`.
        return self.sortby(key, sim, argsort=True)

    def sortby(self, key, sim=None, argsort=False):
        """
        Sort the Stars in ascending order by a defining parameter.

        Args:
          key (str): The parameter to sort by. Options include: 'm' (mass), 'b' (impact parameter), 'v' (relative velocity at infinity), 'inc' (inclination), 'omega' (argument of the periastron), 'Omega' (longitude of the ascending node), 'q' (periapsis), 'e' (eccentricity). For 'q' and 'e', a REBOUND Simulation is required.
          sim (Simulation, optional): The REBOUND Simulation to use for sorting by 'q' and 'e'. Default is None.
          argsort (bool, optional): If True, return the indices used to sort the Stars. Default is False.

        Returns:
          indices (list or None): The indices used to sort the Stars, if argsort is True. Otherwise, None and sorting is done in place.

        !!! Info
            The Stars can also be sorted arbitrarily by providing a list of indices of length len(stars) as the key.

        Examples:
          ```python
          import airball

          stars = airball.Stars(m=[1, 2, 3], b=[3, 2, 1], v=[6, 5, 7])
          stars.sortby("b")
          inds = stars.sortby("v", argsort=True)
          ```

          ```python
          import airball
          import rebound

          sim = rebound.Simulation()
          sim.add(m=1)
          sim.add(m=5e-5, a=30, e=0.01)
          stars = airball.Stars(airball.OpenCluster(), size=100)
          stars.sortby("q", sim=sim)
          ```

          ```python
          import airball

          stars = airball.Stars(airball.LocalNeighborhood(), size=5)
          inds = [0, 4, 1, 3, 2]
          stars.sortby(inds)
          ```
        """

        inds = _np.arange(len(self))
        if key == "m" or key == "mass":
            inds = _np.argsort(self.m)
        elif key == "b" or key == "impact" or key == "impact param" or key == "impact parameter":
            inds = _np.argsort(self.b)
        elif key == "v" or key == "vinf" or key == "v_inf" or key == "velocity":
            inds = _np.argsort(self.v)
        elif key == "inc" or key == "inclination" or key == "i" or key == "I":
            inds = _np.argsort(self.inc)
        elif key == "omega" or key == "ω" or key == "argument_periastron":
            inds = _np.argsort(self.omega)
        elif key == "Omega" or key == "Ω" or key == "longitude_ascending_node":
            inds = _np.argsort(self.Omega)
        elif key == "q" or key == "peri" or key == "perihelion" or key == "periastron" or key == "periapsis":
            if isinstance(sim, _rebound.Simulation):
                inds = _np.argsort(self.q(sim))
            else:
                raise InvalidParameterTypeException()
        elif key == "e" or key == "eccentricity":
            if isinstance(sim, _rebound.Simulation):
                inds = _np.argsort(self.e(sim))
            else:
                raise InvalidParameterTypeException()
        elif _tools.isList(key):
            print(key)
            if len(key) != len(self):
                raise ListLengthException(f"Difference of key: {len(key)} and stars: {len(self)}.")
            inds = _np.array(key)
        else:
            raise InvalidValueForKeyException()

        if argsort:
            return inds
        else:
            self.m[:] = self.m[inds]
            self.b[:] = self.b[inds]
            self.v[:] = self.v[inds]
            self.inc[:] = self.inc[inds]
            self.omega[:] = self.omega[inds]
            self.Omega[:] = self.Omega[inds]

    def save(self, filename):
        """
        Save the current instance of the Stars class to a file using pickle.

        Args:
          filename (str): The name of the file to save the instance to. The file will be saved in binary format.

        Example:
          ```python
          import airball

          se = airball.OpenCluster()
          stars = se.random_stars(100)
          stars.save("open_cluster.stars")
          ```
        """
        if not isinstance(filename, (str, Path)):
            raise ValueError("Filename must be a string or Path.")
        with open(filename, "wb") as pfile:
            _pickle.dump(self, pfile, protocol=_pickle.HIGHEST_PROTOCOL)

    @classmethod
    def _load(cls, filename):
        """
        Load an instance of the Stars class from a file using pickle.

        Args:
          filename (str): The name of the file to load the instance from. The file should be in binary format, pickled.

        Returns:
          loaded_stars (Stars): The loaded instance of the Stars class.

        Example:
          ```python
          import airball

          stars = airball.Stars("open_cluster.stars")
          ```
        """
        if not isinstance(filename, (str, Path)):
            raise ValueError("Filename must be a string or Path.")
        with open(filename, "rb") as pfile:
            return _pickle.load(pfile)

    def stats(self, returned=False):
        """
        Prints a summary of the current stats of the Stars object.
        The stats are returned as a string if `returned=True`.
        """
        s = f"<{self.__module__}.{type(self).__name__} object at {hex(id(self))}, "
        s += f"N={f'{self.N:,.0f}' if len(self.shape) == 1 else self.shape}"
        if self.N > 0:
            s += f", m= {_np.min(self.m.value):,.3f}-{_np.max(self.m.value):,.3f} {self.units['mass']}"
        if self.N > 0:
            s += f", b= {_np.min(self.b.value):,.0f}-{_np.max(self.b.value):,.0f} {self.units['length']}"
        if self.N > 0:
            s += f", v= {_np.min(self.v.value):,.0f}-{_np.max(self.v.value):,.0f} {self.units['velocity']}"
        s += f"{f', Environment={self.environment.name}' if self.environment is not None else ''}"
        s += ">"
        if returned:
            return s
        else:
            print(s)

    def __str__(self):
        return self.stats(returned=True)

    def __repr__(self):
        return self.stats(returned=True)

    def __getitem__(self, key):
        int_types = int, _np.integer

        # Basic indexing.
        if isinstance(key, int_types):
            # If the set of Stars is multi-dimensional, return the requested subset of stars as a set of Stars.
            if len(self.m.shape) > 1:
                return Stars(
                    m=self.m[key],
                    b=self.b[key],
                    v=self.v[key],
                    inc=self.inc[key],
                    omega=self.omega[key],
                    Omega=self.Omega[key],
                    UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                )
            # Otherwise return the requested Star.
            else:
                return Star(
                    m=self.m[key],
                    b=self.b[key],
                    v=self.v[key],
                    inc=self.inc[key],
                    omega=self.omega[key],
                    Omega=self.Omega[key],
                    UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                )

        # Allows for boolean array masking and indexing using a subset of indices.
        if isinstance(key, _np.ndarray):
            return Stars(
                m=self.m[key],
                b=self.b[key],
                v=self.v[key],
                inc=self.inc[key],
                omega=self.omega[key],
                Omega=self.Omega[key],
                UNIT_SYSTEM=self.units.UNIT_SYSTEM,
            )

        # Allow for speed efficient slicing by returning a new set of Stars which are a subset of the original object.
        if isinstance(key, slice):
            # Check for number of elements returned by the slice.
            numEl = _tools.numberOfElementsReturnedBySlice(*key.indices(self.N))
            # If the slice requests the entire set, then simply return the set.
            # if key == slice(None, None, None): return self #  !!! **Note: this is a reference to the same object.** !!!
            # If there are no elements requested, return the empty set.
            if numEl == 0:
                return Stars(m=[], b=[], v=[], size=0)
            # If only one element is requested, return a set of Stars with only one Star.
            elif numEl == 1:
                return Stars(
                    m=self.m[key],
                    b=self.b[key],
                    v=self.v[key],
                    inc=self.inc[key],
                    omega=self.omega[key],
                    Omega=self.Omega[key],
                    UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                    size=1,
                )
            # Otherwise return a subset of the Stars defined by the slice.
            else:
                return Stars(
                    m=self.m[key],
                    b=self.b[key],
                    v=self.v[key],
                    inc=self.inc[key],
                    omega=self.omega[key],
                    Omega=self.Omega[key],
                    UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                )

        # Allow for Numpy style array indexing.
        if isinstance(key, tuple):
            # Check if Stars data is multi-dimensional.
            if len(self.m.shape) == 1:
                raise IndexError(f"Too many indices: Stars are 1-dimensional, but {len(key)} were indexed.")
            # Check to see if the tuple has a slice.
            hasSlice = _tools.hasTrue([isinstance(k, slice) for k in key])
            if hasSlice:
                # Check the number of elements requested by the slice.
                numEl = [
                    _tools.numberOfElementsReturnedBySlice(*k.indices(self.m.shape[i])) if isinstance(k, slice) else 1
                    for i, k in enumerate(key)
                ]
                # If there are no elements requested, return the empty set.
                if numEl.count(0) > 0:
                    return Stars(m=[], b=[], v=[], size=0)
                # If multiple elements are requested, return a set of Stars.
                elif _np.any(_np.array(numEl) > 1):
                    return Stars(
                        m=self.m[key],
                        b=self.b[key],
                        v=self.v[key],
                        inc=self.inc[key],
                        omega=self.omega[key],
                        Omega=self.Omega[key],
                        UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                    )
                # If only one element is requested, return a set of Stars with only one Star.
                else:
                    # Check to see if the single element is an scalar or an array with only one element.
                    if self.m[key].isscalar:
                        return Stars(
                            m=self.m[key],
                            b=self.b[key],
                            v=self.v[key],
                            inc=self.inc[key],
                            omega=self.omega[key],
                            Omega=self.Omega[key],
                            size=1,
                            UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                        )
                    else:
                        return Stars(
                            m=self.m[key],
                            b=self.b[key],
                            v=self.v[key],
                            inc=self.inc[key],
                            omega=self.omega[key],
                            Omega=self.Omega[key],
                            UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                        )
            # If there is no slice, the return the requested Star.
            else:
                return Star(
                    m=self.m[key],
                    b=self.b[key],
                    v=self.v[key],
                    inc=self.inc[key],
                    omega=self.omega[key],
                    Omega=self.Omega[key],
                    UNIT_SYSTEM=self.units.UNIT_SYSTEM,
                )

        raise _tools.InvalidKeyException()

    def __setitem__(self, key, value):
        star_type = Star, Stars
        if isinstance(value, star_type):
            (
                self.m[key],
                self.b[key],
                self.v[key],
                self.inc[key],
                self.omega[key],
                self.Omega[key],
            ) = value.params
        else:
            raise InvalidStarException()

    def __delitem__(self, key):
        raise ValueError("Cannot delete Star elements from Stars array.")

    def __iter__(self):
        for i in list(_np.ndindex(self.m.shape)):
            yield Star(
                m=self.m[i],
                b=self.b[i],
                v=self.v[i],
                inc=self.inc[i],
                omega=self.omega[i],
                Omega=self.Omega[i],
                UNIT_SYSTEM=self.units.UNIT_SYSTEM,
            )

    def __len__(self):
        return self.shape[0]

    def __eq__(self, other):
        # Overrides the default implementation
        if isinstance(other, Stars):
            attrs = [
                "m",
                "b",
                "v",
                "inc",
                "omega",
                "Omega",
                "N",
                "shape",
                "units",
                "environment",
            ]
            equal = True
            for attr in attrs:
                equal_attribute = _np.all(getattr(self, attr) == getattr(other, attr))
                if not equal_attribute:
                    if _tools.isQuantity(getattr(self, attr)):
                        equal_attribute = _np.all(getattr(self, attr).value == getattr(other, attr).value)
                        equal_attribute = equal_attribute and _np.all(
                            getattr(self, attr).unit.is_equivalent(getattr(other, attr).unit)
                        )
                if not equal_attribute:
                    return False
                equal = equal and equal_attribute
            return equal
        return NotImplemented

    def __hash__(self):
        # Overrides the default implementation
        data = []
        for d in sorted(self.__dict__.items()):
            try:
                data.append((d[0], tuple(d[1])))
            except:  # noqa: E722
                data.append(d)
        data = tuple(data)
        return hash(data)

    def __add__(self, other):
        # Overrides the default implementation
        if isinstance(other, Stars):
            if self.N == 0 and other.N == 0:
                return Stars()
            else:
                return Stars(
                    m=_np.concatenate((self.m, other.m)),
                    b=_np.concatenate((self.b, other.b)),
                    v=_np.concatenate((self.v, other.v)),
                    inc=_np.concatenate((self.inc, other.inc)),
                    omega=_np.concatenate((self.omega, other.omega)),
                    Omega=_np.concatenate((self.Omega, other.Omega)),
                )
        elif isinstance(other, Star):
            if self.N == 0 and other.N == 0:
                return Stars()
            else:
                return Stars(
                    m=_np.concatenate((self.m, [other.m])),
                    b=_np.concatenate((self.b, [other.b])),
                    v=_np.concatenate((self.v, [other.v])),
                    inc=_np.concatenate((self.inc, [other.inc])),
                    omega=_np.concatenate((self.omega, [other.omega])),
                    Omega=_np.concatenate((self.Omega, [other.Omega])),
                )
        return NotImplemented
N property

The total number of Stars.

argument_periastron property writable

The argument of periastron of the Stars, alias of omega (default units: radians).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new values for the argument of periastron. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

impact_parameter property writable

Set the impact parameters of the Stars, alias of b (default units: AU).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new impact parameter values. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

impulse_gradient property

Calculate the impulse gradient for a flyby star.

\[\frac{2GM_\star}{V_\star b_\star^2}\]
inclination property writable

The inclinations of the Stars, alias of inc (default units: radians).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new inclination values. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

labels property

A list of labels for the parameters of the Stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

["Mass", "Impact Parameter", "Velocity", "Inclination", "Argument of the Periastron", "Longitude of the Ascending Node"]

longitude_ascending_node property writable

The longitude of the ascending node of the Stars, alias of Omega (default units: radians).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new longitude of the ascending node values. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

mass property writable

Set the masses of the Stars, alias of m (default units: Msun).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new mass values. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

mean_mass property

The mean mass of the Stars.

median_mass property

The median mass of the Stars.

param_dict property

A dictionary of the values of the parameters of the Stars including: Mass, "m"; Impact Parameter, "b"; Velocity, "v"; Inclination, "inc"; Argument of the Periastron, "omega"; and Longitude of the Ascending Node, "Omega".

{"m": stars.m, "b": stars.b, "v": stars.v, "inc": stars.inc, "omega": stars.omega, "Omega": stars.Omega}

param_values property

A list of the values of the parameters of the Stars in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

[m.value, b.value, v.value, inc.value, omega.value, Omega.value]

params property

A list of the parameters of the Stars (with units) in order of: Mass, m; Impact Parameter, b; Velocity, v; Inclination, inc; Argument of the Periastron, omega; and Longitude of the Ascending Node, Omega

[m, b, v, inc, omega, Omega]

shape property

The shape of the Stars arrays.

velocity property writable

Set the velocities at infinity of the Stars, alias of v (default units: km/s).

Parameters:

Name Type Description Default
value list, ndarray, or Quantity

The new velocity values. Can be set with a list such that len(value) == len(Stars).

required

Raises:

Type Description
ListLengthException

If the length of the provided list does not match the number of Stars.

IncompatibleListException

If the provided list is not compatible.

copy()

Returns a deep copy of the Stars.

Source code in src/airball/stars.py
1059
1060
1061
def copy(self):
    """Returns a deep copy of the Stars."""
    return _deepcopy(self)
eccentricity(sim)

The eccentricity of the Stars, alias for e(sim).

Parameters:

Name Type Description Default
sim Simulation

The REBOUND Simulation to use for calculating the eccentricity.

required

Returns:

Name Type Description
eccentricity ndarray

The eccentricity of the Stars.

Source code in src/airball/stars.py
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def eccentricity(self, sim):
    """
    The eccentricity of the Stars, alias for `e(sim)`.

    Args:
      sim (Simulation): The REBOUND Simulation to use for calculating the eccentricity.

    Returns:
      eccentricity (ndarray): The eccentricity of the Stars.
    """
    return self.e(sim)
periastron(sim)

The periastron of the Stars, alias for q(sim).

Parameters:

Name Type Description Default
sim Simulation

The REBOUND Simulation to use for calculating the periastron.

required

Returns:

Name Type Description
periastron ndarray

The periastron of the Stars.

Source code in src/airball/stars.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
def periastron(self, sim):
    """
    The periastron of the Stars, alias for `q(sim)`.

    Args:
      sim (Simulation): The REBOUND Simulation to use for calculating the periastron.

    Returns:
      periastron (ndarray): The periastron of the Stars.
    """
    return self.q(sim)
save(filename)

Save the current instance of the Stars class to a file using pickle.

Parameters:

Name Type Description Default
filename str

The name of the file to save the instance to. The file will be saved in binary format.

required
Example
import airball

se = airball.OpenCluster()
stars = se.random_stars(100)
stars.save("open_cluster.stars")
Source code in src/airball/stars.py
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def save(self, filename):
    """
    Save the current instance of the Stars class to a file using pickle.

    Args:
      filename (str): The name of the file to save the instance to. The file will be saved in binary format.

    Example:
      ```python
      import airball

      se = airball.OpenCluster()
      stars = se.random_stars(100)
      stars.save("open_cluster.stars")
      ```
    """
    if not isinstance(filename, (str, Path)):
        raise ValueError("Filename must be a string or Path.")
    with open(filename, "wb") as pfile:
        _pickle.dump(self, pfile, protocol=_pickle.HIGHEST_PROTOCOL)
sortby(key, sim=None, argsort=False)

Sort the Stars in ascending order by a defining parameter.

Parameters:

Name Type Description Default
key str

The parameter to sort by. Options include: 'm' (mass), 'b' (impact parameter), 'v' (relative velocity at infinity), 'inc' (inclination), 'omega' (argument of the periastron), 'Omega' (longitude of the ascending node), 'q' (periapsis), 'e' (eccentricity). For 'q' and 'e', a REBOUND Simulation is required.

required
sim Simulation

The REBOUND Simulation to use for sorting by 'q' and 'e'. Default is None.

None
argsort bool

If True, return the indices used to sort the Stars. Default is False.

False

Returns:

Name Type Description
indices list or None

The indices used to sort the Stars, if argsort is True. Otherwise, None and sorting is done in place.

Info

The Stars can also be sorted arbitrarily by providing a list of indices of length len(stars) as the key.

Examples:

import airball

stars = airball.Stars(m=[1, 2, 3], b=[3, 2, 1], v=[6, 5, 7])
stars.sortby("b")
inds = stars.sortby("v", argsort=True)
import airball
import rebound

sim = rebound.Simulation()
sim.add(m=1)
sim.add(m=5e-5, a=30, e=0.01)
stars = airball.Stars(airball.OpenCluster(), size=100)
stars.sortby("q", sim=sim)
import airball

stars = airball.Stars(airball.LocalNeighborhood(), size=5)
inds = [0, 4, 1, 3, 2]
stars.sortby(inds)
Source code in src/airball/stars.py
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
def sortby(self, key, sim=None, argsort=False):
    """
    Sort the Stars in ascending order by a defining parameter.

    Args:
      key (str): The parameter to sort by. Options include: 'm' (mass), 'b' (impact parameter), 'v' (relative velocity at infinity), 'inc' (inclination), 'omega' (argument of the periastron), 'Omega' (longitude of the ascending node), 'q' (periapsis), 'e' (eccentricity). For 'q' and 'e', a REBOUND Simulation is required.
      sim (Simulation, optional): The REBOUND Simulation to use for sorting by 'q' and 'e'. Default is None.
      argsort (bool, optional): If True, return the indices used to sort the Stars. Default is False.

    Returns:
      indices (list or None): The indices used to sort the Stars, if argsort is True. Otherwise, None and sorting is done in place.

    !!! Info
        The Stars can also be sorted arbitrarily by providing a list of indices of length len(stars) as the key.

    Examples:
      ```python
      import airball

      stars = airball.Stars(m=[1, 2, 3], b=[3, 2, 1], v=[6, 5, 7])
      stars.sortby("b")
      inds = stars.sortby("v", argsort=True)
      ```

      ```python
      import airball
      import rebound

      sim = rebound.Simulation()
      sim.add(m=1)
      sim.add(m=5e-5, a=30, e=0.01)
      stars = airball.Stars(airball.OpenCluster(), size=100)
      stars.sortby("q", sim=sim)
      ```

      ```python
      import airball

      stars = airball.Stars(airball.LocalNeighborhood(), size=5)
      inds = [0, 4, 1, 3, 2]
      stars.sortby(inds)
      ```
    """

    inds = _np.arange(len(self))
    if key == "m" or key == "mass":
        inds = _np.argsort(self.m)
    elif key == "b" or key == "impact" or key == "impact param" or key == "impact parameter":
        inds = _np.argsort(self.b)
    elif key == "v" or key == "vinf" or key == "v_inf" or key == "velocity":
        inds = _np.argsort(self.v)
    elif key == "inc" or key == "inclination" or key == "i" or key == "I":
        inds = _np.argsort(self.inc)
    elif key == "omega" or key == "ω" or key == "argument_periastron":
        inds = _np.argsort(self.omega)
    elif key == "Omega" or key == "Ω" or key == "longitude_ascending_node":
        inds = _np.argsort(self.Omega)
    elif key == "q" or key == "peri" or key == "perihelion" or key == "periastron" or key == "periapsis":
        if isinstance(sim, _rebound.Simulation):
            inds = _np.argsort(self.q(sim))
        else:
            raise InvalidParameterTypeException()
    elif key == "e" or key == "eccentricity":
        if isinstance(sim, _rebound.Simulation):
            inds = _np.argsort(self.e(sim))
        else:
            raise InvalidParameterTypeException()
    elif _tools.isList(key):
        print(key)
        if len(key) != len(self):
            raise ListLengthException(f"Difference of key: {len(key)} and stars: {len(self)}.")
        inds = _np.array(key)
    else:
        raise InvalidValueForKeyException()

    if argsort:
        return inds
    else:
        self.m[:] = self.m[inds]
        self.b[:] = self.b[inds]
        self.v[:] = self.v[inds]
        self.inc[:] = self.inc[inds]
        self.omega[:] = self.omega[inds]
        self.Omega[:] = self.Omega[inds]
stats(returned=False)

Prints a summary of the current stats of the Stars object. The stats are returned as a string if returned=True.

Source code in src/airball/stars.py
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
def stats(self, returned=False):
    """
    Prints a summary of the current stats of the Stars object.
    The stats are returned as a string if `returned=True`.
    """
    s = f"<{self.__module__}.{type(self).__name__} object at {hex(id(self))}, "
    s += f"N={f'{self.N:,.0f}' if len(self.shape) == 1 else self.shape}"
    if self.N > 0:
        s += f", m= {_np.min(self.m.value):,.3f}-{_np.max(self.m.value):,.3f} {self.units['mass']}"
    if self.N > 0:
        s += f", b= {_np.min(self.b.value):,.0f}-{_np.max(self.b.value):,.0f} {self.units['length']}"
    if self.N > 0:
        s += f", v= {_np.min(self.v.value):,.0f}-{_np.max(self.v.value):,.0f} {self.units['velocity']}"
    s += f"{f', Environment={self.environment.name}' if self.environment is not None else ''}"
    s += ">"
    if returned:
        return s
    else:
        print(s)