cosmic-popsynth 3.6.2__cp313-cp313-macosx_14_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cosmic/evolve.py ADDED
@@ -0,0 +1,607 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (C) Scott Coughlin (2017 - 2021)
3
+ #
4
+ # This file is part of cosmic.
5
+ #
6
+ # cosmic is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # cosmic is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with cosmic. If not, see <http://www.gnu.org/licenses/>.
18
+
19
+ """`evolve`
20
+ """
21
+
22
+ from cosmic import _evolvebin
23
+ from . import utils
24
+ from .sample import initialbinarytable
25
+ from .checkstate import set_checkstates
26
+
27
+ from schwimmbad import MultiPool
28
+
29
+ import numpy as np
30
+ import pandas as pd
31
+ import warnings
32
+ import os
33
+ import sys
34
+ try:
35
+ import multiprocessing
36
+ multiprocessing.set_start_method("fork")
37
+ except RuntimeError:
38
+ pass
39
+
40
+
41
+ __author__ = 'Scott Coughlin <scott.coughlin@ligo.org>'
42
+ __credits__ = ['Katelyn Breivik <katie.breivik@gmail.com>',
43
+ 'Michael Zevin <zevin@northwestern.edu>',
44
+ 'digman.12@osu.edu',
45
+ 'Tom Wagg <tomjwagg@gmail.com>']
46
+ __all__ = ['Evolve']
47
+
48
+
49
+ # Make this match the ordering of all_cols in bpp_array.f
50
+ ALL_COLUMNS = ['tphys', 'mass_1', 'mass_2', 'kstar_1', 'kstar_2', 'sep', 'porb',
51
+ 'ecc', 'RRLO_1', 'RRLO_2', 'evol_type', 'aj_1', 'aj_2', 'tms_1',
52
+ 'tms_2', 'massc_he_layer_1', 'massc_he_layer_2', 'massc_co_layer_1', 'massc_co_layer_2',
53
+ 'rad_1', 'rad_2', 'mass0_1',
54
+ 'mass0_2', 'lum_1', 'lum_2', 'teff_1', 'teff_2', 'radc_1',
55
+ 'radc_2', 'menv_1', 'menv_2', 'renv_1', 'renv_2', 'omega_spin_1',
56
+ 'omega_spin_2', 'B_1', 'B_2', 'bacc_1', 'bacc_2', 'tacc_1',
57
+ 'tacc_2', 'epoch_1', 'epoch_2', 'bhspin_1', 'bhspin_2',
58
+ 'deltam_1', 'deltam_2', 'SN_1', 'SN_2', 'bin_state', 'merger_type', 'metallicity']
59
+
60
+ INTEGER_COLUMNS = ["bin_state", "bin_num", "kstar_1", "kstar_2", "SN_1", "SN_2", "evol_type"]
61
+
62
+
63
+ BPP_COLUMNS = ['tphys', 'mass_1', 'mass_2', 'kstar_1', 'kstar_2',
64
+ 'sep', 'porb', 'ecc', 'RRLO_1', 'RRLO_2', 'evol_type',
65
+ 'aj_1', 'aj_2', 'tms_1', 'tms_2',
66
+ 'massc_he_layer_1', 'massc_he_layer_2', 'massc_co_layer_1', 'massc_co_layer_2', 'rad_1', 'rad_2',
67
+ 'mass0_1', 'mass0_2', 'lum_1', 'lum_2', 'teff_1', 'teff_2',
68
+ 'radc_1', 'radc_2', 'menv_1', 'menv_2', 'renv_1', 'renv_2',
69
+ 'omega_spin_1', 'omega_spin_2', 'B_1', 'B_2', 'bacc_1', 'bacc_2',
70
+ 'tacc_1', 'tacc_2', 'epoch_1', 'epoch_2',
71
+ 'bhspin_1', 'bhspin_2']
72
+
73
+ BCM_COLUMNS = ['tphys', 'kstar_1', 'mass0_1', 'mass_1', 'lum_1', 'rad_1',
74
+ 'teff_1', 'massc_he_layer_1', 'massc_co_layer_1', 'radc_1', 'menv_1', 'renv_1', 'epoch_1',
75
+ 'omega_spin_1', 'deltam_1', 'RRLO_1', 'kstar_2', 'mass0_2', 'mass_2',
76
+ 'lum_2', 'rad_2', 'teff_2', 'massc_he_layer_2', 'massc_co_layer_2', 'radc_2', 'menv_2',
77
+ 'renv_2', 'epoch_2', 'omega_spin_2', 'deltam_2', 'RRLO_2',
78
+ 'porb', 'sep', 'ecc', 'B_1', 'B_2',
79
+ 'SN_1', 'SN_2', 'bin_state', 'merger_type']
80
+
81
+ KICK_COLUMNS = ['star', 'disrupted', 'natal_kick', 'phi', 'theta', 'mean_anomaly',
82
+ 'delta_vsysx_1', 'delta_vsysy_1', 'delta_vsysz_1', 'vsys_1_total',
83
+ 'delta_vsysx_2', 'delta_vsysy_2', 'delta_vsysz_2', 'vsys_2_total',
84
+ 'theta_euler', 'phi_euler', 'psi_euler', 'randomseed', 'bin_num']
85
+
86
+ # We use the list of column in the initialbinarytable function to initialize
87
+ # the list of columns that we will send to the fortran evolv2 function.
88
+ # we also send this in a specific order so this help ensures that the list that
89
+ # is created at the end has a consistent order
90
+ if sys.version_info.major == 2 and sys.version_info.minor == 7:
91
+ INITIAL_CONDITIONS_PASS_COLUMNS = initialbinarytable.INITIAL_CONDITIONS_COLUMNS[:]
92
+ else:
93
+ INITIAL_CONDITIONS_PASS_COLUMNS = initialbinarytable.INITIAL_CONDITIONS_COLUMNS.copy()
94
+
95
+ INITIAL_CONDITIONS_BSE_COLUMNS = ['neta', 'bwind', 'hewind', 'alpha1', 'lambdaf',
96
+ 'ceflag', 'tflag', 'ifflag', 'wdflag', 'pisn', 'rtmsflag',
97
+ 'bhflag', 'remnantflag', 'grflag', 'bhms_coll_flag', 'wd_mass_lim',
98
+ 'cekickflag', 'cemergeflag', 'cehestarflag',
99
+ 'mxns', 'pts1', 'pts2', 'pts3',
100
+ 'ecsn', 'ecsn_mlow', 'aic', 'ussn', 'sigma', 'sigmadiv',
101
+ 'bhsigmafrac', 'polar_kick_angle',
102
+ 'natal_kick_array', 'qcrit_array',
103
+ 'beta', 'xi', 'acc2', 'epsnov',
104
+ 'eddfac', 'gamma', 'don_lim', 'acc_lim',
105
+ 'bdecayfac', 'bconst', 'ck',
106
+ 'windflag', 'qcflag', 'eddlimflag',
107
+ 'fprimc_array', 'dtp', 'randomseed',
108
+ 'bhspinflag', 'bhspinmag', 'rejuv_fac', 'rejuvflag', 'htpmb',
109
+ 'ST_cr', 'ST_tide', 'rembar_massloss', 'zsun', 'kickflag']
110
+
111
+ INITIAL_CONDITIONS_MISC_COLUMN = ['bin_num']
112
+
113
+ # Add the BSE COLUMSN and MISC COLUMN to the PASS_COLUMNS list
114
+ INITIAL_CONDITIONS_PASS_COLUMNS.extend(INITIAL_CONDITIONS_BSE_COLUMNS)
115
+ INITIAL_CONDITIONS_PASS_COLUMNS.extend(INITIAL_CONDITIONS_MISC_COLUMN)
116
+
117
+ if sys.version_info.major == 2 and sys.version_info.minor == 7:
118
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS = INITIAL_CONDITIONS_PASS_COLUMNS[:]
119
+ else:
120
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS = INITIAL_CONDITIONS_PASS_COLUMNS.copy()
121
+
122
+ for col in ['natal_kick_array', 'qcrit_array', 'fprimc_array']:
123
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS.remove(col)
124
+
125
+ NATAL_KICK_COLUMNS = ['natal_kick',
126
+ 'phi',
127
+ 'theta',
128
+ 'mean_anomaly',
129
+ 'randomseed']
130
+
131
+ FLATTENED_NATAL_KICK_COLUMNS = []
132
+ for sn_idx in range(2):
133
+ for idx, column_name in enumerate(NATAL_KICK_COLUMNS):
134
+ FLATTENED_NATAL_KICK_COLUMNS.append(column_name + '_{0}'.format(sn_idx + 1))
135
+
136
+ QCRIT_COLUMNS = ['qcrit_{0}'.format(kstar) for kstar in range(0, 16)]
137
+ FPRIMC_COLUMNS = ['fprimc_{0}'.format(kstar) for kstar in range(0, 16)]
138
+
139
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS.extend(FLATTENED_NATAL_KICK_COLUMNS)
140
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS.extend(QCRIT_COLUMNS)
141
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS.extend(FPRIMC_COLUMNS)
142
+
143
+ # BSE doesn't need the binary fraction, so just add to columns for saving
144
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS.insert(7, 'binfrac')
145
+
146
+
147
+ class Evolve(object):
148
+ def __init__():
149
+ '''
150
+ initialize Evolve
151
+ '''
152
+
153
+ @classmethod
154
+ def evolve(self, initialbinarytable, pool=None, bpp_columns=None, bcm_columns=None, **kwargs):
155
+ """After setting a number of initial conditions we evolve the system.
156
+
157
+ Parameters
158
+ ----------
159
+ initialbinarytable : DataFrame
160
+ Initial conditions of the binary
161
+
162
+ pool : Multiprocessing pool
163
+ Pool of workers to use to evolve systems in parallel
164
+
165
+ bpp_columns : list, optional, default: None
166
+ Columns to save in the bpp table (key evolutionary stage table)
167
+
168
+ bcm_columns : list, optional, default: None
169
+ Columns to save in the bcm table (detailed evolution table)
170
+
171
+ **kwargs:
172
+ There are three ways to tell evolve and thus the fortran
173
+ what you want all the flags and other BSE specific
174
+ parameters to be. If you pass both a dictionary of flags and/or a inifile
175
+ and a table with the BSE parameters in the columns,
176
+ the column values will be overwritten by
177
+ what is in the dictionary or ini file.
178
+
179
+ NUMBER 1: PASS A DICTIONARY OF FLAGS
180
+
181
+ BSEDict
182
+
183
+ NUMBER 2: PASS A PANDAS DATA FRAME WITH PARAMS DEFINED AS COLUMNS
184
+
185
+ All you need is the initialbinarytable if the all
186
+ the BSE parameters are defined as columns
187
+
188
+ NUMBER 3: PASS PATH TO A INI FILE WITH THE FLAGS DEFINED
189
+
190
+ params
191
+
192
+ randomseed : `int`, optional, default let numpy choose for you
193
+ If you would like the random seed that the underlying fortran code
194
+ uses to be the same for all of the initial conditions you passed
195
+ then you can send this keyword argument in. It is recommended
196
+ to just let numpy choose a random number as the Fortran random seed
197
+ and then this number will be returned as a column in the
198
+ initial binary table so that you can reproduce the results.
199
+
200
+ nproc : `int`, optional, default: 1
201
+ number of CPUs to use to evolve systems
202
+ in parallel
203
+
204
+ idx : `int`, optional, default: 0
205
+ initial index of the bcm/bpp arrays
206
+
207
+ dtp : `float`, optional: default: tphysf
208
+ timestep size in Myr for bcm output where tphysf
209
+ is total evolution time in Myr
210
+
211
+ n_per_block : `int`, optional, default: -1
212
+ number of systems to evolve in a block with
213
+ _evolve_multi_system, to allow larger multiprocessing
214
+ queues and reduced overhead. If less than 1 use _evolve_single_system
215
+
216
+ Returns
217
+ -------
218
+ output_bpp : :class:`pandas.DataFrame`
219
+ Table of key evolutionary stages for each binary
220
+
221
+ output_bcm : :class:`pandas.DataFrame`
222
+ Table of detailed evolution for each binary
223
+
224
+ initialbinarytable : DataFrame
225
+ Initial conditions for each binary
226
+ """
227
+ idx = kwargs.pop('idx', 0)
228
+ nproc = min(kwargs.pop('nproc', 1), len(initialbinarytable))
229
+ n_per_block = kwargs.pop('n_per_block', -1)
230
+
231
+ if bpp_columns is None:
232
+ bpp_columns = BPP_COLUMNS
233
+ if bcm_columns is None:
234
+ bcm_columns = BCM_COLUMNS
235
+
236
+ # There are three ways to tell evolve and thus the fortran
237
+ # what you want all the flags and other BSE specific
238
+ # parameters to be
239
+
240
+ # NUMBER 1: PASS A DICTIONARY OF FLAGS
241
+ BSEDict = kwargs.pop('BSEDict', {})
242
+
243
+ # NUMBER 2: PASS A PANDAS DATA FRAME WITH PARAMS DEFINED AS COLUMNS
244
+
245
+ # All you need is the initialbinarytable with columns,
246
+ # If you pass both a dictionary of flags and/or a inifile
247
+ # and a table with the columns, the column values will be
248
+ # overwritten by what is in the dictionary or ini file
249
+
250
+ # NUMBER 3: PASS PATH TO A INI FILE WITH THE FLAGS DEFINED
251
+ params = kwargs.pop('params', None)
252
+
253
+ if BSEDict and params is not None:
254
+ raise ValueError('Please pass either a dictionary '
255
+ 'of BSE flags or a path to an inifle not both.')
256
+
257
+ if params is not None:
258
+ if not os.path.isfile(params):
259
+ raise ValueError("File does not exist, probably supplied incorrect "
260
+ "path to the inifile.")
261
+ BSEDict, _, _, _, _ = utils.parse_inifile(params)
262
+
263
+ # error check the parameters you are trying to pass to BSE
264
+ # if we sent in a table with the parameter names
265
+ # then we will temporarily create a dictionary
266
+ # in order to verify that the values in the table
267
+ # are valid
268
+ utils.error_check(BSEDict)
269
+
270
+ # check the initial conditions of the system and warn user if
271
+ # anything is weird about them, such as the star starts
272
+ # in Roche Lobe overflow
273
+ utils.check_initial_conditions(initialbinarytable)
274
+
275
+ # assign some columns based on keyword arguments but that
276
+ # can be overwritten by the params or BSEDict
277
+ if 'dtp' not in initialbinarytable.keys():
278
+ initialbinarytable = initialbinarytable.assign(dtp=kwargs.pop('dtp', initialbinarytable['tphysf']))
279
+ if 'randomseed' not in initialbinarytable.keys():
280
+ seed = np.random.randint(np.iinfo(np.int32).min, np.iinfo(np.int32).max, size=len(initialbinarytable))
281
+ initialbinarytable = initialbinarytable.assign(randomseed=kwargs.pop('randomseed', seed))
282
+ if 'bin_num' not in initialbinarytable.keys():
283
+ initialbinarytable = initialbinarytable.assign(bin_num=np.arange(idx, idx + len(initialbinarytable)))
284
+
285
+ # go through each item in the BSEDict and update the initialbinarytable
286
+ new_cols = {}
287
+ n = len(initialbinarytable)
288
+ idx = initialbinarytable.index
289
+ for k, v in list(BSEDict.items()):
290
+ # warn the user if they are overwriting a value
291
+ if k in initialbinarytable.columns:
292
+ warnings.warn(
293
+ "The value for {0} in initial binary table is being overwritten by the value of {0} "
294
+ "from either the params file or the BSEDict.".format(k)
295
+ )
296
+
297
+ # handle special cases where we need to expand arrays into multiple columns
298
+ if k == 'natal_kick_array':
299
+ initialbinarytable["natal_kick_array"] = [BSEDict['natal_kick_array']] * n
300
+ for j, column_name in enumerate(NATAL_KICK_COLUMNS):
301
+ for sn in range(2):
302
+ col = f"{column_name}_{sn+1}"
303
+ if col in initialbinarytable.columns:
304
+ initialbinarytable[col] = BSEDict['natal_kick_array'][sn][j]
305
+ else:
306
+ new_cols[col] = BSEDict['natal_kick_array'][sn][j]
307
+
308
+ elif k == 'qcrit_array':
309
+ initialbinarytable["qcrit_array"] = [BSEDict['qcrit_array']] * n
310
+ for kstar in range(16):
311
+ col = f"qcrit_{kstar}"
312
+ if col in initialbinarytable.columns:
313
+ initialbinarytable[col] = BSEDict['qcrit_array'][kstar]
314
+ else:
315
+ new_cols[col] = BSEDict['qcrit_array'][kstar]
316
+
317
+ elif k == 'fprimc_array':
318
+ initialbinarytable["fprimc_array"] = [BSEDict['fprimc_array']] * n
319
+ for kstar in range(16):
320
+ col = f"fprimc_{kstar}"
321
+ if col in initialbinarytable.columns:
322
+ initialbinarytable[col] = BSEDict['fprimc_array'][kstar]
323
+ else:
324
+ new_cols[col] = BSEDict['fprimc_array'][kstar]
325
+ else:
326
+ # base case: if it's present, overwrite, if not, add to a list of new columns (see below)
327
+ if k in initialbinarytable.columns:
328
+ initialbinarytable[k] = v
329
+ else:
330
+ new_cols[k] = v
331
+
332
+ # for columns that are new to the initial binary table, concat once
333
+ if new_cols:
334
+ new_df = pd.DataFrame(new_cols, index=idx)
335
+ initialbinarytable = pd.concat([initialbinarytable, new_df], axis=1)
336
+
337
+ # Here we perform two checks
338
+ # First, if the BSE parameters are not in the initial binary table
339
+ # and either a dictionary or an inifile was not provided
340
+ # then we need to raise an ValueError and tell the user to provide
341
+ # either a dictionary or an inifile or add more columns
342
+ if not BSEDict:
343
+ if ((not set(INITIAL_BINARY_TABLE_SAVE_COLUMNS).issubset(initialbinarytable.columns)) and
344
+ (not set(INITIAL_CONDITIONS_PASS_COLUMNS).issubset(initialbinarytable.columns))):
345
+ raise ValueError("You are passing BSE parameters as columns in the "
346
+ "initial binary table but not all BSE parameters are defined. "
347
+ "Please pass a BSEDict or a params file or make sure "
348
+ "you have all BSE parameters as columns {0} or {1}.".format(
349
+ INITIAL_BINARY_TABLE_SAVE_COLUMNS, INITIAL_CONDITIONS_PASS_COLUMNS))
350
+
351
+ # If you did not supply the natal kick or qcrit_array or fprimc_array in the BSEdict then we construct
352
+ # it from the initial conditions table
353
+ if ((pd.Series(FLATTENED_NATAL_KICK_COLUMNS).isin(initialbinarytable.keys()).all()) and
354
+ ('natal_kick_array' not in BSEDict)):
355
+ column_values = initialbinarytable[FLATTENED_NATAL_KICK_COLUMNS].values.reshape(-1,
356
+ 2,
357
+ len(NATAL_KICK_COLUMNS)).tolist()
358
+ initialbinarytable = initialbinarytable.assign(natal_kick_array=column_values)
359
+
360
+ if (pd.Series(QCRIT_COLUMNS).isin(initialbinarytable.keys()).all()) and ('qcrit_array' not in BSEDict):
361
+ initialbinarytable = initialbinarytable.assign(qcrit_array=initialbinarytable[QCRIT_COLUMNS].values.tolist())
362
+
363
+ if (pd.Series(FPRIMC_COLUMNS).isin(initialbinarytable.keys()).all()) and ('fprimc_array' not in BSEDict):
364
+ initialbinarytable = initialbinarytable.assign(fprimc_array=initialbinarytable[FPRIMC_COLUMNS].values.tolist())
365
+
366
+ # need to ensure that the order of parameters that we pass to BSE
367
+ # is correct
368
+ initial_conditions = initialbinarytable[INITIAL_CONDITIONS_PASS_COLUMNS].to_dict('records')
369
+
370
+ # we use different columns to save the BSE parameters because some
371
+ # of the parameters are list/arrays which we instead save as
372
+ # individual values because it makes saving to HDF5 easier/more efficient.
373
+ initialbinarytable = initialbinarytable[INITIAL_BINARY_TABLE_SAVE_COLUMNS]
374
+
375
+ # Allow a user to specify a custom time step sampling for certain parts of the evolution
376
+ timestep_conditions = kwargs.pop('timestep_conditions', [])
377
+ set_checkstates(timestep_conditions=timestep_conditions)
378
+
379
+ # set the indices of the columns to include in bpp table (+1 because fortran is 1-indexed)
380
+ col_inds_bpp = np.zeros(len(ALL_COLUMNS), dtype=int)
381
+ col_inds_bpp[:len(bpp_columns)] = [ALL_COLUMNS.index(col) + 1 for col in bpp_columns]
382
+
383
+ # save bpp column information in the initial conditions
384
+ for i in range(len(initial_conditions)):
385
+ initial_conditions[i]["n_col_bpp"] = len(bpp_columns)
386
+ initial_conditions[i]["col_inds_bpp"] = col_inds_bpp
387
+
388
+ # same for bcm
389
+ col_inds_bcm = np.zeros(len(ALL_COLUMNS), dtype=int)
390
+ col_inds_bcm[:len(bcm_columns)] = [ALL_COLUMNS.index(col) + 1 for col in bcm_columns]
391
+ for i in range(len(initial_conditions)):
392
+ initial_conditions[i]["n_col_bcm"] = len(bcm_columns)
393
+ initial_conditions[i]["col_inds_bcm"] = col_inds_bcm
394
+
395
+ # check if a pool was passed
396
+ if pool is None:
397
+ with MultiPool(processes=nproc) as pool:
398
+ # evolve systems
399
+ if n_per_block > 0:
400
+ initial_conditions = np.asarray(initial_conditions)
401
+ n_tot = initial_conditions.shape[0]
402
+ initial_conditions_blocked = []
403
+ itr_block = 0
404
+ while itr_block < n_tot:
405
+ itr_next = np.min([n_tot, itr_block+n_per_block])
406
+ initial_conditions_blocked.append(initial_conditions[itr_block:itr_next])
407
+ itr_block = itr_next
408
+ output = list(pool.map(_evolve_multi_system, initial_conditions_blocked))
409
+ else:
410
+ output = list(pool.map(_evolve_single_system, initial_conditions))
411
+ else:
412
+ # evolve systems
413
+ if n_per_block > 0:
414
+ initial_conditions = np.asarray(initial_conditions)
415
+ n_tot = initial_conditions.shape[0]
416
+ initial_conditions_blocked = []
417
+ itr_block = 0
418
+ while itr_block < n_tot:
419
+ itr_next = np.min([n_tot, itr_block+n_per_block])
420
+ initial_conditions_blocked.append(initial_conditions[itr_block:itr_next])
421
+ itr_block = itr_next
422
+ output = list(pool.map(_evolve_multi_system, initial_conditions_blocked))
423
+ else:
424
+ output = list(pool.map(_evolve_single_system, initial_conditions))
425
+
426
+ output = np.array(output, dtype=object)
427
+ bpp_arrays = np.vstack(output[:, 1])
428
+ bcm_arrays = np.vstack(output[:, 2])
429
+ kick_info_arrays = np.vstack(output[:, 3])
430
+
431
+ natal_kick_arrays = np.vstack(output[:, 4])
432
+ natal_kick_arrays = natal_kick_arrays.reshape(-1, 1, len(FLATTENED_NATAL_KICK_COLUMNS))
433
+
434
+ # update initial table with sampled kicks
435
+ to_add = {}
436
+ for idx, column in enumerate(FLATTENED_NATAL_KICK_COLUMNS):
437
+ if column not in initialbinarytable.columns:
438
+ to_add[column] = natal_kick_arrays[:, 0, idx]
439
+ else:
440
+ initialbinarytable[column] = natal_kick_arrays[:, 0, idx]
441
+
442
+ # if kicks weren't already present, add them
443
+ if to_add:
444
+ natal_kick_df = pd.DataFrame(to_add, index=initialbinarytable.index)
445
+ initialbinarytable = pd.concat([initialbinarytable, natal_kick_df], axis=1)
446
+
447
+ kick_info = pd.DataFrame(kick_info_arrays,
448
+ columns=KICK_COLUMNS,
449
+ index=kick_info_arrays[:, -1].astype(int))
450
+
451
+ bpp = pd.DataFrame(bpp_arrays,
452
+ columns=bpp_columns + ["bin_num"],
453
+ index=bpp_arrays[:, -1].astype(int))
454
+
455
+ bcm = pd.DataFrame(bcm_arrays,
456
+ columns=bcm_columns + ["bin_num"],
457
+ index=bcm_arrays[:, -1].astype(int))
458
+
459
+ # convert a subset of columns to integers
460
+ for col in INTEGER_COLUMNS:
461
+ if col in bpp.columns:
462
+ bpp[col] = bpp[col].astype(int)
463
+ if col in bcm.columns:
464
+ bcm[col] = bcm[col].astype(int)
465
+
466
+ # convert merger type to a padded string
467
+ if 'merger_type' in bpp.columns:
468
+ bpp.merger_type = bpp.merger_type.astype(int).astype(str).apply(lambda x: x.zfill(4))
469
+ if 'merger_type' in bcm.columns:
470
+ bcm.merger_type = bcm.merger_type.astype(int).astype(str).apply(lambda x: x.zfill(4))
471
+
472
+ return bpp, bcm, initialbinarytable, kick_info
473
+
474
+
475
+ def _evolve_single_system(f):
476
+ try:
477
+ f["kick_info"] = np.zeros((2, len(KICK_COLUMNS)-1))
478
+ # determine if we already have a compact object, if yes than one SN has already occured
479
+ if (f["kstar_1"] in range(10, 15)) or (f["kstar_2"] in range(10, 15)):
480
+ f["kick_info"][0, 0] = 1
481
+ # kstar, mass, orbital period (days), eccentricity, metaliccity, evolution time (millions of years)
482
+ _evolvebin.windvars.neta = f["neta"]
483
+ _evolvebin.windvars.bwind = f["bwind"]
484
+ _evolvebin.windvars.hewind = f["hewind"]
485
+ _evolvebin.cevars.alpha1 = f["alpha1"]
486
+ _evolvebin.cevars.lambdaf = f["lambdaf"]
487
+ _evolvebin.ceflags.ceflag = f["ceflag"]
488
+ _evolvebin.flags.tflag = f["tflag"]
489
+ _evolvebin.flags.ifflag = f["ifflag"]
490
+ _evolvebin.flags.wdflag = f["wdflag"]
491
+ _evolvebin.flags.rtmsflag = f["rtmsflag"]
492
+ _evolvebin.snvars.pisn = f["pisn"]
493
+ _evolvebin.flags.bhflag = f["bhflag"]
494
+ _evolvebin.flags.remnantflag = f["remnantflag"]
495
+ _evolvebin.ceflags.cekickflag = f["cekickflag"]
496
+ _evolvebin.ceflags.cemergeflag = f["cemergeflag"]
497
+ _evolvebin.ceflags.cehestarflag = f["cehestarflag"]
498
+ _evolvebin.flags.grflag = f["grflag"]
499
+ _evolvebin.flags.bhms_coll_flag = f["bhms_coll_flag"]
500
+ _evolvebin.flags.wd_mass_lim = f["wd_mass_lim"]
501
+ _evolvebin.snvars.mxns = f["mxns"]
502
+ _evolvebin.points.pts1 = f["pts1"]
503
+ _evolvebin.points.pts2 = f["pts2"]
504
+ _evolvebin.points.pts3 = f["pts3"]
505
+ _evolvebin.snvars.ecsn = f["ecsn"]
506
+ _evolvebin.snvars.ecsn_mlow = f["ecsn_mlow"]
507
+ _evolvebin.flags.aic = f["aic"]
508
+ _evolvebin.ceflags.ussn = f["ussn"]
509
+ _evolvebin.snvars.sigma = f["sigma"]
510
+ _evolvebin.snvars.sigmadiv = f["sigmadiv"]
511
+ _evolvebin.snvars.bhsigmafrac = f["bhsigmafrac"]
512
+ _evolvebin.snvars.polar_kick_angle = f["polar_kick_angle"]
513
+ _evolvebin.snvars.natal_kick_array = f["natal_kick_array"]
514
+ _evolvebin.cevars.qcrit_array = f["qcrit_array"]
515
+ _evolvebin.mtvars.don_lim = f["don_lim"]
516
+ _evolvebin.mtvars.acc_lim = f["acc_lim"]
517
+ _evolvebin.windvars.beta = f["beta"]
518
+ _evolvebin.windvars.xi = f["xi"]
519
+ _evolvebin.windvars.acc2 = f["acc2"]
520
+ _evolvebin.windvars.epsnov = f["epsnov"]
521
+ _evolvebin.windvars.eddfac = f["eddfac"]
522
+ _evolvebin.windvars.gamma = f["gamma"]
523
+ _evolvebin.flags.bdecayfac = f["bdecayfac"]
524
+ _evolvebin.magvars.bconst = f["bconst"]
525
+ _evolvebin.magvars.ck = f["ck"]
526
+ _evolvebin.flags.windflag = f["windflag"]
527
+ _evolvebin.flags.qcflag = f["qcflag"]
528
+ _evolvebin.flags.eddlimflag = f["eddlimflag"]
529
+ _evolvebin.tidalvars.fprimc_array = f["fprimc_array"]
530
+ _evolvebin.rand1.idum1 = f["randomseed"]
531
+ _evolvebin.flags.bhspinflag = f["bhspinflag"]
532
+ _evolvebin.snvars.bhspinmag = f["bhspinmag"]
533
+ _evolvebin.mixvars.rejuv_fac = f["rejuv_fac"]
534
+ _evolvebin.flags.rejuvflag = f["rejuvflag"]
535
+ _evolvebin.flags.htpmb = f["htpmb"]
536
+ _evolvebin.flags.st_cr = f["ST_cr"]
537
+ _evolvebin.flags.st_tide = f["ST_tide"]
538
+ _evolvebin.snvars.rembar_massloss = f["rembar_massloss"]
539
+ _evolvebin.metvars.zsun = f["zsun"]
540
+ _evolvebin.snvars.kickflag = f["kickflag"]
541
+ _evolvebin.cmcpass.using_cmc = 0
542
+
543
+ _evolvebin.col.n_col_bpp = f["n_col_bpp"]
544
+ _evolvebin.col.col_inds_bpp = f["col_inds_bpp"]
545
+ _evolvebin.col.n_col_bcm = f["n_col_bcm"]
546
+ _evolvebin.col.col_inds_bcm = f["col_inds_bcm"]
547
+
548
+ [bpp_index, bcm_index, kick_info] = _evolvebin.evolv2([f["kstar_1"], f["kstar_2"]],
549
+ [f["mass_1"], f["mass_2"]],
550
+ f["porb"], f["ecc"], f["metallicity"],
551
+ f["tphysf"], f["dtp"],
552
+ [f["mass0_1"], f["mass0_2"]],
553
+ [f["rad_1"], f["rad_2"]],
554
+ [f["lum_1"], f["lum_2"]],
555
+ [f["massc_1"], f["massc_2"]],
556
+ [f["radc_1"], f["radc_2"]],
557
+ [f["menv_1"], f["menv_2"]],
558
+ [f["renv_1"], f["renv_2"]],
559
+ [f["omega_spin_1"], f["omega_spin_2"]],
560
+ [f["B_1"], f["B_2"]],
561
+ [f["bacc_1"], f["bacc_2"]],
562
+ [f["tacc_1"], f["tacc_2"]],
563
+ [f["epoch_1"], f["epoch_2"]],
564
+ [f["tms_1"], f["tms_2"]],
565
+ [f["bhspin_1"], f["bhspin_2"]],
566
+ f["tphys"],
567
+ np.zeros(20),
568
+ np.zeros(20),
569
+ f["kick_info"])
570
+ bpp = _evolvebin.binary.bpp[:bpp_index, :f["n_col_bpp"]].copy()
571
+ _evolvebin.binary.bpp[:bpp_index, :f["n_col_bpp"]] = np.zeros(bpp.shape)
572
+ bcm = _evolvebin.binary.bcm[:bcm_index, :f["n_col_bcm"]].copy()
573
+ _evolvebin.binary.bcm[:bcm_index, :f["n_col_bcm"]] = np.zeros(bcm.shape)
574
+
575
+ bpp = np.hstack((bpp, np.ones((bpp.shape[0], 1))*f["bin_num"]))
576
+ bcm = np.hstack((bcm, np.ones((bcm.shape[0], 1))*f["bin_num"]))
577
+ kick_info = np.hstack((kick_info, np.ones((kick_info.shape[0], 1))*f["bin_num"]))
578
+
579
+ return f, bpp, bcm, kick_info, _evolvebin.snvars.natal_kick_array.copy()
580
+
581
+ except Exception as e:
582
+ print(e)
583
+ raise
584
+
585
+
586
+ def _evolve_multi_system(f):
587
+ try:
588
+ res_bcm = np.zeros(f.shape[0], dtype=object)
589
+ res_bpp = np.zeros(f.shape[0], dtype=object)
590
+ res_kick_info = np.zeros(f.shape[0], dtype=object)
591
+ res_natal_kick_array = np.zeros(f.shape[0], dtype=object)
592
+ for i in range(0, f.shape[0]):
593
+
594
+ # call evolve single system
595
+ _, bpp, bcm, kick_info, _ = _evolve_single_system(f[i])
596
+
597
+ # add results to pre-allocated list
598
+ res_bpp[i] = bpp
599
+ res_bcm[i] = bcm
600
+ res_kick_info[i] = kick_info
601
+ res_natal_kick_array[i] = _evolvebin.snvars.natal_kick_array
602
+
603
+ return f, np.vstack(res_bpp), np.vstack(res_bcm), np.vstack(res_kick_info), np.vstack(res_natal_kick_array)
604
+
605
+ except Exception as e:
606
+ print(e)
607
+ raise