Commit 2100a072 authored by Robert Izzard's avatar Robert Izzard
Browse files

sync minor changes to notebooks: chemistry in particular changed the filename...

sync minor changes to notebooks: chemistry in particular changed the filename to save in the examples directory (jupyter has no access to /tmp/ typically)
parent ca7f274b
Loading
Loading
Loading
Loading
Loading
+30 −99

File changed.

Preview size limit exceeded, changes collapsed.

+13 −14
Original line number Diff line number Diff line
%% Cell type:markdown id:bbbaafbb-fd7d-4b73-a970-93506ba35d71 tags:

# Running populations to analyse chemistry
This notebook will show you how to evolve a population of stars to analyse their stellar chemistry

First, we import various modules and set up a temporary directory space.

%% Cell type:code id:bf6b8673-a2b5-4b50-ad1b-e90671f57470 tags:

``` python
import os

from binarycpython.utils.functions import temp_dir, output_lines
from binarycpython import Population

TMP_DIR = temp_dir("notebooks", "notebook_population", clean_path=True)
```

%% Cell type:markdown id:c2ab0979-6575-481d-9c1c-ca98517b2437 tags:

### Binary-star population
We now set up a population that samples binary systems by adding extra grid variables. Below is an example of a full script that runs a binary population, using the ensemble's chemistry sampling to output JSON data to a file.

%% Cell type:code id:79acdbb2-7dd6-45c4-9609-80994f03619a tags:

``` python
# Create population object
example_pop = Population()

# If you want verbosity, set this before other things
example_pop.set(verbosity=0)

# Setting values can be done via .set(<parameter_name>=<value>)
example_pop.set(
    # binary_c physics options
    max_evolution_time=15000,  # bse_options

    # set up the ensemble
    ensemble=True, # True : want to turn on the ensemble
    ensemble_defer=True, # True : wait until all stars have run to output the ensemble data
    ensemble_dt=1000.0, # Ensemble time resolution: not really required for the chemistry, so leave long (1e3)
    ensemble_filter_CHEMISTRY=True, # chemistry

    num_cores=2,  # number of CPU cores
    tmp_dir=TMP_DIR, # temporary file space

    # Custom options: the data directory and the output filename
    data_dir=os.path.join(
        TMP_DIR, "example_python_population_result"
    ),  # custom_options
    base_filename="example_pop.dat",  # custom_options
)

#########################################
# Set up phase space parameter sampling
#########################################

# Add grid variables' resolution: these are
# the number of stars on each side of the
# parameter space cubioid.
#
# The larger the number, the longer your
# grid will take to run.
resolution = {
    "M_1": 3, # primary mass
    "q": 3,   # mass ratio
    "per": 3  # orbital period
}

# Mass
example_pop.add_sampling_variable(
    name="lnm1",
    longname="Primary mass",
    valuerange=[2, 100],
    samplerfunc="self.const_linear(math.log(2), math.log(150), {})".format(resolution["M_1"]),
    precode="M_1=math.exp(lnm1)",
    probdist="self.three_part_powerlaw(M_1, 0.1, 0.5, 1.0, 150, -1.3, -2.3, -2.3)*M_1",
    dphasevol="dlnm1",
    parameter_name="M_1",
    condition="",  # Impose a condition on this grid variable. Mostly for a check for yourself
)

# Mass ratio
example_pop.add_sampling_variable(
    name="q",
    longname="Mass ratio",
    valuerange=["0.1/M_1", 1],
    samplerfunc="self.const_linear(0.1/M_1, 1, {})".format(resolution['q']),
    probdist="self.flatsections(q, [{'min': 0.1/M_1, 'max': 1.0, 'height': 1}])",
    dphasevol="dq",
    precode="M_2 = q * M_1",
    parameter_name="M_2",
    condition="",  # Impose a condition on this grid variable. Mostly for a check for yourself
)

#
example_pop.add_sampling_variable(
   name="log10per", # in days
   longname="log10(Orbital_Period)",
   valuerange=[0.15, 8.0],
   samplerfunc="self.const_linear(0.15, 8.0, {})".format(resolution["per"]),
   precode="""orbital_period = 10** log10per
sep = calc_sep_from_period(M_1, M_2, orbital_period)
sep_min = calc_sep_from_period(M_1, M_2, 10**0.15)
sep_max = calc_sep_from_period(M_1, M_2, 10**5.5)""",
   probdist="self.sana12(M_1, M_2, sep, orbital_period, sep_min, sep_max, math.log10(10**0.15), math.log10(10**5.5), -0.55)",
   parameter_name="orbital_period",
   dphasevol="dlog10per",
)

######################################################################
# Export settings and evolve the stellar population
######################################################################
example_pop.export_all_info()
example_pop.evolve()

######################################################################
# Population has run: save the data
######################################################################

# Make JSON output filename
outfile = os.path.join('/tmp/',
                       'ensemble_output.json.bz2')
outfile = os.path.join('ensemble_output.json.bz2')

# Always convert to an absolute path.
outfile = os.path.abspath(outfile)
print(f"outfile = {outfile}")

# Remove the outfile if it exists.
if os.path.exists(outfile):
    os.remove(outfile)

# Write output to outfile.
example_pop.write_ensemble(outfile,
                           sort_keys=True,
                           indent=4)

# We are done! The data should be in outfile.
print(f"ensemble has been written to {outfile}")

```

%% Output

    Grid has handled 8 stars with a total probability of 0.0307911
    
    **********************************
    *             Dry run            *
    *      Total starcount is 8      *
    * Total probability is 0.0307911 *
    **********************************
    
    Signalling processes to stop
    
    ****************************************************
    *                Process 1 finished:               *
    *  generator started at 2025-08-14T09:31:33.050846 *
    * generator finished at 2025-08-14T09:31:34.658149 *
    *                   total: 1.61s                   *
    *           of which 1.39s with binary_c           *
    *  generator started at 2025-08-17T10:44:12.138115 *
    * generator finished at 2025-08-17T10:44:13.443102 *
    *                   total: 1.30s                   *
    *           of which 1.07s with binary_c           *
    *                   Ran 4 systems                  *
    *       with a total probability of 0.0223549      *
    *         This thread had 0 failing systems        *
    *       with a total failed probability of 0       *
    *   Skipped a total of 0 zero-probability systems  *
    *                                                  *
    ****************************************************
    
    
    ****************************************************
    *                Process 0 finished:               *
    *  generator started at 2025-08-14T09:31:33.043713 *
    * generator finished at 2025-08-14T09:31:34.944496 *
    *                   total: 1.90s                   *
    *           of which 1.65s with binary_c           *
    *  generator started at 2025-08-17T10:44:12.134005 *
    * generator finished at 2025-08-17T10:44:13.623680 *
    *                   total: 1.49s                   *
    *           of which 1.27s with binary_c           *
    *                   Ran 4 systems                  *
    *      with a total probability of 0.00843624      *
    *         This thread had 0 failing systems        *
    *       with a total failed probability of 0       *
    *   Skipped a total of 0 zero-probability systems  *
    *                                                  *
    ****************************************************
    
    
    **********************************************************
    *  Population-51902290038049ed98ec3bfa3e716bdc finished! *
    *  Population-945f0662dd8b434483cb20cf5493e9bd finished! *
    *           The total probability is 0.0307911.          *
    *  It took a total of 2.25s to run 8 systems on 2 cores  *
    *                   = 4.50s of CPU time.                 *
    *              Maximum memory use 560.961 MB             *
    *  It took a total of 1.82s to run 8 systems on 2 cores  *
    *                   = 3.64s of CPU time.                 *
    *              Maximum memory use 569.117 MB             *
    **********************************************************
    
    No failed systems were found in this run.
    outfile = /tmp/ensemble_output.json.bz2
    ensemble has been written to /tmp/ensemble_output.json.bz2

%% Cell type:code id:247f2229-37fc-42d1-9f20-4dc7aa295ee4 tags:

``` python
```
+13067 −11640

File changed.

Preview size limit exceeded, changes collapsed.