repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
GraphLIME
GraphLIME-master/exp/noise_features/utils.py
import os import numpy as np from tqdm import tqdm import seaborn as sns import matplotlib.pyplot as plt import torch import torch.optim as optim import torch.nn.functional as F import torch_geometric.transforms as T from torch_geometric.datasets import Planetoid def prepare_data(args): dataset = args.dataset.title() dirname = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(dirname, '..', 'data', 'Planetoid') dataset = Planetoid(path, dataset, transform=T.NormalizeFeatures()) data = dataset[0] data = modify_train_mask(data) data = add_noise_features(data, args.num_noise) return data def modify_train_mask(data): num_nodes = data.x.size(0) num_train = int(num_nodes * 0.8) node_indices = np.random.choice(num_nodes, size=num_train, replace=False) new_train_mask = torch.zeros_like(data.train_mask) new_train_mask[node_indices] = 1 new_train_mask = new_train_mask > 0 new_val_mask = torch.zeros_like(data.val_mask) new_val_mask = new_val_mask > 0 new_test_mask = ~(new_train_mask + new_val_mask) data.train_mask = new_train_mask data.val_mask = new_val_mask data.test_mask = new_test_mask # val_mask = data.val_mask # test_mask = data.test_mask # new_train_mask = ~(val_mask + test_mask) # data.train_mask = new_train_mask return data def add_noise_features(data, num_noise): if not num_noise: return data num_nodes = data.x.size(0) noise_feat = torch.randn((num_nodes, num_noise)) noise_feat = noise_feat - noise_feat.mean(1, keepdim=True) data.x = torch.cat([data.x, noise_feat], dim=-1) return data def extract_test_nodes(data, num_samples): test_indices = data.test_mask.cpu().numpy().nonzero()[0] node_indices = np.random.choice(test_indices, num_samples).tolist() return node_indices def plot_dist(noise_feats, label=None, ymax=1.0, color=None, title=None, save_path=None): sns.set_style('darkgrid') ax = sns.distplot(noise_feats, hist=False, kde=True, kde_kws={'label': label}, color=color) plt.xlim(-3, 11) plt.ylim(ymin=0.0, ymax=ymax) if title: plt.title(title) if save_path: plt.savefig(save_path) return ax def train(model, data, args, verbose=True): optimizer = optim.Adam(model.parameters(), lr=args.model_lr, weight_decay=5e-4) train_loss_values, train_acc_values = [], [] test_loss_values, test_acc_values = [], [] best = np.inf bad_counter = 0 model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'model.pth') for epoch in tqdm(range(args.model_epochs), desc='Training', leave=False): if epoch == 0: print(' | Trainging | Validation |') print(' |-------------------|--------------------|') print(' Epoch | loss accuracy | loss accuracy |') print('-------|-------------------|--------------------|') train_loss, train_acc = train_on_epoch(model, optimizer, data) train_loss_values.append(train_loss.item()) train_acc_values.append(train_acc.item()) test_loss, test_acc = evaluate(model, data, data.test_mask) test_loss_values.append(test_loss.item()) test_acc_values.append(test_acc.item()) if test_loss_values[-1] < best: bad_counter = 0 log = ' {:3d} | {:.4f} {:.4f} | {:.4f} {:.4f} |'.format(epoch + 1, train_loss.item(), train_acc.item(), test_loss.item(), test_acc.item()) torch.save(model.state_dict(), model_path) log += ' save model to {}'.format(model_path) if verbose: tqdm.write(log) best = test_loss_values[-1] else: bad_counter += 1 print('-------------------------------------------------') model.load_state_dict(torch.load(model_path)) def train_on_epoch(model, optimizer, data): model.train() optimizer.zero_grad() output = model(data.x, data.edge_index) train_loss = F.nll_loss(output[data.train_mask], data.y[data.train_mask]) train_acc = accuracy(output[data.train_mask], data.y[data.train_mask]) train_loss.backward() optimizer.step() return train_loss, train_acc def evaluate(model, data, mask): model.eval() with torch.no_grad(): output = model(data.x, data.edge_index) loss = F.nll_loss(output[mask], data.y[mask]) acc = accuracy(output[mask], data.y[mask]) return loss, acc def accuracy(output, labels): _, pred = output.max(dim=1) correct = pred.eq(labels).double() correct = correct.sum() return correct / len(labels)
5,089
28.766082
97
py
GraphLIME
GraphLIME-master/exp/noise_features/models.py
import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv, GATConv class GCN(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.5): super(GCN, self).__init__() self.dropout = dropout self.conv1 = GCNConv(input_dim, hidden_dim) self.conv2 = GCNConv(hidden_dim, output_dim) def forward(self, x, edge_index): x = self.conv1(x, edge_index) x = F.relu(x) x = F.dropout(x, p=self.dropout, training=self.training) x = self.conv2(x, edge_index) return F.log_softmax(x, dim=1) class GAT(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, heads_1=8, heads_2=1, att_dropout=0.6, input_dropout=0.6): super(GAT, self).__init__() self.att_dropout = att_dropout self.input_dropout = input_dropout self.conv1 = GATConv(in_channels=input_dim, out_channels=hidden_dim // heads_1, heads=heads_1, concat=True, dropout=att_dropout) self.conv2 = GATConv(in_channels=hidden_dim, out_channels=output_dim, heads=heads_2, concat=False, dropout=att_dropout) def forward(self, x, edge_index): x = F.dropout(x, p=self.input_dropout, training=self.training) x = self.conv1(x, edge_index) x = F.elu(x) x = F.dropout(x, p=self.input_dropout, training=self.training) x = self.conv2(x, edge_index) return F.log_softmax(x, dim=1)
1,699
32.333333
116
py
arl-eegmodels
arl-eegmodels-master/EEGModels.py
""" ARL_EEGModels - A collection of Convolutional Neural Network models for EEG Signal Processing and Classification, using Keras and Tensorflow Requirements: (1) tensorflow == 2.X (as of this writing, 2.0 - 2.3 have been verified as working) To run the EEG/MEG ERP classification sample script, you will also need (4) mne >= 0.17.1 (5) PyRiemann >= 0.2.5 (6) scikit-learn >= 0.20.1 (7) matplotlib >= 2.2.3 To use: (1) Place this file in the PYTHONPATH variable in your IDE (i.e.: Spyder) (2) Import the model as from EEGModels import EEGNet model = EEGNet(nb_classes = ..., Chans = ..., Samples = ...) (3) Then compile and fit the model model.compile(loss = ..., optimizer = ..., metrics = ...) fitted = model.fit(...) predicted = model.predict(...) Portions of this project are works of the United States Government and are not subject to domestic copyright protection under 17 USC Sec. 105. Those portions are released world-wide under the terms of the Creative Commons Zero 1.0 (CC0) license. Other portions of this project are subject to domestic copyright protection under 17 USC Sec. 105. Those portions are licensed under the Apache 2.0 license. The complete text of the license governing this material is in the file labeled LICENSE.TXT that is a part of this project's official distribution. """ from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Activation, Permute, Dropout from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D from tensorflow.keras.layers import SeparableConv2D, DepthwiseConv2D from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import SpatialDropout2D from tensorflow.keras.regularizers import l1_l2 from tensorflow.keras.layers import Input, Flatten from tensorflow.keras.constraints import max_norm from tensorflow.keras import backend as K def EEGNet(nb_classes, Chans = 64, Samples = 128, dropoutRate = 0.5, kernLength = 64, F1 = 8, D = 2, F2 = 16, norm_rate = 0.25, dropoutType = 'Dropout'): """ Keras Implementation of EEGNet http://iopscience.iop.org/article/10.1088/1741-2552/aace8c/meta Note that this implements the newest version of EEGNet and NOT the earlier version (version v1 and v2 on arxiv). We strongly recommend using this architecture as it performs much better and has nicer properties than our earlier version. For example: 1. Depthwise Convolutions to learn spatial filters within a temporal convolution. The use of the depth_multiplier option maps exactly to the number of spatial filters learned within a temporal filter. This matches the setup of algorithms like FBCSP which learn spatial filters within each filter in a filter-bank. This also limits the number of free parameters to fit when compared to a fully-connected convolution. 2. Separable Convolutions to learn how to optimally combine spatial filters across temporal bands. Separable Convolutions are Depthwise Convolutions followed by (1x1) Pointwise Convolutions. While the original paper used Dropout, we found that SpatialDropout2D sometimes produced slightly better results for classification of ERP signals. However, SpatialDropout2D significantly reduced performance on the Oscillatory dataset (SMR, BCI-IV Dataset 2A). We recommend using the default Dropout in most cases. Assumes the input signal is sampled at 128Hz. If you want to use this model for any other sampling rate you will need to modify the lengths of temporal kernels and average pooling size in blocks 1 and 2 as needed (double the kernel lengths for double the sampling rate, etc). Note that we haven't tested the model performance with this rule so this may not work well. The model with default parameters gives the EEGNet-8,2 model as discussed in the paper. This model should do pretty well in general, although it is advised to do some model searching to get optimal performance on your particular dataset. We set F2 = F1 * D (number of input filters = number of output filters) for the SeparableConv2D layer. We haven't extensively tested other values of this parameter (say, F2 < F1 * D for compressed learning, and F2 > F1 * D for overcomplete). We believe the main parameters to focus on are F1 and D. Inputs: nb_classes : int, number of classes to classify Chans, Samples : number of channels and time points in the EEG data dropoutRate : dropout fraction kernLength : length of temporal convolution in first layer. We found that setting this to be half the sampling rate worked well in practice. For the SMR dataset in particular since the data was high-passed at 4Hz we used a kernel length of 32. F1, F2 : number of temporal filters (F1) and number of pointwise filters (F2) to learn. Default: F1 = 8, F2 = F1 * D. D : number of spatial filters to learn within each temporal convolution. Default: D = 2 dropoutType : Either SpatialDropout2D or Dropout, passed as a string. """ if dropoutType == 'SpatialDropout2D': dropoutType = SpatialDropout2D elif dropoutType == 'Dropout': dropoutType = Dropout else: raise ValueError('dropoutType must be one of SpatialDropout2D ' 'or Dropout, passed as a string.') input1 = Input(shape = (Chans, Samples, 1)) ################################################################## block1 = Conv2D(F1, (1, kernLength), padding = 'same', input_shape = (Chans, Samples, 1), use_bias = False)(input1) block1 = BatchNormalization()(block1) block1 = DepthwiseConv2D((Chans, 1), use_bias = False, depth_multiplier = D, depthwise_constraint = max_norm(1.))(block1) block1 = BatchNormalization()(block1) block1 = Activation('elu')(block1) block1 = AveragePooling2D((1, 4))(block1) block1 = dropoutType(dropoutRate)(block1) block2 = SeparableConv2D(F2, (1, 16), use_bias = False, padding = 'same')(block1) block2 = BatchNormalization()(block2) block2 = Activation('elu')(block2) block2 = AveragePooling2D((1, 8))(block2) block2 = dropoutType(dropoutRate)(block2) flatten = Flatten(name = 'flatten')(block2) dense = Dense(nb_classes, name = 'dense', kernel_constraint = max_norm(norm_rate))(flatten) softmax = Activation('softmax', name = 'softmax')(dense) return Model(inputs=input1, outputs=softmax) def EEGNet_SSVEP(nb_classes = 12, Chans = 8, Samples = 256, dropoutRate = 0.5, kernLength = 256, F1 = 96, D = 1, F2 = 96, dropoutType = 'Dropout'): """ SSVEP Variant of EEGNet, as used in [1]. Inputs: nb_classes : int, number of classes to classify Chans, Samples : number of channels and time points in the EEG data dropoutRate : dropout fraction kernLength : length of temporal convolution in first layer F1, F2 : number of temporal filters (F1) and number of pointwise filters (F2) to learn. D : number of spatial filters to learn within each temporal convolution. dropoutType : Either SpatialDropout2D or Dropout, passed as a string. [1]. Waytowich, N. et. al. (2018). Compact Convolutional Neural Networks for Classification of Asynchronous Steady-State Visual Evoked Potentials. Journal of Neural Engineering vol. 15(6). http://iopscience.iop.org/article/10.1088/1741-2552/aae5d8 """ if dropoutType == 'SpatialDropout2D': dropoutType = SpatialDropout2D elif dropoutType == 'Dropout': dropoutType = Dropout else: raise ValueError('dropoutType must be one of SpatialDropout2D ' 'or Dropout, passed as a string.') input1 = Input(shape = (Chans, Samples, 1)) ################################################################## block1 = Conv2D(F1, (1, kernLength), padding = 'same', input_shape = (Chans, Samples, 1), use_bias = False)(input1) block1 = BatchNormalization()(block1) block1 = DepthwiseConv2D((Chans, 1), use_bias = False, depth_multiplier = D, depthwise_constraint = max_norm(1.))(block1) block1 = BatchNormalization()(block1) block1 = Activation('elu')(block1) block1 = AveragePooling2D((1, 4))(block1) block1 = dropoutType(dropoutRate)(block1) block2 = SeparableConv2D(F2, (1, 16), use_bias = False, padding = 'same')(block1) block2 = BatchNormalization()(block2) block2 = Activation('elu')(block2) block2 = AveragePooling2D((1, 8))(block2) block2 = dropoutType(dropoutRate)(block2) flatten = Flatten(name = 'flatten')(block2) dense = Dense(nb_classes, name = 'dense')(flatten) softmax = Activation('softmax', name = 'softmax')(dense) return Model(inputs=input1, outputs=softmax) def EEGNet_old(nb_classes, Chans = 64, Samples = 128, regRate = 0.0001, dropoutRate = 0.25, kernels = [(2, 32), (8, 4)], strides = (2, 4)): """ Keras Implementation of EEGNet_v1 (https://arxiv.org/abs/1611.08024v2) This model is the original EEGNet model proposed on arxiv https://arxiv.org/abs/1611.08024v2 with a few modifications: we use striding instead of max-pooling as this helped slightly in classification performance while also providing a computational speed-up. Note that we no longer recommend the use of this architecture, as the new version of EEGNet performs much better overall and has nicer properties. Inputs: nb_classes : total number of final categories Chans, Samples : number of EEG channels and samples, respectively regRate : regularization rate for L1 and L2 regularizations dropoutRate : dropout fraction kernels : the 2nd and 3rd layer kernel dimensions (default is the [2, 32] x [8, 4] configuration) strides : the stride size (note that this replaces the max-pool used in the original paper) """ # start the model input_main = Input((Chans, Samples)) layer1 = Conv2D(16, (Chans, 1), input_shape=(Chans, Samples, 1), kernel_regularizer = l1_l2(l1=regRate, l2=regRate))(input_main) layer1 = BatchNormalization()(layer1) layer1 = Activation('elu')(layer1) layer1 = Dropout(dropoutRate)(layer1) permute_dims = 2, 1, 3 permute1 = Permute(permute_dims)(layer1) layer2 = Conv2D(4, kernels[0], padding = 'same', kernel_regularizer=l1_l2(l1=0.0, l2=regRate), strides = strides)(permute1) layer2 = BatchNormalization()(layer2) layer2 = Activation('elu')(layer2) layer2 = Dropout(dropoutRate)(layer2) layer3 = Conv2D(4, kernels[1], padding = 'same', kernel_regularizer=l1_l2(l1=0.0, l2=regRate), strides = strides)(layer2) layer3 = BatchNormalization()(layer3) layer3 = Activation('elu')(layer3) layer3 = Dropout(dropoutRate)(layer3) flatten = Flatten(name = 'flatten')(layer3) dense = Dense(nb_classes, name = 'dense')(flatten) softmax = Activation('softmax', name = 'softmax')(dense) return Model(inputs=input_main, outputs=softmax) def DeepConvNet(nb_classes, Chans = 64, Samples = 256, dropoutRate = 0.5): """ Keras implementation of the Deep Convolutional Network as described in Schirrmeister et. al. (2017), Human Brain Mapping. This implementation assumes the input is a 2-second EEG signal sampled at 128Hz, as opposed to signals sampled at 250Hz as described in the original paper. We also perform temporal convolutions of length (1, 5) as opposed to (1, 10) due to this sampling rate difference. Note that we use the max_norm constraint on all convolutional layers, as well as the classification layer. We also change the defaults for the BatchNormalization layer. We used this based on a personal communication with the original authors. ours original paper pool_size 1, 2 1, 3 strides 1, 2 1, 3 conv filters 1, 5 1, 10 Note that this implementation has not been verified by the original authors. """ # start the model input_main = Input((Chans, Samples, 1)) block1 = Conv2D(25, (1, 5), input_shape=(Chans, Samples, 1), kernel_constraint = max_norm(2., axis=(0,1,2)))(input_main) block1 = Conv2D(25, (Chans, 1), kernel_constraint = max_norm(2., axis=(0,1,2)))(block1) block1 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block1) block1 = Activation('elu')(block1) block1 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block1) block1 = Dropout(dropoutRate)(block1) block2 = Conv2D(50, (1, 5), kernel_constraint = max_norm(2., axis=(0,1,2)))(block1) block2 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block2) block2 = Activation('elu')(block2) block2 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block2) block2 = Dropout(dropoutRate)(block2) block3 = Conv2D(100, (1, 5), kernel_constraint = max_norm(2., axis=(0,1,2)))(block2) block3 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block3) block3 = Activation('elu')(block3) block3 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block3) block3 = Dropout(dropoutRate)(block3) block4 = Conv2D(200, (1, 5), kernel_constraint = max_norm(2., axis=(0,1,2)))(block3) block4 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block4) block4 = Activation('elu')(block4) block4 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block4) block4 = Dropout(dropoutRate)(block4) flatten = Flatten()(block4) dense = Dense(nb_classes, kernel_constraint = max_norm(0.5))(flatten) softmax = Activation('softmax')(dense) return Model(inputs=input_main, outputs=softmax) # need these for ShallowConvNet def square(x): return K.square(x) def log(x): return K.log(K.clip(x, min_value = 1e-7, max_value = 10000)) def ShallowConvNet(nb_classes, Chans = 64, Samples = 128, dropoutRate = 0.5): """ Keras implementation of the Shallow Convolutional Network as described in Schirrmeister et. al. (2017), Human Brain Mapping. Assumes the input is a 2-second EEG signal sampled at 128Hz. Note that in the original paper, they do temporal convolutions of length 25 for EEG data sampled at 250Hz. We instead use length 13 since the sampling rate is roughly half of the 250Hz which the paper used. The pool_size and stride in later layers is also approximately half of what is used in the paper. Note that we use the max_norm constraint on all convolutional layers, as well as the classification layer. We also change the defaults for the BatchNormalization layer. We used this based on a personal communication with the original authors. ours original paper pool_size 1, 35 1, 75 strides 1, 7 1, 15 conv filters 1, 13 1, 25 Note that this implementation has not been verified by the original authors. We do note that this implementation reproduces the results in the original paper with minor deviations. """ # start the model input_main = Input((Chans, Samples, 1)) block1 = Conv2D(40, (1, 13), input_shape=(Chans, Samples, 1), kernel_constraint = max_norm(2., axis=(0,1,2)))(input_main) block1 = Conv2D(40, (Chans, 1), use_bias=False, kernel_constraint = max_norm(2., axis=(0,1,2)))(block1) block1 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block1) block1 = Activation(square)(block1) block1 = AveragePooling2D(pool_size=(1, 35), strides=(1, 7))(block1) block1 = Activation(log)(block1) block1 = Dropout(dropoutRate)(block1) flatten = Flatten()(block1) dense = Dense(nb_classes, kernel_constraint = max_norm(0.5))(flatten) softmax = Activation('softmax')(dense) return Model(inputs=input_main, outputs=softmax)
18,033
43.74938
96
py
arl-eegmodels
arl-eegmodels-master/examples/ERP.py
""" Sample script using EEGNet to classify Event-Related Potential (ERP) EEG data from a four-class classification task, using the sample dataset provided in the MNE [1, 2] package: https://martinos.org/mne/stable/manual/sample_dataset.html#ch-sample-data The four classes used from this dataset are: LA: Left-ear auditory stimulation RA: Right-ear auditory stimulation LV: Left visual field stimulation RV: Right visual field stimulation The code to process, filter and epoch the data are originally from Alexandre Barachant's PyRiemann [3] package, released under the BSD 3-clause. A copy of the BSD 3-clause license has been provided together with this software to comply with software licensing requirements. When you first run this script, MNE will download the dataset and prompt you to confirm the download location (defaults to ~/mne_data). Follow the prompts to continue. The dataset size is approx. 1.5GB download. For comparative purposes you can also compare EEGNet performance to using Riemannian geometric approaches with xDAWN spatial filtering [4-8] using PyRiemann (code provided below). [1] A. Gramfort, M. Luessi, E. Larson, D. Engemann, D. Strohmeier, C. Brodbeck, L. Parkkonen, M. Hämäläinen, MNE software for processing MEG and EEG data, NeuroImage, Volume 86, 1 February 2014, Pages 446-460, ISSN 1053-8119. [2] A. Gramfort, M. Luessi, E. Larson, D. Engemann, D. Strohmeier, C. Brodbeck, R. Goj, M. Jas, T. Brooks, L. Parkkonen, M. Hämäläinen, MEG and EEG data analysis with MNE-Python, Frontiers in Neuroscience, Volume 7, 2013. [3] https://github.com/alexandrebarachant/pyRiemann. [4] A. Barachant, M. Congedo ,"A Plug&Play P300 BCI Using Information Geometry" arXiv:1409.0107. link [5] M. Congedo, A. Barachant, A. Andreev ,"A New generation of Brain-Computer Interface Based on Riemannian Geometry", arXiv: 1310.8115. [6] A. Barachant and S. Bonnet, "Channel selection procedure using riemannian distance for BCI applications," in 2011 5th International IEEE/EMBS Conference on Neural Engineering (NER), 2011, 348-351. [7] A. Barachant, S. Bonnet, M. Congedo and C. Jutten, “Multiclass Brain-Computer Interface Classification by Riemannian Geometry,” in IEEE Transactions on Biomedical Engineering, vol. 59, no. 4, p. 920-928, 2012. [8] A. Barachant, S. Bonnet, M. Congedo and C. Jutten, “Classification of covariance matrices using a Riemannian-based kernel for BCI applications“, in NeuroComputing, vol. 112, p. 172-178, 2013. Portions of this project are works of the United States Government and are not subject to domestic copyright protection under 17 USC Sec. 105. Those portions are released world-wide under the terms of the Creative Commons Zero 1.0 (CC0) license. Other portions of this project are subject to domestic copyright protection under 17 USC Sec. 105. Those portions are licensed under the Apache 2.0 license. The complete text of the license governing this material is in the file labeled LICENSE.TXT that is a part of this project's official distribution. """ import numpy as np # mne imports import mne from mne import io from mne.datasets import sample # EEGNet-specific imports from EEGModels import EEGNet from tensorflow.keras import utils as np_utils from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras import backend as K # PyRiemann imports from pyriemann.estimation import XdawnCovariances from pyriemann.tangentspace import TangentSpace from pyriemann.utils.viz import plot_confusion_matrix from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression # tools for plotting confusion matrices from matplotlib import pyplot as plt # while the default tensorflow ordering is 'channels_last' we set it here # to be explicit in case if the user has changed the default ordering K.set_image_data_format('channels_last') ##################### Process, filter and epoch the data ###################### data_path = sample.data_path() # Set parameters and read data raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' tmin, tmax = -0., 1 event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4) # Setup for reading the raw data raw = io.Raw(raw_fname, preload=True, verbose=False) raw.filter(2, None, method='iir') # replace baselining with high-pass events = mne.read_events(event_fname) raw.info['bads'] = ['MEG 2443'] # set bad channels picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False, picks=picks, baseline=None, preload=True, verbose=False) labels = epochs.events[:, -1] # extract raw data. scale by 1000 due to scaling sensitivity in deep learning X = epochs.get_data()*1000 # format is in (trials, channels, samples) y = labels kernels, chans, samples = 1, 60, 151 # take 50/25/25 percent of the data to train/validate/test X_train = X[0:144,] Y_train = y[0:144] X_validate = X[144:216,] Y_validate = y[144:216] X_test = X[216:,] Y_test = y[216:] ############################# EEGNet portion ################################## # convert labels to one-hot encodings. Y_train = np_utils.to_categorical(Y_train-1) Y_validate = np_utils.to_categorical(Y_validate-1) Y_test = np_utils.to_categorical(Y_test-1) # convert data to NHWC (trials, channels, samples, kernels) format. Data # contains 60 channels and 151 time-points. Set the number of kernels to 1. X_train = X_train.reshape(X_train.shape[0], chans, samples, kernels) X_validate = X_validate.reshape(X_validate.shape[0], chans, samples, kernels) X_test = X_test.reshape(X_test.shape[0], chans, samples, kernels) print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # configure the EEGNet-8,2,16 model with kernel length of 32 samples (other # model configurations may do better, but this is a good starting point) model = EEGNet(nb_classes = 4, Chans = chans, Samples = samples, dropoutRate = 0.5, kernLength = 32, F1 = 8, D = 2, F2 = 16, dropoutType = 'Dropout') # compile the model and set the optimizers model.compile(loss='categorical_crossentropy', optimizer='adam', metrics = ['accuracy']) # count number of parameters in the model numParams = model.count_params() # set a valid path for your system to record model checkpoints checkpointer = ModelCheckpoint(filepath='/tmp/checkpoint.h5', verbose=1, save_best_only=True) ############################################################################### # if the classification task was imbalanced (significantly more trials in one # class versus the others) you can assign a weight to each class during # optimization to balance it out. This data is approximately balanced so we # don't need to do this, but is shown here for illustration/completeness. ############################################################################### # the syntax is {class_1:weight_1, class_2:weight_2,...}. Here just setting # the weights all to be 1 class_weights = {0:1, 1:1, 2:1, 3:1} ################################################################################ # fit the model. Due to very small sample sizes this can get # pretty noisy run-to-run, but most runs should be comparable to xDAWN + # Riemannian geometry classification (below) ################################################################################ fittedModel = model.fit(X_train, Y_train, batch_size = 16, epochs = 300, verbose = 2, validation_data=(X_validate, Y_validate), callbacks=[checkpointer], class_weight = class_weights) # load optimal weights model.load_weights('/tmp/checkpoint.h5') ############################################################################### # can alternatively used the weights provided in the repo. If so it should get # you 93% accuracy. Change the WEIGHTS_PATH variable to wherever it is on your # system. ############################################################################### # WEIGHTS_PATH = /path/to/EEGNet-8-2-weights.h5 # model.load_weights(WEIGHTS_PATH) ############################################################################### # make prediction on test set. ############################################################################### probs = model.predict(X_test) preds = probs.argmax(axis = -1) acc = np.mean(preds == Y_test.argmax(axis=-1)) print("Classification accuracy: %f " % (acc)) ############################# PyRiemann Portion ############################## # code is taken from PyRiemann's ERP sample script, which is decoding in # the tangent space with a logistic regression n_components = 2 # pick some components # set up sklearn pipeline clf = make_pipeline(XdawnCovariances(n_components), TangentSpace(metric='riemann'), LogisticRegression()) preds_rg = np.zeros(len(Y_test)) # reshape back to (trials, channels, samples) X_train = X_train.reshape(X_train.shape[0], chans, samples) X_test = X_test.reshape(X_test.shape[0], chans, samples) # train a classifier with xDAWN spatial filtering + Riemannian Geometry (RG) # labels need to be back in single-column format clf.fit(X_train, Y_train.argmax(axis = -1)) preds_rg = clf.predict(X_test) # Printing the results acc2 = np.mean(preds_rg == Y_test.argmax(axis = -1)) print("Classification accuracy: %f " % (acc2)) # plot the confusion matrices for both classifiers names = ['audio left', 'audio right', 'vis left', 'vis right'] plt.figure(0) plot_confusion_matrix(preds, Y_test.argmax(axis = -1), names, title = 'EEGNet-8,2') plt.figure(1) plot_confusion_matrix(preds_rg, Y_test.argmax(axis = -1), names, title = 'xDAWN + RG')
10,178
40.717213
86
py
sampling_for_genomic_surveillance
sampling_for_genomic_surveillance-master/compare_distribution.py
#libraries to use import pandas as pd from scipy.stats import mannwhitneyu from scipy.stats import ks_2samp from scipy.stats import ttest_ind def define_significance_value(p_value): summary = "" if p_value > 0.05: summary = "NS" elif p_value > 0.01 and p_value <= 0.05: summary = "*" elif p_value > 0.001 and p_value <= 0.01: summary = "**" elif p_value > 0.001 and p_value <= 0.001: summary = "***" else: summary = "****" return summary #read datasets ignored columns df_adaptativo = pd.read_csv("comparative_data\\Res_Adaptive.csv") df_constant = pd.read_csv("comparative_data\\Res_Constant.csv") #adding columns name name_columns = ["column_{}".format(i+1) for i in range(len(df_adaptativo.columns))] df_adaptativo.columns = name_columns df_constant.columns = name_columns matrix_data = [] #start comparison for each columns for column in name_columns: #get values of the columns using the proposed name values_adaptativo = df_adaptativo[column] values_constante = df_constant[column] #apply different statistical test, all returns the statistic value and the p-value u_test_result = mannwhitneyu(values_adaptativo, values_constante, alternative='two-sided') kolmogorov = ks_2samp(values_adaptativo, values_constante) different_variance = ttest_ind(values_adaptativo, values_constante, equal_var=False) #get the number of * by definitions sig_u_test = define_significance_value(u_test_result[1]) sig_k_test = define_significance_value(kolmogorov[1]) sig_d_test = define_significance_value(different_variance[1]) #create row with different element row = [column, u_test_result[0], u_test_result[1], sig_u_test, kolmogorov[0], kolmogorov[1], sig_k_test, different_variance[0], different_variance[1], sig_d_test] #adding row to matrix matrix_data.append(row) #creating df to export results in a csv format df_export = pd.DataFrame(matrix_data, columns=['column_compare', 'statistic-u-test', 'p-value-u-test', 'significance-level-u-test', 'statistic-ks-test', 'p-value-ks-test', 'significance-level-ks-test', 'statistic-t-test', 'p-value-t-test', 'significance-level-t-test']) df_export.to_csv("comparative_data\\results_test.csv", index=False)
2,285
37.1
269
py
amuse
amuse-main/setup.py
from setuptools import setup, find_packages from support.setup_codes import setup_commands from support.misc import find_data_files name = 'amuse-devel' author = 'The AMUSE team' author_email = 'info@amusecode.org' license_ = "Apache License 2.0" url = 'http://www.amusecode.org/' install_requires = [ 'setuptools>=41.0.0', 'setuptools_scm', 'pip>=19.0.0', 'wheel>=0.32', 'docutils>=0.6', 'numpy>=1.2.2', 'pytest>=4.0', # 'mpi4py>=1.1.0', 'h5py>=1.1.0', ] description = 'The Astrophysical Multipurpose Software Environment' with open("README.md", "r") as fh: long_description = fh.read() long_description_content_type = "text/markdown" classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: C', 'Programming Language :: C++', 'Programming Language :: Fortran', 'Topic :: Scientific/Engineering :: Astronomy', ] extensions = [] all_data_files = [] all_data_files.append(('share/amuse', ['./config.mk'])) packages = find_packages('src') packages.extend( ['amuse.examples.' + x for x in find_packages('examples')] ) package_data = { 'amuse.rfi.tools': ['*.template'], 'amuse.test.suite.core_tests': [ '*.txt', '*.dyn', '*.ini', '*.nemo', '*.dat', 'gadget_snapshot' ], 'amuse.test.suite.codes_tests': [ '*.txt', 'test_sphray_data*' ], 'amuse.test.suite.ticket_tests': [ '*.out' ], 'amuse': [ '*rc' ] } mapping_from_command_name_to_command_class = setup_commands() setup( name=name, use_scm_version={ "write_to": "src/amuse/version.py", }, setup_requires=['setuptools_scm'], classifiers=classifiers, url=url, author_email=author_email, author=author, license=license_, description=description, long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, python_requires=">=3.7", extras_require = { "MPI" : ["mpi4py>=1.1.0"] }, cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={'': 'src', 'amuse.examples': 'examples'}, packages=packages, package_data=package_data, data_files=all_data_files, scripts=["bin/amusifier", "bin/amuse-tutorial", ], )
2,853
26.980392
67
py
amuse
amuse-main/examples/examples_galaxia/orbit_one_star.py
# --------------------------------------------------------------------------- # Script that uses galaxia and the bridge in rotating coordinates | # to integrate the orbit of a star. | # For a complete explanation of the possible parameters and models | # included in galaxia, we refer the reader to the file: user_manual_galaxia.| # The running time may take some seconds, so be patient! | # --------------------------------------------------------------------------- from amuse import datamodel from amuse.units import quantities, units from amuse.ext.rotating_bridge import Rotating_Bridge from amuse.community.galaxia.interface import BarAndSpirals3D from amuse.ext.composition_methods import ( SPLIT_6TH_SS_M13, SPLIT_4TH_S_M6 ) import numpy from matplotlib import pyplot class drift_without_gravity(object): """ This class is necessary to make the evolution of test particles by using bridge. """ def __init__(self, particles, time=0 | units.Myr): self.particles = particles self.model_time = time def evolve_model(self, t_end): dt = t_end - self.model_time self.particles.position += self.particles.velocity*dt self.model_time = t_end @property def potential_energy(self): return quantities.zero @property def kinetic_energy(self): return ( 0.5 * self.particles.mass * self.particles.velocity.lengths()**2 ).sum() class IntegrateOrbitStar(object): """ This class makes the integration of a star in an analytical potential using galaxia. The integration methods that can be used in the Rotating Bridge are: LEAPFROG SPLIT_4TH_S_M6 SPLIT_4TH_S_M5 SPLIT_4TH_S_M4 SPLIT_6TH_SS_M11 SPLIT_6TH_SS_M13 SPLIT_8TH_SS_M21 SPLIT_10TH_SS_M35 where the ordinal number stands for the order of the integrator (i.e, 4th is fourth order); the S for symplectic; and M corresponds to the number of times the force in computed (i.e., M6 means that the force is computed 6 times). """ def __init__( self, simulation_time=10 | units.Myr, dt_bridge=0.5 | units.Myr, method_for_rotating_bridge=SPLIT_6TH_SS_M13, initial_phase_bar=0, initial_phase_spiral_arms=0, pattern_speed_spiral_arms=-20 | (units.kms/units.kpc), amplitude_spiral_arms=1100 | (units.kms**2/units.kpc), number_of_arms=4, separation_locus_spiral_arms=3.12 | units.kpc, tangent_pitch_angle=0.227194425, pattern_speed_bar=-50 | (units.kms/units.kpc), mass_bar=1.1e10 | units.MSun, semimajor_axis_bar=3.12 | units.kpc, axis_ratio_bar=0.37): # initialization of Simulation parameters. self.t_end = simulation_time self.dt_bridge = dt_bridge self.method = method_for_rotating_bridge self.time = 0 | units.Myr # initialization of the galaxy parameters. self.omega = 0 | (units.kms/units.kpc) self.initial_phase = 0 self.bar_phase = initial_phase_bar self.spiral_phase = initial_phase_spiral_arms self.omega_spiral = pattern_speed_spiral_arms self.amplitude = amplitude_spiral_arms self.rsp = separation_locus_spiral_arms self.m = number_of_arms self.tan_pitch_angle = tangent_pitch_angle self.omega_bar = pattern_speed_bar self.mass_bar = mass_bar self.aaxis_bar = semimajor_axis_bar self.axis_ratio_bar = axis_ratio_bar return def galaxy(self): # Model of the Galaxy. # In this example, the Galaxy has two-dimensional bar and spiral arms. # The spiral arms model is the TWA # The bar does not grow adiabatically # The axisymmetric component has its defaul values from Allen & # Santillan (1990). galaxy = BarAndSpirals3D() galaxy.kinetic_energy = quantities.zero galaxy.potential_energy = quantities.zero galaxy.parameters.bar_contribution = True galaxy.parameters.bar_phase = self.bar_phase galaxy.parameters.omega_bar = self.omega_bar galaxy.parameters.mass_bar = self.mass_bar galaxy.parameters.aaxis_bar = self.aaxis_bar galaxy.parameters.axis_ratio_bar = self.axis_ratio_bar galaxy.parameters.spiral_contribution = True galaxy.parameters.spiral_model = 0 galaxy.parameters.spiral_phase = self.spiral_phase galaxy.parameters.omega_spiral = self.omega_spiral galaxy.parameters.amplitude = self.amplitude galaxy.parameters.rsp = self.rsp galaxy.parameters.m = self.m galaxy.parameters.tan_pitch_angle = self.tan_pitch_angle galaxy.commit_parameters() self.omega = galaxy.parameters.omega_system self. initial_phase = galaxy.parameters.initial_phase return galaxy def creation_particles_noinertial(self, particles): # This function creates a particle set in a # rotating system. This information is used by # the rotating bridge no_inertial_system = particles.copy() angle = self.initial_phase + self.omega*self.time C1 = particles.vx + self.omega*particles.y C2 = particles.vy - self.omega*particles.x no_inertial_system.x = ( particles.x * numpy.cos(angle) + particles.y * numpy.sin(angle) ) no_inertial_system.y = ( -particles.x * numpy.sin(angle) + particles.y * numpy.cos(angle) ) no_inertial_system.z = particles.z no_inertial_system.vx = C1*numpy.cos(angle) + C2*numpy.sin(angle) no_inertial_system.vy = C2*numpy.cos(angle) - C1*numpy.sin(angle) no_inertial_system.vz = particles.vz return no_inertial_system def noinertial_to_inertial(self, part_noin, part_in): # Transformation function from a rotating to an inertial frame. angle = self.initial_phase + self.omega*self.time C1 = part_noin.vx - part_noin.y*self.omega C2 = part_noin.vy + part_noin.x*self.omega part_in.x = part_noin.x*numpy.cos(angle)-part_noin.y*numpy.sin(angle) part_in.y = part_noin.x*numpy.sin(angle)+part_noin.y*numpy.cos(angle) part_in.z = part_noin.z part_in.vx = C1*numpy.cos(angle) - C2*numpy.sin(angle) part_in.vy = C1*numpy.sin(angle) + C2*numpy.cos(angle) part_in.vz = part_noin.vz return def get_orbit_of_the_star(self, particle_set): # Function that integrates the orbit of the star. # input: particle_set -> defined in an inertial system # steps: # 1. The Galaxy model is created # 2. A copy of particle_set is created in the rotating frame # where the stellar motion is computed # 3. The Galaxy and the particles in the rotating frame are coupled # through the rotating Bridge # 4. The evolution of the system is made # 5. The positions and velocities in particle_set are updated by # transforming the phase-space coordinates back to the inertial frame. X = [] Y = [] MW = self.galaxy() particles_in_rotating_coordinates = self.creation_particles_noinertial( particle_set) gravless = drift_without_gravity(particles_in_rotating_coordinates) system = Rotating_Bridge( self.omega, timestep=self.dt_bridge, verbose=False, method=self.method) system.add_system(gravless, (MW,), False) system.add_system(MW, (), False) while (self.time < self.t_end-self.dt_bridge/2): X.append(particle_set[0].x.value_in(units.kpc)) Y.append(particle_set[0].y.value_in(units.kpc)) self.time += self.dt_bridge system.evolve_model(self.time) self.noinertial_to_inertial( particles_in_rotating_coordinates, particle_set) return X, Y def plot_orbit(position_x, position_y): figure = pyplot.figure(figsize=(6, 6)) ax = figure.add_subplot(111) ax.plot(position_x, position_y) ax.set_xlabel('X [kpc]') ax.set_ylabel('Y [kpc]') ax.set_title('Orbit of a star with initial position at (%g,%g) kpc \n from the Galactic center' % ( position_x[0], position_y[0])) ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) pyplot.show() if __name__ in('__main__', '__plot__'): star = datamodel.Particles(1) star[0].mass = 1 | units.MSun star[0].radius = 1 | units.RSun star[0].position = [-8.5, 0, 0] | units.kpc star[0].velocity = [-7.3, 100, 0] | units.kms integrator = IntegrateOrbitStar( simulation_time=250 | units.Myr, dt_bridge=0.5 | units.Myr, method_for_rotating_bridge=SPLIT_4TH_S_M6, initial_phase_bar=-0.35, initial_phase_spiral_arms=-0.35, pattern_speed_spiral_arms=20 | (units.kms/units.kpc), amplitude_spiral_arms=1100 | (units.kms**2/units.kpc), number_of_arms=4, pattern_speed_bar=50 | (units.kms/units.kpc), mass_bar=1.1e10 | units.MSun) x, y = integrator.get_orbit_of_the_star(star) plot_orbit(x, y)
9,533
37.756098
103
py
amuse
amuse-main/examples/examples_galaxia/resonances.py
# --------------------------------------------------------------------------- # This script generates the corrotation and Lindbland resonances | # as a function of radius using galaxia. | # For a complete explanation of the possible parameters and models | # included in galaxia, we refer the reader to the file: user_manual_galaxia.| # --------------------------------------------------------------------------- import numpy from amuse.units import units from amuse.community.galaxia.interface import BarAndSpirals3D from matplotlib import rc import matplotlib.pyplot as plt def plot_resonances(r, omega_c, ilr2, olr2, ilr4, olr4): rc('text', usetex=True) rc('font', family='serif') fig = plt.figure(0, figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1) ax.plot(r.value_in(units.kpc), omega_c.value_in( units.kms/units.kpc), 'r-', label='Corotation resonance') ax.plot(r.value_in(units.kpc), ilr2.value_in( units.kms/units.kpc), "b--", label='ILRm2') ax.plot(r.value_in(units.kpc), olr2.value_in( units.kms/units.kpc), "g--", label='OLRm2') ax.plot(r.value_in(units.kpc), ilr4.value_in( units.kms/units.kpc), "b-", lw=2, label='ILRm4') ax.plot(r.value_in(units.kpc), olr4.value_in( units.kms/units.kpc), "g-", lw=2, label='OLRm4') ax.legend(loc="upper right", ncol=1, shadow=False, fontsize=12) yticks = numpy.arange(0, 100, 10) xticks = numpy.arange(0, 15, 1) ax.set_xlim(0, 15) ax.set_ylim(0, 100) ax.set_ylabel("$\Omega$ $[kms^{-1}kpc^{-1}]$") ax.set_xlabel("R [Kpc]") plt.yticks(yticks) plt.xticks(xticks) plt.grid(True) plt.show() if __name__ in('__main__', '__plot__'): # Axisymmetric model of the Galaxy with default values MW = BarAndSpirals3D() MW.commit_parameters() r = numpy.arange(0.001, 15, 0.005) | units.kpc phi = numpy.pi/4. # phi can take any value x, y, z = r*numpy.cos(phi), r*numpy.sin(phi), 0 | units.kpc circular_velocity = MW.get_velcirc(x, y, z) omega = circular_velocity/r # Angular velocity epicyclic_frecuency = MW.get_epifreq(x, y, z) kappa = epicyclic_frecuency/r # epicyclic velocity # Inner and Outer Lindblad resonances for 2,4 spiral arms ILRm2 = omega - kappa/2. OLRm2 = omega + kappa/2. ILRm4 = omega - kappa/4. OLRm4 = omega + kappa/4. plot_resonances(r, omega, ILRm2, OLRm2, ILRm4, OLRm4)
2,479
36.014925
77
py
amuse
amuse-main/examples/examples_galaxia/evolution_cluster.py
# --------------------------------------------------------------------------- # Script that uses galaxia and the bridge in rotating coordinates | # to calculate the evolution of a star cluster in the Galaxy. | # The physical processes involved are self gravity, stellar evolution | # and the external tidal field of the Galaxy. | # For a complete explanation of the possible parameters and models | # included in galaxia, we refer the reader to the file: user_manual_galaxia.| # The running time may take some seconds, so be patient! | # --------------------------------------------------------------------------- import numpy # from amuse.couple import bridge from amuse.units import units, constants, quantities, nbody_system from amuse.ic.brokenimf import new_broken_power_law_mass_distribution from amuse.ic.plummer import new_plummer_sphere from amuse.community.huayno.interface import Huayno from amuse.community.seba.interface import SeBa from amuse.ext.composition_methods import LEAPFROG from amuse.ext.rotating_bridge import Rotating_Bridge from amuse.community.galaxia.interface import BarAndSpirals3D from matplotlib import pyplot def create_cluster_with_IMF(N=100, radius=3 | units.parsec): ''' Creation of a cluster following a Kroupa IMF ''' masses = new_broken_power_law_mass_distribution( N, mass_boundaries=[0.08, 0.5, 100] | units.MSun, alphas=[-1.3, -2.3]) convert_nbody = nbody_system.nbody_to_si(masses.sum(), radius) cluster = new_plummer_sphere(N, convert_nbody) cluster.mass = masses cluster.move_to_center() cluster.scale_to_standard(convert_nbody) return cluster class RealisticEvolutionCluster(object): """ This class makes the integration of a star cluster in an analytical potential using galaxia. The integration methods that can be used in the Rotating Bridge are: LEAPFROG SPLIT_4TH_S_M6 SPLIT_4TH_S_M5 SPLIT_4TH_S_M4 SPLIT_6TH_SS_M11 SPLIT_6TH_SS_M13 SPLIT_8TH_SS_M21 SPLIT_10TH_SS_M35 where the ordinal number stands for the order of the integrator (i.e, 4th is fourth order); the S for symplectic; and M corresponds to the number of times the force in computed (i.e., M6 means that the force is computed 6 times). """ def __init__( self, simulation_time=100 | units.Myr, dt_bridge=1 | units.Myr, method_for_rotating_bridge=LEAPFROG, initial_phase_main_spiral_arms=0, pattern_speed_main_spiral_arms=20 | (units.kms/units.kpc), amplitude_main_spiral_arms=1100 | (units.kms**2/units.kpc), number_of_main_spiral_arms=2, tangent_pitch_angle_main_spiral_arms=0.227194425, initial_phase_secondary_spiral_arms=200*(numpy.pi/180), pattern_speed_secondary_spiral_arms=15 | (units.kms/units.kpc), amplitude_secondary_spiral_arms=880 | (units.kms**2/units.kpc), tangent_pitch_angle_secondary_spiral_arms=numpy.tan( (-14*numpy.pi)/180.), number_of_secondary_spiral_arms=2, separation_locus_spiral_arms=3.12 | units.kpc, initial_phase_bar=0, pattern_speed_bar=40 | (units.kms/units.kpc), mass_bar=1.2e10 | units.MSun, semimajor_axis_bar=3.12 | units.kpc, axis_ratio_bar=0.37): # Simulation parameters self.t_end = simulation_time self.time = 0 | units.Myr self.dt_bridge = dt_bridge self.method = method_for_rotating_bridge # galaxy parameters self.omega_system = 0 | (units.kms/units.kpc) self.initial_phase_system = 0 self.bar_phase = initial_phase_bar self.omega_bar = pattern_speed_bar self.mass_bar = mass_bar self.aaxis_bar = semimajor_axis_bar self.axis_ratio_bar = axis_ratio_bar self.spiral_phase_main_sp = initial_phase_main_spiral_arms self.omega_spiral_main_sp = pattern_speed_main_spiral_arms self.amplitude_main_sp = amplitude_main_spiral_arms self.number_main_sp = number_of_main_spiral_arms self.tangent_pitch_angle_main_sp = tangent_pitch_angle_main_spiral_arms self.spiral_phase_second_sp = initial_phase_secondary_spiral_arms self.omega_spiral_second_sp = pattern_speed_secondary_spiral_arms self.amplitude_second_sp = amplitude_secondary_spiral_arms self.number_second_sp = number_of_secondary_spiral_arms self.tangent_pitch_angle_second_sp = \ tangent_pitch_angle_secondary_spiral_arms self.separation_sp = separation_locus_spiral_arms return def softening(self, particles): ''' optimum softening lenght. ''' N = len(particles.mass) U = particles.potential_energy() Rvir = 0.5*constants.G*particles.mass.sum()**2/abs(U) epsilon = 4*Rvir/N return epsilon def galactic_model(self): ''' Model of the Galaxy. In this example, the Galaxy has two-dimensional bar and spiral arms. The spiral arms are described by the Composite model (2+2) The bar does not grow adiabatically The axisymmetric component has its defaul values from Allen & Santillan (1990). ''' galaxy = BarAndSpirals3D() galaxy.kinetic_energy = quantities.zero galaxy.potential_energy = quantities.zero galaxy.parameters.spiral_contribution = True galaxy.parameters.spiral_model = 2 galaxy.parameters.omega_spiral = self.omega_spiral_main_sp galaxy.parameters.spiral_phase = self.spiral_phase_main_sp galaxy.parameters.amplitude = self.amplitude_main_sp galaxy.parameters.m = self.number_main_sp galaxy.parameters.tan_pitch_angle = self.tangent_pitch_angle_main_sp galaxy.parameters.phi21_spiral = self.spiral_phase_second_sp galaxy.parameters.omega_spiral2 = self.omega_spiral_second_sp galaxy.parameters.amplitude2 = self.amplitude_second_sp galaxy.parameters.m2 = self.number_second_sp galaxy.parameters.tan_pitch_angle2 = self.tangent_pitch_angle_second_sp galaxy.parameters.rsp = self.separation_sp galaxy.parameters.bar_contribution = True galaxy.parameters.bar_phase = self.bar_phase galaxy.parameters.omega_bar = self.omega_bar galaxy.parameters.mass_bar = self.mass_bar galaxy.parameters.aaxis_bar = self.aaxis_bar galaxy.parameters.axis_ratio_bar = self.axis_ratio_bar galaxy.commit_parameters() self.omega_system = galaxy.parameters.omega_system self.initial_phase_sytem = galaxy.parameters.initial_phase return galaxy def circular_velocity(self): MW = self.galactic_model() r = numpy.arange(15) vc = MW.get_velcirc(r | units.kpc, 0 | units.kpc, 0 | units.kpc) pyplot.plot(r, vc.value_in(units.kms)) pyplot.show() def creation_cluster_in_rotating_frame(self, particles): "forming a cluster in a rotating frame" no_inertial_system = particles.copy() angle = self.initial_phase_system + self.omega_system*self.time C1 = particles.vx + self.omega_system*particles.y C2 = particles.vy - self.omega_system*particles.x no_inertial_system.x = particles.x * \ numpy.cos(angle) + particles.y*numpy.sin(angle) no_inertial_system.y = -particles.x * \ numpy.sin(angle) + particles.y*numpy.cos(angle) no_inertial_system.z = particles.z no_inertial_system.vx = C1*numpy.cos(angle) + C2*numpy.sin(angle) no_inertial_system.vy = C2*numpy.cos(angle) - C1*numpy.sin(angle) no_inertial_system.vz = particles.vz return no_inertial_system def from_noinertial_to_cluster_in_inertial_frame(self, part_noin, part_in): 'makes transformation to the inertial frame' angle = self.initial_phase_system + self.omega_system*self.time C1 = part_noin.vx - part_noin.y*self.omega_system C2 = part_noin.vy + part_noin.x*self.omega_system part_in.age = part_noin.age part_in.mass = part_noin.mass part_in.radius = part_noin.radius part_in.luminosity = part_noin.luminosity part_in.temperature = part_noin.temperature part_in.stellar_type = part_noin.stellar_type part_in.x = part_noin.x*numpy.cos(angle)-part_noin.y*numpy.sin(angle) part_in.y = part_noin.x*numpy.sin(angle)+part_noin.y*numpy.cos(angle) part_in.z = part_noin.z part_in.vx = C1*numpy.cos(angle) - C2*numpy.sin(angle) part_in.vy = C1*numpy.sin(angle) + C2*numpy.cos(angle) part_in.vz = part_noin.vz return def evolution_of_the_cluster(self, cluster): ''' Function that makes de cluster evolution. input: cluster -> defined in an inertial frame (centered at the Galactic center) steps in this function: 1. From cluster, another cluster is defined in a rotating frame 2. The gravity code is initialized 3. The stellar evolution is initialized 4. the Galaxy model is constructed 5. The Galaxy and the cluster in the rotating frame are coupled via the Rotating Bridge 6. The evolution of the system is made 7. the cluster properties are transformed back to the inertial frame ''' cluster_in_rotating_frame = self.creation_cluster_in_rotating_frame( cluster) # N body code epsilon = self.softening(cluster) convert_nbody = nbody_system.nbody_to_si( cluster.mass.sum(), cluster.virial_radius()) gravity = Huayno(convert_nbody) gravity.parameters.timestep = self.dt_bridge/3. gravity.particles.add_particles(cluster_in_rotating_frame) gravity.parameters.epsilon_squared = epsilon**2 channel_from_gravity_to_rotating_cluster = \ gravity.particles.new_channel_to( cluster_in_rotating_frame) channel_from_rotating_cluster_to_gravity = \ cluster_in_rotating_frame.new_channel_to(gravity.particles) # stellar evolution code se = SeBa() se.particles.add_particles(cluster_in_rotating_frame) channel_from_rotating_cluster_to_se = \ cluster_in_rotating_frame.new_channel_to(se.particles) channel_from_se_to_rotating_cluster = se.particles.new_channel_to( cluster_in_rotating_frame) # Galaxy model and Rotating bridge MW = self.galactic_model() system = Rotating_Bridge( self.omega_system, timestep=self.dt_bridge, verbose=False, method=self.method) system.add_system(gravity, (MW,), False) system.add_system(MW, (), False) X = [] Y = [] T = [] # Cluster evolution while (self.time <= self.t_end-self.dt_bridge/2): self.time += self.dt_bridge system.evolve_model(self.time) se.evolve_model(self.time) channel_from_gravity_to_rotating_cluster.copy_attributes( ['x', 'y', 'z', 'vx', 'vy', 'vz']) channel_from_se_to_rotating_cluster.copy_attributes( [ 'mass', 'radius', 'luminosity', 'age', 'temperature', 'stellar_type' ] ) channel_from_rotating_cluster_to_gravity.copy_attributes(['mass']) self.from_noinertial_to_cluster_in_inertial_frame( cluster_in_rotating_frame, cluster) time = self.time.value_in(units.Myr) cm = cluster.center_of_mass() # write data if ((time == 2) or (time == 50) or (time == 100) or (time == 150)): X.append((cluster.x-cm[0]).value_in(units.kpc)) Y.append((cluster.y-cm[1]).value_in(units.kpc)) T.append(time) gravity.stop() se.stop() return T, X, Y def plot_cluster(T, X, Y): figure = pyplot.figure(figsize=(10, 10)) figure.subplots_adjust(wspace=0.3) figure.suptitle('Evolution of a star cluster', fontsize=14, fontweight='bold') for i in range(0, len(T)): ax = figure.add_subplot(2, 2, i+1) ax.scatter(X[i], Y[i], label='t= %g Myr' % T[i]) ax.set_xlabel('X [kpc]') ax.set_ylabel('Y [kpc]') ax.set_xlim(-0.1, 0.1) ax.set_ylim(-0.1, 0.1) ax.legend(loc="upper right", ncol=1, shadow=False, fontsize=12) pyplot.show() if __name__ in('__main__', '__plot__'): # Create a cluster star_cluster = create_cluster_with_IMF(N=200) star_cluster.position += [-6.5, 0, 0] | units.kpc star_cluster.velocity += [0, 50, 0] | units.kms # Construct the galactic model and make the evolution evolution = RealisticEvolutionCluster(simulation_time=150 | units.Myr) t, x, y = evolution.evolution_of_the_cluster(star_cluster) # plots plot_cluster(t, x, y)
13,348
40.200617
79
py
amuse
amuse-main/examples/examples_galaxia/rotation_curve_Milky_Way.py
# --------------------------------------------------------------------------- # This script generates the rotation curve of the Milky Way using galaxia. | # For a complete explanation of the possible parameters and models | # included in galaxia, we refer the reader to the file: user_manual_galaxia.| # --------------------------------------------------------------------------- from amuse.units import units from amuse.community.galaxia.interface import BarAndSpirals3D import numpy from matplotlib import pyplot def galaxy_model_with_bar_and_spirals( mass_bar=1.4e10 | units.MSun, initial_phase_bar_and_SA=0.35, semimajor_axis_bar=3.12 | units.kpc, axis_ratio_bar=0.37, vertical_axis_bar=1 | units.kpc, amplitude_spirals=3e6 | (units.MSun/units.kpc**3), scale_length_spirals=2.6 | units.kpc, number_of_arms=2, tangent_pitch_angle=0.2773, scale_height_spirals=0.3 | units.kpc, fiducial_radius=8 | units.kpc): # Galaxy model that uses a three dimensional bar (no adiabatic growing) # and the C&G model for the spiral arms galaxy = BarAndSpirals3D() galaxy.parameters.bar_contribution = True galaxy.parameters.bar_phase = initial_phase_bar_and_SA galaxy.parameters.mass_bar = mass_bar galaxy.parameters.aaxis_bar = semimajor_axis_bar galaxy.parameters.axis_ratio_bar = axis_ratio_bar galaxy.parameters.caxis_bar = vertical_axis_bar galaxy.parameters.spiral_contribution = True galaxy.parameters.spiral_model = 1 galaxy.parameters.spiral_phase = initial_phase_bar_and_SA galaxy.parameters.spiral_density_amplitude = amplitude_spirals galaxy.parameters.r_sigma = scale_length_spirals galaxy.parameters.m = number_of_arms galaxy.parameters.tan_pitch_angle = tangent_pitch_angle galaxy.parameters.scale_height = scale_height_spirals galaxy.parameters.fiducial_radius = fiducial_radius galaxy.commit_parameters() return galaxy def galaxy_model_purely_axisymmetric(): # Axisymmetric Galaxy model with default values galaxy = BarAndSpirals3D() galaxy.commit_parameters() return galaxy def plot_rotation_curves(r, vc, vc1): figure = pyplot.figure(figsize=(6, 6)) ax = figure.add_subplot(111) ax.plot(x.value_in(units.kpc), vc.value_in(units.kms), label='Model with bar and spiral arms') ax.plot(x.value_in(units.kpc), vc1.value_in( units.kms), label='Only axisymmetric') ax.set_xlabel('Galactocentric radius [Kpc]') ax.set_ylabel('Circular velocity [km/s]') ax.legend(loc='lower right') pyplot.show() if __name__ in('__main__', '__plot__'): x, y, z = numpy.linspace( 0.01, 15, 500) | units.kpc, 0 | units.kpc, 0 | units.kpc MilkyWay = galaxy_model_with_bar_and_spirals() circular_velocity = MilkyWay.get_velcirc(x, y, z) AxiGalaxy = galaxy_model_purely_axisymmetric() circular_velocity_axisymmetric_component = AxiGalaxy.get_velcirc(x, y, z) plot_rotation_curves(x, circular_velocity, circular_velocity_axisymmetric_component)
3,135
38.2
77
py
amuse
amuse-main/examples/examples_galaxia/utility_functions.py
# --------------------------------------------------------------------------- # Script that shows the utility functions of galaxia. | # These functions include: the computation of the components of the | # tidal tensor at a given point, the eigen-values and the tidal radius | # of a star cluster. | # For a complete explanation of the possible parameters and models | # included in galaxia, we refer the reader to the file: user_manual_galaxia.| # --------------------------------------------------------------------------- from amuse.units import units from amuse.community.galaxia.interface import BarAndSpirals3D import numpy from amuse.units.quantities import VectorQuantity def galaxy_model( initial_phase_bar=(-20*numpy.pi)/180, initial_phase_spiral_arms=(-20*numpy.pi)/180, pattern_speed_spiral_arms=20 | (units.kms/units.kpc), amplitude_spiral_arms=1100 | (units.kms**2/units.kpc), number_of_arms=4, separation_locus_spiral_arms=3.12 | units.kpc, tangent_pitch_angle=0.227194425, pattern_speed_bar=50 | (units.kms/units.kpc), mass_bar=1.1e10 | units.MSun, semimajor_axis_bar=3.12 | units.kpc, axis_ratio_bar=0.37): # Model of the Galaxy. # In this example, the Galaxy has two-dimensional bar and spiral arms. # The spiral arms model is the TWA # The bar does not grow adiabatically # The axisymmetric component has its default values from Allen & Santillan # (1990). galaxy = BarAndSpirals3D() galaxy.parameters.bar_contribution = True galaxy.parameters.bar_phase = initial_phase_bar galaxy.parameters.omega_bar = pattern_speed_bar galaxy.parameters.mass_bar = mass_bar galaxy.parameters.aaxis_bar = semimajor_axis_bar galaxy.parameters.axis_ratio_bar = axis_ratio_bar galaxy.parameters.spiral_contribution = True galaxy.parameters.spiral_model = 0 galaxy.parameters.spiral_phase = initial_phase_spiral_arms galaxy.parameters.omega_spiral = pattern_speed_spiral_arms galaxy.parameters.amplitude = amplitude_spiral_arms galaxy.parameters.rsp = separation_locus_spiral_arms galaxy.parameters.m = number_of_arms galaxy.parameters.tan_pitch_angle = tangent_pitch_angle galaxy.commit_parameters() return galaxy def tidal_tensor(t, x, y, z, galaxy): Fxx, Fyx, Fzx, Fxy, Fyy, Fzy, Fxz, Fyz, Fzz = galaxy.get_tidal_tensor( t, x, y, z) return VectorQuantity.new_from_scalar_quantities( Fxx, Fyx, Fzx, Fxy, Fyy, Fzy, Fxz, Fyz, Fzz) def eigen_values(t, x, y, z, galaxy): l1, l2, l3 = galaxy.get_eigen_values(t, x, y, z) return VectorQuantity.new_from_scalar_quantities(l1, l2, l3) if __name__ in('__main__', '__plot__'): # Tidal tensor, eigen values and tidal radius of a star cluster # with 1000 MSun that is located at solar radius. # The local stellar density is also calculated. mass_cluster = 1000 | units.MSun time, x, y, z = ( 0 | units.Myr, 8.5 | units.kpc, 0 | units.kpc, 0 | units.kpc, ) MilkyWay = galaxy_model() Tij = tidal_tensor(time, x, y, z, MilkyWay) eigenValues = eigen_values(time, x, y, z, MilkyWay) tidal_radius = MilkyWay.get_tidal_radius(time, x, y, z, mass_cluster) local_stellar_density = MilkyWay.get_local_density(time, x, y, z) print( 'tidal tensor:', Tij.value_in(100*units.kms**2/units.kpc**2), '\n', 'eigen values:', eigenValues.value_in(100*units.kms**2/units.kpc**2), '\n', 'tidal radius:', tidal_radius.value_in(units.parsec), '\n', 'local stellar density:', local_stellar_density.value_in(units.MSun/units.kpc**3) )
3,913
39.350515
78
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/disk_script/boxedfi.py
from amuse.units import nbody_system from amuse.units import units import amuse.datamodel as core from amuse.community.fi.interface import Fi from amuse.ext.gasplummer import MakePlummerGasModel class BoxedFi(Fi): def __init__(self, *args, **kargs): Fi.__init__(self, *args, **kargs) self.escapers=core.Particles(0) def evolve_model(self, *args, **kargs): self.stopping_conditions.out_of_box_detection.enable() outofbox=0.9*self.parameters.periodic_box_size/2 self.parameters.stopping_conditions_out_of_box_size = outofbox # Fi.evolve_model(self,*args,**kargs) self.overridden().evolve_model(*args,**kargs) while self.stopping_conditions.out_of_box_detection.is_set(): escapers=self.particles.select_array( lambda x,y,z: (x**2+y**2+z**2 > outofbox**2), ["x","y","z"]) print "***", len(escapers) if len(escapers)>0: self.escapers.add_particles(escapers) self.particles.remove_particles(escapers) # Fi.evolve_model(self,*args, **kargs) self.overridden().evolve_model(*args,**kargs) if __name__=="__main__": Ngas=1000 conv = nbody_system.nbody_to_si(100 | units.MSun, 1 | units.parsec) dt=conv.to_si(1|nbody_system.time)/100 print dt.in_(units.Myr) parts=MakePlummerGasModel(Ngas,convert_nbody=conv).result parts.h_smooth=0 | units.parsec outofbox=0.9*10. | units.parsec escapers=parts.select_array( lambda x,y,z: (x**2+y**2+z**2 > outofbox**2), ["x","y","z"]) print "**",len(escapers),outofbox.in_(units.parsec) parts.remove_particles(escapers) print len(parts) sph=BoxedFi(convert_nbody=conv,use_gl=True) sph.parameters.periodic_box_size=20. | units.parsec sph.parameters.timestep=dt sph.parameters.self_gravity_flag=False sph.gas_particles.add_particles(parts) sph.start_viewer() sph.evolve_model(dt*1000) print len(sph.gas_particles) print len(sph.particles)
1,929
30.129032
69
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/disk_script/fast.py
# issues: # - for now, units in si # - a common coordinate system is used for all systems # - sync of systems should be checked # - timestepping: adaptive dt? from amuse.units import units from amuse.units.quantities import zero import threading from amuse import datamodel def radius_or_hsmooth(parts): d=set(dir(parts)) if "radius" in d: return parts.radius else: if "h_smooth" in d: return parts.h_smooth else: print d raise Exception def potential_energy(system, get_potential): parts=system.particles.copy() pot=get_potential(parts.radius,parts.x,parts.y,parts.z) return (pot*parts.mass).sum()/2 def kick_system(system, get_gravity, dt): parts=system.particles.copy() ax,ay,az=get_gravity(parts.radius,parts.x,parts.y,parts.z) parts.vx=parts.vx+dt*ax parts.vy=parts.vy+dt*ay parts.vz=parts.vz+dt*az # parts.copy_values_of_state_attributes_to(system.particles) channel = parts.new_channel_to(system.particles) channel.copy_attributes(["vx","vy","vz"]) class FAST(object): def __init__(self,verbose=False,timestep=None): """ verbose indicates whether to output some run info """ self.systems=set() self.partners=dict() self.time_offsets=dict() self.time=0. | units.s self.do_sync=dict() self.verbose=verbose self.timestep=timestep def set_timestep(self,timestep): self.timestep=timestep def add_system(self, interface, partners=set(),do_sync=True): """ add a system to bridge integrator """ if hasattr(interface,"model_time"): self.time_offsets[interface]=(self.time-interface.model_time) else: self.time_offsets[interface]=0. self.systems.add(interface) for p in partners: if not hasattr(interface,"get_gravity_at_point"): return -1 self.partners[interface]=partners self.do_sync[interface]=do_sync return 0 def evolve_model(self,tend): """ evolve combined system to tend, timestep fixes timestep """ timestep=self.timestep if timestep is None: timestep=tend-self.time first=True while self.time < (tend-timestep/2.): if first: self.kick_systems(timestep/2.) first=False else: self.kick_systems(timestep) self.drift_systems(self.time+timestep) self.time=self.time+timestep if not first: self.kick_systems(timestep/2.) return 0 def synchronize_model(self): """ explicitly synchronize all components """ for x in self.systems: if hasattr(x,"synchronize_model"): if(self.verbose): print x.__class__.__name__,"is synchronizing", x.synchronize_model() if(self.verbose): print ".. done" def get_potential_at_point(self,radius,x,y,z): err=0 pot=0.*radius for x in self.systems: _pot,err=x.get_potential_at_point(radius,x,y,z) if err != 0: break pot=pot+_pot return pot,err def get_gravity_at_point(self,radius,x,y,z): err=0 ax=0.*radius ay=0.*radius az=0.*radius for x in self.systems: _ax,_ay,_az,err=x.get_gravity_at_point(radius,x,y,z) if err != 0: break ax=ax+_ax ay=ay+_ay az=az+_az return ax,ay,az,err @property def potential_energy(self): Ep=zero for x in self.systems: Ep+=x.potential_energy if hasattr(x,"particles"): for y in self.partners[x]: Ep+=potential_energy(x,y.get_potential_at_point) return Ep @property def kinetic_energy(self): Ek=zero for x in self.systems: Ek+=x.kinetic_energy return Ek @property def thermal_energy(self): Eth=zero for x in self.systems: if hasattr(x,'thermal_energy'): Eth+=x.thermal_energy return Eth @property def model_time(self): return self.time @property def particles(self): arr=[] for x in self.systems: if hasattr(x,"particles"): arr.append(x.particles) return datamodel.ParticlesSuperset(arr) @property def gas_particles(self): arr=[] for x in self.systems: if hasattr(x,"gas_particles"): arr.append(x.gas_particles) return datamodel.ParticlesSuperset(arr) # 'private' functions def drift_systems(self,tend): threads=[] for x in self.systems: if hasattr(x,"evolve_model"): offset=self.time_offsets[x] if(self.verbose): print "evolving", x.__class__.__name__, threads.append(threading.Thread(target=x.evolve_model, args=(tend-offset,)) ) for x in threads: x.start() for x in threads: x.join() if(self.verbose): print ".. done" return 0 def kick_systems(self,dt): for x in self.systems: if self.do_sync[x]: if hasattr(x,"synchronize_model"): if(self.verbose): print x.__class__.__name__,"is synchronizing", x.synchronize_model() if(self.verbose): print ".. done" for x in self.systems: if hasattr(x,"particles"): for y in self.partners[x]: if x is not y: if(self.verbose): print x.__class__.__name__,"receives kick from",y.__class__.__name__, kick_system(x,y.get_gravity_at_point,dt) if(self.verbose): print ".. done" return 0
5,433
25.90099
100
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/disk_script/run.py
from binary import circumbinary_disc_run from amuse.units import units # kepler 16 circumbinary_disc_run( tend=40. | units.yr, # simulation time Ngas=100000, # number of gas particles m1=0.6897 | units.MSun, # primary mass m2=0.20255 | units.MSun, # secondary mass r1=0.6489 | units.RSun, # primary radius r2=0.22623 | units.RSun, # secondary radius ecc=0.15944, # binary orbit eccentricity Pbinary=41.08 | units.day, # binary orbit period Rmin=2.3, # inner edge of initial disk Rmax=36., # out edge of initial disk q_out=12., # outer disk Toomre Q parameter discfraction=0.01, # disk mass fraction Raccretion=0.1 | units.AU, # accretion radius for sink particle dt_int=0.5 | units.day, # timestep for gas - binary grav interaction (bridge timestep) Pplanet=228.776 | units.day, # period of planet (makes the r-phi map rotate with this period) densitypower=1., # surface density powerlaw eosfreq=8, # times between EOS updates/sink particle checks mapfreq=1, # time between maps ( in units of dt=eosfreq*dt_int) Lmap=6. | units.AU, # size of map outputfreq=100, # output snapshot frequency (every ... dt=eosfreq*dt_int) outputdir='./kepler16', # output directory label='16', # label for run (only for terminal output) alpha=0.5, # viscosity alpha beta=1., # viscosity beta balsara=False ) # balsara viscosity switch
2,223
70.741935
119
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/disk_script/binary.py
import os from socket import gethostname import numpy import time import matplotlib matplotlib.use('Agg') from matplotlib import pyplot from amuse.community.twobody.twobody import TwoBody from amuse.units import units from amuse.units import nbody_system from amuse.units import constants from amuse.datamodel import Particles #from amuse.community.fi.interface import Fi from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.io import write_set_to_file,read_set_from_file from fast import FAST from directsum import directsum from boxedfi import BoxedFi as Fi def binary(interface,m1=1.|units.MSun,m2=.0001| units.MSun,r1=None,r2=None,ecc=0,P=1| units.yr): mu=constants.G*(m1+m2) a=(P/(2*numpy.pi)*mu**0.5)**(2./3.) f1=m2/(m1+m2) f2=m1/(m1+m2) rmax=a*(1+ecc) r0=rmax print 'semimajor axis:', a.in_(units.AU) print 'initial separation:',r0.in_(units.AU) h=(a*mu*(1-ecc**2))**0.5 v0=h/r0 bin=Particles(2) bin[0].mass=m1 bin[0].x=r0*f1 bin[0].vy=v0*f1 bin[1].mass=m2 bin[1].x=-r0*f2 bin[1].vy=-v0*f2 bin.y=0*r0 bin.z=0.*r0 bin.vx=0*v0 bin.vz=0.*v0 if r1 is None: bin[0].radius=(1.|units.RSun)*(m1/(1.|units.MSun))**(1./3.) else: bin[0].radius=r1 if r2 is None: bin[1].radius=(1.|units.RSun)*(m2/(1.|units.MSun))**(1./3.) else: bin[1].radius=r2 convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU) nb = interface(convert,redirection="none") nb.particles.add_particles(bin) return nb def sphdisc(interface,N=10000,Mstar=1| units.MSun, Rmin=1|units.AU, Rmax=10|units.AU, q_out=1.5, discfraction=0.1,densitypower=1,dt_sph=1|units.day, alpha=0.5,beta=1.0,balsara=False): convert=nbody_system.nbody_to_si(Mstar, Rmin.unit) proto=ProtoPlanetaryDisk(N,convert_nbody=convert,densitypower=densitypower, Rmin=Rmin.number,Rmax=Rmax.number,q_out=q_out, discfraction=discfraction) gas=proto.result gas.h_smooth=0.06 | units.AU gas.u0=gas.u.copy() sph=interface(convert,redirection='none') sph.parameters.use_hydro_flag=True sph.parameters.radiation_flag=False sph.parameters.self_gravity_flag=True sph.parameters.gamma=1. sph.parameters.isothermal_flag=True sph.parameters.integrate_entropy_flag=False sph.parameters.timestep=dt_sph sph.parameters.verbosity=0 sph.parameters.courant=0.2 sph.parameters.artificial_viscosity_alpha=alpha sph.parameters.beta=beta sph.parameters.balsara_flag=balsara # print sph.parameters.periodic_box_size.in_(units.AU) print 'disc mass:',gas.mass.sum().in_(units.MSun) sph.gas_particles.add_particles(gas) return sph,gas def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.AU(x) y=units.AU(y) z=units.AU(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return numpy.transpose(rho) def make_phi_map(sph,N=100,Rrange=(0.3,2),phioffset=0.): phi,r=numpy.mgrid[0:2*numpy.pi:N*1j,Rrange[0]:Rrange[1]:N*1j] phi=phi.flatten() r=r.flatten() x,y=r*numpy.cos(phi+phioffset),r*numpy.sin(phi+phioffset) z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.AU(x) y=units.AU(y) z=units.AU(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N,N)) return numpy.transpose(rho) def output_maps(tnow,bin,disc,Lmap,i,outputdir='./',Pplanet=None): L=Lmap.value_in(units.AU) rho=make_map(disc,N=200,L=L) f=pyplot.figure(figsize=(8,8)) pyplot.imshow(numpy.log10(1.e-15+rho.value_in(units.g/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=-13,vmax=-7.,origin='lower') pyplot.plot(bin.particles.x.value_in(units.AU), bin.particles.y.value_in(units.AU),'r+') pyplot.xlim(-L/2,L/2) pyplot.ylim(-L/2,L/2) pyplot.title(tnow) pyplot.xlabel('AU') pyplot.savefig(outputdir+'/map/map%6.6i.png'%i) f.clear() pyplot.close(f) if Pplanet is None: offset=0. else: offset=numpy.mod(2*numpy.pi*tnow.value_in(units.day)/Pplanet.value_in(units.day),2*numpy.pi) rho=make_phi_map(disc,N=200,phioffset=offset) f=pyplot.figure(figsize=(12,4)) pyplot.imshow(numpy.log10(1.e-15+rho.value_in(units.g/units.cm**3)), extent=[0,2*numpy.pi,0.3,2],vmin=-13.,vmax=-7.,origin='lower') x=bin.particles.x.value_in(units.AU) y=bin.particles.y.value_in(units.AU) r=(x**2+y**2)**0.5 phi=numpy.arctan2(y,x)-offset phi=numpy.mod(phi,2*numpy.pi) pyplot.plot(phi,r,'r+') pyplot.xlabel('phi') pyplot.ylabel('R') pyplot.xlim(0,2.*numpy.pi) pyplot.ylim(0.,2) pyplot.savefig(outputdir+'/map/phi-%6.6i.png'%i) f.clear() pyplot.close(f) def handle_eos(gas,memgas,rhotrans=(1.e-5 | units.g/units.cm**3), gamma=1.4): channel=gas.new_channel_to(memgas) channel.copy_attribute("rho") a=memgas.select_array(lambda rho: rho> rhotrans,["rho"]) a.u=a.u0*(a.rho/rhotrans)**gamma a=memgas.select_array(lambda rho: rho<= rhotrans,["rho"]) a.u=a.u0 channel=memgas.new_channel_to(gas) channel.copy_attribute("u") def sink_particles(sinks,sources,Raccretion=0.1 | units.AU): closest=numpy.array([-1]*len(sources)) mind2=(numpy.array([Raccretion.number]*len(sources)) | Raccretion.unit)**2 for i,s in enumerate(sinks): xs,ys,zs=s.x,s.y,s.z d2=(sources.x-xs)**2+(sources.y-ys)**2+(sources.z-zs)**2 select=numpy.where( d2<mind2 )[0] mind2[select]=d2[select] closest[select]=i to_remove=Particles(0) for i,s in enumerate(sinks): insink=numpy.where(closest == i)[0] if len(insink) > 0: cm=s.position*s.mass p=s.velocity*s.mass insinkp=Particles(0) for ip in insink: insinkp.add_particle(sources[ip]) s.mass+=insinkp.total_mass() s.position=(cm+insinkp.center_of_mass()*insinkp.total_mass())/s.mass s.velocity=(p+insinkp.total_momentum())/s.mass # we lose angular momentum ! to_remove.add_particles(insinkp) print len(insinkp),"particles accrete on star", i if len(to_remove)>0: sources.remove_particles(to_remove) def circumbinary_disc_run(tend=10. | units.yr, # simulation time Ngas=10000, # number of gas particles m1=1. | units.MSun, # primary mass m2=1. | units.MSun, # secondary mass r1=1. | units.RSun, # primary radius r2=1. | units.RSun, # secondary radius ecc=0., # binary orbit eccentricity Pbinary=25. | units.day, # binary orbit period Rmin=0.6 | units.AU, # inner edge of initial disk Rmax=8.0 |units.AU, # out edge of initial disk q_out=12., # outer disk Toomre Q parameter discfraction=0.01, # disk mass fraction Raccretion=0.1 | units.AU, # accretion radius for sink particle dt_int=1.|units.day, # timestep for gas - binary grav interaction (bridge timestep) Pplanet=None, # period of planet (makes the r-phi map rotate with this period) densitypower=1., # surface density powerlaw eosfreq=2, # times between EOS updates/sink particle checks mapfreq=1, # time between maps ( in units of dt=eosfreq*dt_int) Lmap=6. | units.AU, # size of map outputfreq=20, # output snapshot frequency (every ... dt=eosfreq*dt_int) outputdir='./', # output directory label='anonymous', # label for run (only for terminal output) overwrite=False, alpha=0.5, beta=1.0, balsara=False ): if outputdir=='./': outputdir=os.getcwd() print "output directory of run "+label+" is:", outputdir if overwrite and outputdir !=os.getcwd(): import shutil shutil.rmtree(outputdir) if outputdir !=os.getcwd(): os.mkdir(outputdir) os.mkdir(outputdir+'/map') os.mkdir(outputdir+'/snap') a=(Pbinary/(2*numpy.pi)*(constants.G*(m1+m2))**0.5)**(2./3.) try: Rmin.unit except: Rmin=(Rmin*a).in_(units.AU) try: Rmax.unit except: Rmax=(Rmax*a).in_(units.AU) print "binary semi major axis:", a.in_(units.AU) print "disc inner edge:", Rmin.in_(units.AU) print "disc outer edge:", Rmax.in_(units.AU) bin=binary(TwoBody,m1=m1,m2=m2,r1=r1,r2=r2,ecc=ecc,P=Pbinary) disc,gas=sphdisc(Fi,Ngas,bin.particles.mass.sum(),Rmin=Rmin, Rmax=Rmax, q_out=q_out, discfraction=discfraction,densitypower=densitypower, dt_sph=dt_int,alpha=alpha,beta=beta,balsara=balsara) directsum_disc=directsum( (disc,) ) bridge=FAST(verbose=False) bridge.set_timestep(dt_int) bridge.add_system(bin, (directsum_disc,), False) bridge.add_system(disc, (bin,), False) tnow=0. | units.day dt=eosfreq*dt_int print "bridge timestep=", dt_int.in_(units.day) print "eos timestep=", dt.in_(units.day) print "map timestep=", (dt*mapfreq).in_(units.day) print "snap timestep=", (dt*outputfreq).in_(units.day) i=0 time_begin=time.time() while tnow < tend-dt/2: if i%outputfreq==0: write_set_to_file(bin.particles,outputdir+'/snap/bin-%6.6i'%(i),'amuse') write_set_to_file(disc.gas_particles,outputdir+'/snap/disc-%6.6i'%(i),'amuse') tnow+=dt i+=1 handle_eos(disc.particles,gas,rhotrans=(1.e-5 | units.g/units.cm**3)) sink_particles(bin.particles,disc.particles,Raccretion=Raccretion) bridge.evolve_model(tnow) frac=(tnow/tend) time_now=time.time() print 'sim '+label+' reached:',tnow, ": %4.2f%%, ETA: %6.2f hours"%(100*frac, (time_now-time_begin)/frac*(1-frac)/3600) if i%mapfreq==0: output_maps(tnow,bin,disc,Lmap,i,outputdir,Pplanet) return gethostname(),outputdir if __name__=="__main__": circumbinary_disc_run( tend=100. | units.yr, # simulation time Ngas=100000, # number of gas particles m1=1.0479 | units.MSun, # primary mass m2=1.0208 | units.MSun, # secondary mass r1=1.1618 | units.RSun, # primary radius r2=1.0927 | units.RSun, # secondary radius ecc=0.52087, # binary orbit eccentricity Pbinary=27.7958| units.day, # binary orbit period Rmin=2., # inner edge of initial disk (in AU or (w/o units) in a_binary) Rmax=36, # outer edge of initial disk (in AU or (w/o units) in a_binary) q_out=12., # outer disk Toomre Q parameter discfraction=0.01, # disk mass fraction Raccretion=0.1 | units.AU, # accretion radius for sink particle dt_int=1. | units.day, # timestep for gas - binary grav interaction (bridge timestep) Pplanet=288.822 | units.day, # period of planet (makes the r-phi map rotate with this period) densitypower=1., # surface density powerlaw eosfreq=4, # times between EOS updates/sink particle checks mapfreq=1, # time between maps ( in units of dt=eosfreq*dt_int) Lmap=6. | units.AU, # size of map outputfreq=100, # output snapshot frequency (every ... dt=eosfreq*dt_int) outputdir='./r15', # output directory label='34b' # label for run (only for terminal output) ) # mencoder "mf://map*.png" -mf fps=20 -ovc x264 -o movie.avi
12,738
34.884507
123
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/disk_script/directsum.py
from amuse.units import constants from amuse.datamodel import Particles from amuse.units.quantities import zero from amuse.units.quantities import AdaptingVectorQuantity class directsum(object): def __init__(self, systems, G=constants.G): self.systems=systems self.G=G def get_gravity_at_point(self,radius,x,y,z): part=Particles(0) for s in self.systems: part.add_particles(s.particles) ax=AdaptingVectorQuantity() ay=AdaptingVectorQuantity() az=AdaptingVectorQuantity() for rr,xx,yy,zz in zip(radius,x,y,z): dr2=((part.x-xx)**2+(part.y-yy)**2+(part.z-zz)**2+rr**2+part.radius**2) ax.append( (self.G*part.mass*(part.x-xx)/dr2**1.5).sum() ) ay.append( (self.G*part.mass*(part.y-yy)/dr2**1.5).sum() ) az.append( (self.G*part.mass*(part.z-zz)/dr2**1.5).sum() ) return ax,ay,az def get_potential_at_point(self,radius,x,y,z): part=Particles(0) for s in self.systems: part.add_particles(s.particles) phi=AdaptingVectorQuantity() for rr,xx,yy,zz in zip(radius,x,y,z): dr2=((part.x-xx)**2+(part.y-yy)**2+(part.z-zz)**2+rr**2+part.radius**2) phi.append( (-self.G*part.mass/dr2**0.5).sum() ) return phi
1,332
38.205882
81
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/three_body_script/python_interface.py
from amuse.rfi.core import * import cPickle as Pickle from amuse.units import units #from testmod import f from bin_planet import binary_with_planet_run as f def func(*arg,**kwarg): return f(*arg,**kwarg) class CodeImplementation(object): def _func(self,argin,kwargin,argout): try: arg=Pickle.loads(argin) kwarg=Pickle.loads(kwargin) result=func(*arg,**kwarg) argout.value=Pickle.dumps(result,-1) return 0 except Exception as ex: print ex argout.value=Pickle.dumps(" ",-1) return -1 class CodeInterface(PythonCodeInterface): def __init__(self, **options): PythonCodeInterface.__init__(self, CodeImplementation, **options) @legacy_function def _func(): function = LegacyFunctionSpecification() function.addParameter('argin', dtype='string', direction=function.IN) function.addParameter('kwargin', dtype='string', direction=function.IN) function.addParameter('argout', dtype='string', direction=function.OUT) function.result_type = 'int32' return function def func(self,*args,**kwargs): result,err=self._func(Pickle.dumps( args,-1),Pickle.dumps( kwargs,-1)) return Pickle.loads(result[0]),err def async_func(self,*args,**kwargs): request=self._func.async(Pickle.dumps( args,-1),Pickle.dumps( kwargs,-1)) def f(x): result,err=x() return Pickle.loads(result[0]),err request.add_result_handler( f ) return request
1,540
30.44898
81
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/three_body_script/kepler_16_three_body.py
from python_interface import CodeInterface from amuse.units import units from amuse.rfi.channel import AsyncRequestsPool import numpy from matplotlib import pyplot ncpu=16 allhosts=[ ("paddegat",4), ("koppoel",4), ("gaasp",4), ("biesbosch",4), ] hosts=reduce(lambda x,y: x+[y[0]]*y[1],allhosts,[]) print hosts m_planet=0.333 | units.MJupiter r_planet=0.754 | units.RJupiter, m1=0.6897| units.MSun # primary mass m2=0.20255| units.MSun # secondary mass r1=0.6489 | units.RSun # primary radius r2=0.22623| units.RSun # secondary radius ecc_binary=0.15944 # binary orbit eccentric$ P_binary=41.08| units.day # binary orbit period a_binary=0.2243 # units.AU amin=2. amax=10. results=[] N=40 M=40 aset= ( a_binary*(amin+j*(amax-amin)/(M+1)) for j in range(M+1) ) eset= [ j*0.5/N for j in range(N+1)] current_a=0 pool=AsyncRequestsPool() def finalize_job(request,i_ecc,a,code,host): print "done with", eset[i_ecc],a result,err=request.result() print result results.append((eset[i_ecc],a,result)) if result[0]=="stable" or i_ecc==0: # if i_ecc==0: try: a=aset.next() except: a=None if a is not None: i_ecc=N add_job(i_ecc,a,code,host) else: i_ecc-=1 add_job(i_ecc,a,code,host) def add_job(i_ecc,a,code=None,host=""): ecc=eset[i_ecc] if code is None: host=hosts.pop() code=CodeInterface(hostname=host) print "adding:",(ecc,a),' on: ',host request=code.async_func( m1=m1,m2=m2,m_planet=m_planet, r1=r1,r2=r2,r_planet=r_planet, ecc_binary=ecc_binary,P_binary=P_binary,ecc_planet=ecc,a_planet=a | units.AU, pangle_planet=numpy.pi, tend=1000000.| units.yr,hostname=host) pool.add_request( request, finalize_job, [i_ecc,a,code,host]) for i in range(ncpu): try: a=aset.next() except: a=None if a is not None: i_ecc=N add_job(i_ecc,a) while len(pool)>0: print "waiting for job to finish.." pool.wait() f=open('results_16_pi','w') import cPickle cPickle.dump(results,f) f.close()
2,111
21.709677
83
py
amuse
amuse-main/examples/publications/2013MNRAS.429..895P/three_body_script/bin_planet.py
import numpy import time from matplotlib import pyplot from amuse.units import nbody_system,units,constants from amuse.units.quantities import AdaptingVectorQuantity from amuse.io import write_set_to_file,read_set_from_file from amuse.community.huayno.interface import Huayno from amuse.datamodel import Particles def binary(m1=1.|units.MSun,m2=1.| units.MSun,r1=None,r2=None,ecc=0,P=1| units.yr): mu=constants.G*(m1+m2) a=(P/(2*numpy.pi)*mu**0.5)**(2./3.) f1=m2/(m1+m2) f2=m1/(m1+m2) rmax=a*(1+ecc) r0=rmax h=(a*mu*(1-ecc**2))**0.5 v0=h/r0 bin=Particles(2) bin[0].mass=m1 bin[0].x=r0*f1 bin[0].vy=v0*f1 bin[1].mass=m2 bin[1].x=-r0*f2 bin[1].vy=-v0*f2 bin.y=0*r0 bin.z=0.*r0 bin.vx=0*v0 bin.vz=0.*v0 if r1 is None: bin[0].radius=(1.|units.RSun)*(m1/(1.|units.MSun))**(1./3.) else: bin[0].radius=r1 if r2 is None: bin[1].radius=(1.|units.RSun)*(m2/(1.|units.MSun))**(1./3.) else: bin[1].radius=r2 return bin def binary_with_planet(m1=1.|units.MSun, m2=1.| units.MSun, m_planet=1|units.MJupiter, r1=None, r2=None, r_planet=None, ecc_binary=0, P_binary=20 | units.day, ecc_planet=0., P_planet=1.| units.yr, pangle_planet=0., a_planet=None): parts=binary(m1,m2,r1,r2,ecc_binary,P_binary) mu=constants.G*(m1+m2+m_planet) if a_planet is None: if P_planet is None: print "provide a_planet or P_planet" raise Exception a_planet=(P_planet/(2*numpy.pi)*mu**0.5)**(2./3.) rmax=a_planet*(1+ecc_planet) r0=rmax print a_planet print a_planet.in_(units.AU),r0.in_(units.AU) h=(a_planet*mu*(1-ecc_planet**2))**0.5 v0=h/r0 planet=Particles(1) planet.mass=m_planet if r_planet is None: r_planet=(1.|units.RJupiter)*(m_planet/(1.|units.MJupiter))**(1./3.) planet.radius=r_planet planet.x=numpy.cos(pangle_planet)*r0 planet.y=numpy.sin(pangle_planet)*r0 planet.z=0.*r0 planet.vx=-numpy.sin(pangle_planet)*v0 planet.vy=numpy.cos(pangle_planet)*v0 planet.vz=0.*v0 parts.add_particles(planet) parts.move_to_center() return parts def elements(starmass,x,y,z,vx,vy,vz,G=constants.G): mu=G*starmass r=(x**2+y**2+z**2)**0.5 v2=(vx**2+vy**2+vz**2) e=v2/2-mu/r a=-mu/2/e hx=y*vz-z*vy hy=z*vx-x*vz hz=x*vy-y*vx rdotv=x*vx+y*vy+z*vz ex=v2*x/mu-rdotv*vx/mu-x/r ey=v2*y/mu-rdotv*vy/mu-y/r ez=v2*z/mu-rdotv*vz/mu-z/r pangle= numpy.arctan2(ex,ey) # assuming orbits in plane pangle=pangle h2=(hx**2+hy**2+hz**2) eps=(1-h2/mu/a)**0.5 return a,eps,pangle def binary_with_planet_run(m1=1.|units.MSun, m2=1.| units.MSun, m_planet=1|units.MJupiter, r1=None, r2=None, r_planet=None, ecc_binary=0, P_binary=20 | units.day, ecc_planet=0., P_planet=1.| units.yr, pangle_planet=0., a_planet=None, tend=100. | units.yr,hostname=''): dEcrit=1.e-6 three=binary_with_planet(m1=m1,m2=m2,m_planet=m_planet,r1=r1,r2=r2,r_planet=r_planet, ecc_binary=ecc_binary,P_binary=P_binary, ecc_planet=ecc_planet,a_planet=a_planet,pangle_planet=pangle_planet) convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU) code=Huayno(convert,hostname=hostname) code.parameters.inttype_parameter=code.inttypes.SHARED10 code.parameters.timestep_parameter=.2 code.parameters.timestep=100. | units.day dt=10000. | units.day code.particles.add_particles(three) E0=code.potential_energy+code.kinetic_energy a0,eps0,pangle0=elements( three.total_mass(), code.particles.x[2], code.particles.y[2], code.particles.z[2], code.particles.vx[2], code.particles.vy[2], code.particles.vz[2] ) t=0. | units.day result="stable" while(t < tend-dt/2): t=t+dt code.evolve_model(t) E=code.potential_energy+code.kinetic_energy dE=abs(((E-E0)/E0)) a,eps,pangle=elements( three.total_mass(), code.particles.x[2], code.particles.y[2], code.particles.z[2], code.particles.vx[2], code.particles.vy[2], code.particles.vz[2] ) if dE > dEcrit or a<0.5*a0 or a>2.*a0: result="unstable" if dE > dEcrit: result="failed" break code.stop() return result,t,dE,a.in_(units.AU),eps,pangle def test_run(): three=binary_with_planet( m1=0.6897 | units.MSun,m2=0.20255 | units.MSun,m_planet=0.333 | units.MJupiter, r1=0.6489 | units.RSun,r2=0.22623 | units.RSun,r_planet=0.754 | units.RJupiter, ecc_binary=0.15944,P_binary=41.08| units.day,ecc_planet=0.00685,a_planet=.7048 | units.AU, pangle_planet=0.) convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU) code=Huayno(convert) code.parameters.inttype_parameter=code.inttypes.SHARED4 code.parameters.timestep_parameter=0.1 # tend=100. | units.yr tend=100. | units.day snapfreq=1 dt=10. | units.day # dt=convert.to_si( 1. | nbody_system.time).in_(units.day) code.particles.add_particles(three) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() z = AdaptingVectorQuantity() vx = AdaptingVectorQuantity() vy = AdaptingVectorQuantity() vz = AdaptingVectorQuantity() x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) ts=[0.] E0=code.potential_energy+code.kinetic_energy dE=[1.e-14] t=0. | units.day i=0 while(t < tend-dt/2): i+=1 t=t+dt if i%snapfreq==0: print t ts.append(t.value_in(units.day)) code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) E=code.potential_energy+code.kinetic_energy dE.append(abs(((E-E0)/E0))) code.stop() a,eps,pangle=elements(three.total_mass(), x[:,2], y[:,2], z[:,2], vx[:,2], vy[:,2], vz[:,2]) x=x.value_in(units.AU) y=y.value_in(units.AU) a=a.value_in(units.AU) eps=eps print a[-1],eps[-1],pangle[-1] f=pyplot.figure(figsize=(8,8)) pyplot.plot(x[:,0],y[:,0],'r.') pyplot.plot(x[:,1],y[:,1],'g.') pyplot.plot(x[:,2],y[:,2],'b.') pyplot.xlim(-3,3) pyplot.ylim(-3,3) pyplot.xlabel('AU') pyplot.savefig('three_16b.eps') f=pyplot.figure(figsize=(8,8)) pyplot.semilogy(ts,dE,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('dE/E0') pyplot.savefig('three_16b_eerr.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,a,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('a (AU)') pyplot.savefig('three_16b_a.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,eps,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('eccentricity') pyplot.savefig('three_16b_ecc.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,pangle,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('long. of periapsis') pyplot.savefig('three_16b_pangle.eps') if __name__=="__main__": result,t,dE,a,eps,pangle=binary_with_planet_run( m1=0.6897 | units.MSun,m2=0.20255 | units.MSun,m_planet=0.333 | units.MJupiter, r1=0.6489 | units.RSun,r2=0.22623 | units.RSun,r_planet=0.754 | units.RJupiter, ecc_binary=0.52,P_binary=41.08| units.day,ecc_planet=0.00685,a_planet=.87048 | units.AU, pangle_planet=0., tend=1000.| units.yr,hostname="gaasp") print result,t,dE,a,eps,pangle
7,935
26.651568
98
py
amuse
amuse-main/examples/simple/pre_main_sequence_evolution.py
# -*- coding: ascii -*- """ Calculated theoretical pre-main-sequance evolutionary tracks for stars of various masses. After Iben, ApJ 141, 993, 1965 """ from __future__ import print_function from matplotlib import pyplot from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel def simulate_evolution_tracks( masses=[0.5, 1.0, 1.25, 1.5, 2.25, 3.0, 5.0, 9.0, 15.0] | units.MSun ): stellar_evolution = MESA() stellar_evolution.parameters.AGB_wind_scheme = 0 stellar_evolution.parameters.RGB_wind_scheme = 0 stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.pre_ms_stars.add_particles(stars) data = {} for star in stars: luminosity = [] | units.LSun temperature = [] | units.K time = [] | units.yr print('Evolving pre main sequence star with') print(' mass:', star.mass) print(' luminosity:', star.luminosity) print(' radius:', star.radius) while star.stellar_type == 17 | units.stellar_type: luminosity.append(star.luminosity) temperature.append(star.temperature) time.append(star.age) star.evolve_one_step() print('Evolved pre main sequence star to:', star.stellar_type) print(' age:', star.age) print(' mass:', star.mass) print(' luminosity:', star.luminosity) print(' radius:', star.radius) print() stardata = {} stardata['luminosity'] = luminosity stardata['temperature'] = temperature stardata['time'] = time data[star.mass] = stardata return data def plot_track(data): figure = pyplot.figure(figsize=(6, 8)) plot = figure.add_subplot(1, 1, 1) plot.set_title('Hertzsprung-Russell diagram', fontsize=12) temp_unit = units.K luminosity_unit = units.LSun for mass, stardata in list(data.items()): temperature = stardata['temperature'] luminosity = stardata['luminosity'] plot.loglog( temperature[4:].value_in(temp_unit), luminosity[4:].value_in(luminosity_unit), marker="s") # first few points show transient plot.text( 1.25 * temperature[-1].value_in(temp_unit), 0.5 * luminosity[-1].value_in(luminosity_unit), str(mass)) plot.set_xlabel('Effective Temperature [' + str(temp_unit) + ']') plot.set_ylabel('Luminosity [' + str(luminosity_unit) + ']') plot.set_xlim(10**4.6, 10**3.5) plot.set_ylim(1.0e-2, 1.e5) pyplot.show() if __name__ == "__main__": data = simulate_evolution_tracks(masses=[0.5, 1.0, 1.25] | units.MSun) plot_track(data)
2,752
31.011628
76
py
amuse
amuse-main/examples/simple/helium_star.py
# -*- coding: ascii -*- """ Creates a helium burning star from the inner shells of a main sequence star. """ from __future__ import print_function from amuse.units import units from amuse.datamodel import Particle from amuse.community.mesa.interface import MESA from matplotlib import pyplot from amuse.plot import loglog, xlabel, ylabel def main(): temperatures_original = [] | units.K luminosities_original = [] | units.LSun temperatures_helium = [] | units.K luminosities_helium = [] | units.LSun star = Particle() star.mass = 10.0 | units.MSun stop_radius = 100 | units.RSun stellar_evolution = MESA() se_star = stellar_evolution.particles.add_particle(star) print( "Evolving a", star.mass, "star with", stellar_evolution.__class__.__name__, end=' ') print("until its radius exceeds", stop_radius) while (se_star.radius < stop_radius): se_star.evolve_one_step() temperatures_original.append(se_star.temperature) luminosities_original.append(se_star.luminosity) number_of_zones = se_star.get_number_of_zones() composition = se_star.get_chemical_abundance_profiles( number_of_zones=number_of_zones) # first index where H fraction > 1.0e-9 index = (composition[0] > 1.0e-9).nonzero()[0][0] print("Creating helium star, from the inner", index, "(out of", str(number_of_zones) + ") shells.") helium_star = stellar_evolution.new_particle_from_model(dict( mass=(se_star.get_cumulative_mass_profile( number_of_zones=number_of_zones) * se_star.mass)[:index], radius=se_star.get_radius_profile( number_of_zones=number_of_zones)[:index], rho=se_star.get_density_profile( number_of_zones=number_of_zones)[:index], temperature=se_star.get_temperature_profile( number_of_zones=number_of_zones)[:index], luminosity=se_star.get_luminosity_profile( number_of_zones=number_of_zones)[:index], X_H=composition[0][:index], X_He=composition[1][:index] + composition[2][:index], X_C=composition[3][:index], X_N=composition[4][:index], X_O=composition[5][:index], X_Ne=composition[6][:index], X_Mg=composition[7][:index], X_Si=composition[7][:index] * 0.0, X_Fe=composition[7][:index] * 0.0), 0.0 | units.Myr) print("\nStar properties before helium star evolution:\n", stellar_evolution.particles) for i in range(1000): helium_star.evolve_one_step() temperatures_helium.append(helium_star.temperature) luminosities_helium.append(helium_star.luminosity) print("\nStar properties after helium star evolution:\n", stellar_evolution.particles) stellar_evolution.stop() return ( temperatures_original, luminosities_original, temperatures_helium, luminosities_helium ) def plot_tracks( temperatures_original, luminosities_original, temperatures_helium, luminosities_helium): pyplot.figure(figsize=(8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperatures_original, luminosities_original, label='progenitor') loglog(temperatures_helium, luminosities_helium, label='helium star') xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.ylim(1.0, 1.0e5) pyplot.legend(loc=3) pyplot.show() if __name__ == "__main__": temperatures_original, luminosities_original, temperatures_helium, \ luminosities_helium = main() plot_tracks(temperatures_original, luminosities_original, temperatures_helium, luminosities_helium)
3,738
35.656863
76
py
amuse
amuse-main/examples/simple/stellar_lifetime_vs_mass.py
# -*- coding: ascii -*- """ Calculates the stellar lifetime in a range of masses between Mmax and Mmin using SSE (or another stellar evolution code) and an analytic expression. """ from __future__ import print_function import numpy from optparse import OptionParser from amuse.units import units from amuse.datamodel import Particle from amuse.plot import plot from matplotlib import pyplot as plt from amuse.community.sse.interface import SSE se = None def stellar_remnant_state(star): return 10 <= star.stellar_type.value_in(units.stellar_type) < 16 def stellar_lifetime(mZAMS, z=0.02): global se if se is None: se = SSE() se.parameters.metallicity = z se.particles.add_particle(Particle(mass=mZAMS)) while not stellar_remnant_state(se.particles[0]): se.evolve_model() t_end = se.particles[0].age # tpe = se.particles[0].stellar_type se.particles.remove_particle(se.particles[0]) return t_end def power_law_fit_to_main_sequence_lifetime(mZAMS): return 2 + 1.0E+4 / pow(mZAMS.value_in(units.MSun), 2.5) | units.Myr def main(n=10, mmin=1.0, mmax=100, z=0.02): dm = (mmax - mmin) / n mZAMS = numpy.arange(mmin, mmax, dm) | units.MSun mmin = mmin | units.MSun mmax = mmax | units.MSun print(mZAMS) t_sse = [] | units.Myr t_analytic = [] | units.Myr for mi in mZAMS: t_sse.append(stellar_lifetime(mi, z)) t_analytic.append(power_law_fit_to_main_sequence_lifetime(mi)) plot(mZAMS, t_sse, label="sse") plot(mZAMS, t_analytic, label="analytic") plt.loglog() plt.legend() plt.title("comparison between SSE and analytic with z=" + str(z)) plt.show() def new_option_parser(): result = OptionParser() result.add_option("-n", dest="n", type="int", default=10, help="number of stars") result.add_option("-m", dest="mmin", type="float", default=1.0, help="Minimal mass [1.0] MSun") result.add_option("-M", dest="mmax", type="float", default=100.0, help="Maximal mass [100] MSun") result.add_option("-z", dest="z", type="float", default=0.02, help="metalicity [0.02]") return result if __name__ == "__main__": o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,332
29.697368
72
py
amuse
amuse-main/examples/simple/clump_finding.py
# -*- coding: ascii -*- """ Generates a random distribution of particles and uses Hop to determine clumps in the particle set. """ from __future__ import print_function # import numpy from numpy import random from matplotlib import pyplot from amuse.units import units from amuse.units import nbody_system from amuse.community.hop.interface import Hop from amuse.datamodel.particles import Particles from amuse.ic.salpeter import new_salpeter_mass_distribution def new_cluster(number_of_stars=1000): masses = new_salpeter_mass_distribution( number_of_stars, mass_min=0.1 | units.MSun, mass_max=125.0 | units.MSun, alpha=-2.35 ) particles = Particles(number_of_stars) particles.mass = masses particles.x = units.parsec(random.gamma(2.0, 1.0, number_of_stars)) particles.y = units.parsec(random.gamma(1.0, 1.0, number_of_stars)) particles.z = units.parsec(random.random(number_of_stars)) return particles def find_clumps(particles, unit_converter): hop = Hop(unit_converter) hop.particles.add_particles(particles) hop.calculate_densities() hop.do_hop() result = [x.get_intersecting_subset_in(particles) for x in hop.groups()] hop.stop() return result def plot_clumps(groups, total_mass): number_of_particles_in_group = [] fraction_of_mass_in_group = [] for group in groups: number_of_particles_in_group.append(len(group)) fraction = (group.mass.sum() / total_mass) fraction_of_mass_in_group.append(fraction) figure = pyplot.figure(figsize=(12, 6)) subplot = figure.add_subplot(1, 2, 1) colormap = pyplot.cm.Paired for index, group in enumerate(groups): color = colormap(1.0 * index / len(groups)) subplot.scatter( group.x.value_in(units.parsec), group.y.value_in(units.parsec), s=group.mass.value_in(units.MSun), edgecolors=color, facecolors=color ) subplot.set_xlim(0, 1) subplot.set_ylim(0, 1) subplot.set_xlabel('x (parsec)') subplot.set_ylabel('y (parsec)') subplot = figure.add_subplot(1, 2, 2) subplot.plot( number_of_particles_in_group, fraction_of_mass_in_group, ) subplot.set_xscale('log') subplot.set_yscale('log') subplot.set_xlabel('N') subplot.set_ylabel('df/d(Log_10 N)') figure.savefig('x.png') pyplot.show() if __name__ == "__main__": number_of_stars = 10000 stars = new_cluster(number_of_stars) total_mass = stars.mass.sum() unit_converter = nbody_system.nbody_to_si(total_mass, 1 | units.parsec) groups = find_clumps(stars, unit_converter) plot_clumps(groups, total_mass)
2,734
25.553398
77
py
amuse
amuse-main/examples/simple/agb.py
# -*- coding: ascii -*- """ Evolves an the sun in it's AGB star phase using SSE """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.community.sse.interface import SSE from amuse.units import units # from amuse.ext import solarsystem from amuse import datamodel def plottillagb(): sun = datamodel.Particle( mass=1 | units.MSun, radius=1 | units.RSun ) sse = SSE() sse.particles.add_particle(sun) channel_from_se_to_memory = sse.particles.new_channel_to(sun.as_set()) channel_from_se_to_memory.copy() masses = [] | units.MSun timerange = numpy.arange(11500, 13500, 10) | units.Myr for time in timerange: sse.evolve_model(time) channel_from_se_to_memory.copy() masses.append(sun.mass) print(time.as_quantity_in(units.Myr), sun.mass.as_quantity_in(units.MSun)) sse.stop() figure = pyplot.figure(figsize=(6, 6)) subplot = figure.add_subplot(1, 1, 1) subplot.plot(timerange.value_in(units.Gyr), masses.value_in(units.MSun), '.') subplot.set_xlabel('t (Gyr)') subplot.set_ylabel('mass (MSun)') pyplot.show() if __name__ == '__main__': plottillagb()
1,247
22.54717
74
py
amuse
amuse-main/examples/simple/cluster.py
# -*- coding: ascii -*- """ Evolves an equal mass stellar cluster. """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.units import nbody_system from amuse.community.hermite.interface import Hermite # import logging from amuse.ic.plummer import new_plummer_model # logging.basicConfig(level=logging.DEBUG) smoothing_length = 0.0 | nbody_system.length ** 2 def print_log(time, gravity, particles, total_energy_at_t0): kinetic_energy = gravity.kinetic_energy potential_energy = gravity.potential_energy total_energy_at_this_time = kinetic_energy + potential_energy print("time : ", time) print("energy error : ", ( total_energy_at_this_time - total_energy_at_t0) / total_energy_at_t0) def simulate_small_cluster( number_of_stars=1000, end_time=40 | nbody_system.time, number_of_workers=1 ): particles = new_plummer_model(number_of_stars) particles.scale_to_standard() gravity = Hermite(number_of_workers=number_of_workers) gravity.parameters.epsilon_squared = 0.15 | nbody_system.length ** 2 gravity.particles.add_particles(particles) from_gravity_to_model = gravity.particles.new_channel_to(particles) time = 0.0 * end_time total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy positions_at_different_times = [] positions_at_different_times.append(particles.position) times = [] times.append(time) print("evolving the model until t = " + str(end_time)) while time < end_time: time += end_time / 3.0 gravity.evolve_model(time) from_gravity_to_model.copy() positions_at_different_times.append(particles.position) times.append(time) print_log(time, gravity, particles, total_energy_at_t0) gravity.stop() return times, positions_at_different_times def adjust_spines(ax, spines, ticks): for loc, spine in ax.spines.items(): if loc in spines: spine.set_position(('outward', 10)) # outward by 10 points spine.set_smart_bounds(True) else: spine.set_color('none') # don't draw spine if 'left' in spines: ax.yaxis.set_ticks_position('left') ax.yaxis.set_ticks(ticks) else: ax.yaxis.set_ticks([]) if 'bottom' in spines: ax.xaxis.set_ticks_position('bottom') ax.xaxis.set_ticks(ticks) else: ax.xaxis.set_ticks([]) def plot_positions(times, positions_at_different_times): figure = pyplot.figure() plot_matrix_size = numpy.ceil(numpy.sqrt( len(positions_at_different_times))).astype(int) number_of_rows = len(positions_at_different_times) / plot_matrix_size figure.subplots_adjust(wspace=0.15, hspace=0.15) for index, (time, positions) in enumerate( zip(times, positions_at_different_times) ): subplot = figure.add_subplot( plot_matrix_size, plot_matrix_size, index + 1) subplot.scatter( positions[..., 0].value_in(nbody_system.length), positions[..., 1].value_in(nbody_system.length), s=1, edgecolors='red', facecolors='red' ) subplot.set_xlim(-4.0, 4.0) subplot.set_ylim(-4.0, 4.0) title = 'time = {0:.2f}'.format(time.value_in(nbody_system.time)) subplot.set_title(title) # , fontsize=12) spines = [] if index % plot_matrix_size == 0: spines.append('left') if index >= ((number_of_rows - 1) * plot_matrix_size): spines.append('bottom') adjust_spines(subplot, spines, numpy.arange(-4.0, 4.1, 1.0)) if index % plot_matrix_size == 0: subplot.set_ylabel('y') if index >= ((number_of_rows - 1) * plot_matrix_size): subplot.set_xlabel('x') pyplot.show() if __name__ == "__main__": times, positions_at_different_time = simulate_small_cluster( 300, 9.0 | nbody_system.time ) plot_positions(times, positions_at_different_time)
4,118
28.847826
77
py
amuse
amuse-main/examples/simple/orbit_in_potential.py
# -*- coding: ascii -*- """ Integrates a stellar orbit in the galactic potential This example illustrates the use of a simple external potential and simple integrator, no amuse community code is used. """ from __future__ import print_function # import numpy from amuse.units.optparse import OptionParser from math import atan from math import log from amuse.units import units, constants from amuse.units.quantities import AdaptingVectorQuantity from amuse.datamodel import Particle from matplotlib import pyplot from amuse.plot import plot class MilkyWay_galaxy(object): def __init__(self, potential="point_particle", M=1.6e10 | units.MSun): print("pot=", potential) if potential.find("Milky") >= 0: print("Milky Way Potential") self.potential = self.Milky_Way_potential else: self.potential = self.point_particle_potential self.M = M # Generic function to get gravity at a point given the potential def get_gravity_at_point(self, pos): phi_0 = self.get_potential_at_point(pos) grav = AdaptingVectorQuantity() dpos = 0.001 * pos.length() for ii in range(len(pos)): ppos = 1.0 * pos ppos[ii] += dpos phi_1 = self.get_potential_at_point(ppos) grav.append((phi_1 - phi_0) / dpos) return grav def get_potential_at_point(self, pos): phi = self.potential(pos) return phi def point_particle_potential(self, pos): return self.Kepler_potential(self.M, pos) def Kepler_potential(self, mass, pos, eps2=0.0 | units.kpc**2): return self.Power_law_potential(mass, pos, eps2=eps2, eta=1) def Power_law_potential(self, mass, pos, eps2=0.0 | units.kpc**2, eta=1): return constants.G * mass / (pos.length()**2 + eps2)**(eta / 2.) def disk_and_bulge_potentials(self, pos, a, b, mass): r = (pos.x**2 + pos.y**2).sqrt() return constants.G * mass /\ (r**2 + (a + (pos.z**2 + b**2).sqrt())**2).sqrt() def halo_potential( self, pos, Mc=5.0E+10 | units.MSun, Rc=1.0 | units.kpc**2): r = pos.length() rr = (r / Rc) return -constants.G * (Mc / Rc) * \ (0.5 * log(1 + rr**2) + atan(rr) / rr) # 1990ApJ...348..485P def Milky_Way_potential(self, pos): pot_disk = self.disk_and_bulge_potentials(pos, 0.0 | units.kpc, 0.277 | units.kpc, 1.12E+10 | units.MSun) pot_bulge = self.disk_and_bulge_potentials(pos, 3.7 | units.kpc, 0.20 | units.kpc, 8.07E+10 | units.MSun) pot_halo = self.halo_potential(pos, Mc=5.0E+10 | units.MSun, Rc=6.0 | units.kpc) return pot_disk + pot_bulge + pot_halo def new_single_star(mass, pos, vel): single_star = Particle() single_star.mass = mass single_star.position = pos single_star.velocity = vel single_star.radius = 1.0 | units.RSun return single_star def evolve_particle_in_potential(single_star, potential, t_end): time = 0 | units.Myr dt_min = 0.1 * t_end while time < t_end: acc = potential.get_gravity_at_point(single_star.position) dt = min(dt_min, 0.1 * single_star.velocity.length() / acc.length()) single_star.velocity += acc * dt single_star.position += single_star.velocity * dt time += dt def evolve_particle_trajectory_in_potential( single_star, potential, dt_diag, t_end): time = 0 | units.Myr x = [] | size_unit y = [] | size_unit z = [] | size_unit while time < t_end: evolve_particle_in_potential(single_star, potential, dt_diag) time += dt_diag print( "time=", time, single_star.position.length().as_quantity_in(units.AU)) x.append(single_star.x) y.append(single_star.y) z.append(single_star.y) return x, y, z def plot_orbit(x, y): pyplot.figure(figsize=(10, 10)) plot(x, y) pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-t", dest="t_end", type="float", default=250, unit=units.Myr, help="end time [%unit]") result.add_option("-d", dest="dt_diag", type="float", default=10, unit=units.Myr, help="diagnostic timestep [%unit]") result.add_option("-P", dest="potential", default="MilkyWay", help="name of potential") result.add_option("-M", dest="mass", type="float", default=1.e+11, unit=units.MSun, help="mass of the galaxy [%unit]") result.add_option("-e", dest="eps", type="float", default=0.0, unit=units.parsec, help="softening of the potential [%unit]") result.add_option("-x", dest="x", type="float", default=8500, unit=units.parsec, help="x-position [%unit]") result.add_option("-y", dest="y", type="float", default=0, unit=units.parsec, help="y-position [%unit]") result.add_option("-z", dest="z", type="float", default=0, unit=units.parsec, help="z-position [%unit]") result.add_option("--vx", dest="vx", type="float", default=0, unit=units.km / units.s, help="x-velocity [%unit]") result.add_option("--vy", dest="vy", type="float", default=220, unit=units.km / units.s, help="y-velocity [%unit]") result.add_option("--vz", dest="vz", type="float", default=0, unit=units.km / units.s, help="z-velocity [%unit]") return result if __name__ == "__main__": o, arguments = new_option_parser().parse_args() t_end = o.t_end dt_diag = min(o.dt_diag, 0.1 * o.t_end) size_unit = units.parsec mass = 1.0 pos = [o.x, o.y, o.z] vel = [o.vx, o.vy, o.vz] single_star = new_single_star(mass, pos, vel) galaxy = MilkyWay_galaxy(o.potential, M=o.mass) x, y, z = evolve_particle_trajectory_in_potential( single_star, galaxy, dt_diag, t_end) plot_orbit(x, y)
6,325
36.431953
77
py
amuse
amuse-main/examples/simple/stellar_mass_loss.py
# -*- coding: ascii -*- """ Set an artificial mass loss rate at a specific point in the stellar evolution using MESA and calculate the effect this has on the stellar radius. """ from __future__ import print_function # import numpy from amuse.units import units from amuse.datamodel import Particle from amuse.support.console import set_printing_strategy from amuse.community.mesa.interface import MESA def print_report(star1, star2, mdot): report_string = ("mdot = {mdot}\n" " effective mdot = {eff_mdot}\n" " age: {star1.age} -> {star2.age}\n" " {d_age}\n" " radius: {star1.radius} -> {star2.radius}\n" " {d_radius}\n" " mass: {star1.mass} -> {star2.mass}\n" " {d_mass}\n" "-> rdot: {rdot}\n\n") with open("radius_mass_loss_output.dat", 'a+') as f: f.write(report_string.format( star1=star1, star2=star2, mdot=mdot, eff_mdot=(star2.mass - star1.mass) / (star2.age - star1.age), rdot=(star2.radius - star1.radius) / (star2.age - star1.age), d_age=star2.age - star1.age, d_radius=star2.radius - star1.radius, d_mass=star2.mass - star1.mass)) def evolve_star_and_apply_mass_loss(radius, mdot): print("Evolve to radius = ", radius, "and then apply mdot =", mdot) stev = MESA(redirection='none') # We have to switch off all wind mass loss for manual mass loss to work stev.parameters.AGB_wind_scheme = 0 stev.parameters.RGB_wind_scheme = 0 star = stev.particles.add_particle(Particle(mass=2 | units.MSun)) while star.radius < radius: star.evolve_one_step() print("evolved to:", star.age, "->", star.radius) star1 = star.copy() # High mass loss rates can only be calculated for small time steps star.time_step = 1. | units.yr star.mass_change = mdot print(star.mass_change) star.evolve_one_step() print_report(star1, star, mdot) if __name__ == "__main__": set_printing_strategy( "custom", preferred_units=[ units.RSun, units.MSun, units.Myr, units.MSun / units.yr, units.RSun / units.yr, ] ) evolve_star_and_apply_mass_loss( 39. | units.RSun, -1e-3 | units.MSun / units.yr)
2,442
30.727273
75
py
amuse
amuse-main/examples/simple/h2region.py
# -*- coding: ascii -*- """ Evolves the steady state solution of a star irridiating a H2 region. """ from __future__ import print_function # import numpy import os from matplotlib import pyplot from optparse import OptionParser from amuse.community.mocassin.interface import Mocassin, mocassin_rydberg_unit from amuse.units import units # from amuse.units import nbody_system # from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.datamodel import Particle from amuse.datamodel import Grid from amuse.io import write_set_to_file def make_grid( number_of_grid_cells, length, constant_hydrogen_density, inner_radius, outer_radius): grid = Grid.create([number_of_grid_cells] * 3, length.as_vector_with_length(3)) grid.radius = grid.position.lengths() grid.hydrogen_density = constant_hydrogen_density grid.hydrogen_density[grid.radius <= inner_radius] = 0 | units.cm ** -3 grid.hydrogen_density[grid.radius >= outer_radius] = 0 | units.cm ** -3 return grid def setup_abundancies(code): table = code.abundancies_table() for atom in list(table.keys()): table[atom] = 0.0 table['H'] = 1.0 table['He'] = 0.1 table['C'] = 2.2e-4 table['N'] = 4.e-5 table['O'] = 3.3e-4 table['Ne'] = 5.e-5 table['S'] = 9.e-6 def plot_temperature_line(radii, electron_temperatures): pyplot.figure(figsize=(8, 8)) pyplot.scatter( radii.value_in(1e17 * units.cm), electron_temperatures.value_in(units.K) ) pyplot.title('electron temperature') pyplot.xlabel('10^17 cm') pyplot.ylabel('K') pyplot.xlim(30, 100) pyplot.ylim(5500, 7500) pyplot.show() def main(number_of_grid_cells=15, min_convergence=20): inner_radius = 30.0e17 | units.cm outer_radius = 95.0e17 | units.cm hydrogen_density = 100 | units.cm ** -3 star = Particle() star.position = [0.0, 0.0, 0.0] | units.AU star.temperature = 20000 | units.K star.luminosity = 600.5 | 1e37 * units.erg * (units.s**-1) grid = make_grid( number_of_grid_cells=number_of_grid_cells, length=outer_radius, constant_hydrogen_density=hydrogen_density, inner_radius=inner_radius, outer_radius=outer_radius ) radiative_transfer = Mocassin(number_of_workers=2) # , debugger = "xterm") radiative_transfer.set_input_directory( radiative_transfer.get_default_input_directory()) radiative_transfer.set_mocassin_output_directory( radiative_transfer.output_directory + os.sep) radiative_transfer.initialize_code() radiative_transfer.set_symmetricXYZ(True) radiative_transfer.parameters.length_x = outer_radius radiative_transfer.parameters.length_y = outer_radius radiative_transfer.parameters.length_z = outer_radius radiative_transfer.parameters.mesh_size = [ number_of_grid_cells, number_of_grid_cells, number_of_grid_cells] setup_abundancies(radiative_transfer) radiative_transfer.parameters.initial_nebular_temperature = 6000.0 | units.K radiative_transfer.parameters.high_limit_of_the_frequency_mesh = 15 | mocassin_rydberg_unit radiative_transfer.parameters.low_limit_of_the_frequency_mesh = 1.001e-5 | mocassin_rydberg_unit radiative_transfer.parameters.total_number_of_photons = 10000000 radiative_transfer.parameters.total_number_of_points_in_frequency_mesh = 600 radiative_transfer.parameters.convergence_limit = 0.09 radiative_transfer.parameters.number_of_ionisation_stages = 6 radiative_transfer.commit_parameters() radiative_transfer.grid.hydrogen_density = grid.hydrogen_density radiative_transfer.commit_grid() radiative_transfer.particles.add_particle(star) radiative_transfer.commit_particles() max_number_of_photons = radiative_transfer.parameters.total_number_of_photons * 100 previous_percentage_converged = 0.0 for i in range(20): radiative_transfer.step() percentage_converged = radiative_transfer.get_percentage_converged() print( "percentage converged :", percentage_converged, ", step :", i, ", photons:", radiative_transfer.parameters.total_number_of_photons) if percentage_converged >= min_convergence: break if previous_percentage_converged > 5 and percentage_converged < 95: convergence_increase = ( percentage_converged - previous_percentage_converged ) / previous_percentage_converged if ( convergence_increase < 0.2 and radiative_transfer.parameters.total_number_of_photons < max_number_of_photons ): radiative_transfer.parameters.total_number_of_photons *= 2 previous_percentage_converged = percentage_converged grid.electron_temperature = radiative_transfer.grid.electron_temperature radius = grid.radius.flatten() electron_temperature = grid.electron_temperature.flatten() selection = electron_temperature > 0 | units.K plot_temperature_line(radius[selection], electron_temperature[selection]) write_set_to_file(grid, 'h2region.h5', 'amuse') def new_option_parser(): result = OptionParser() result.add_option( "-n", "--gridcells", default=13, dest="number_of_grid_cells", help="number of cells in each direction", type="int" ) result.add_option( "-c", "--min-convergence", default=60, dest="min_convergence", help="stop the iteratation when the solution is converged to the given percentage (in whole numbers between 10 and 100)", type="int") return result if __name__ == "__plot__": main(13, 30) if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
5,925
31.382514
129
py
amuse
amuse-main/examples/simple/hydro_star.py
# -*- coding: ascii -*- """ Converts a 1d stellar model into a 3d spherical gas model for a star """ from __future__ import print_function from amuse.units import units from amuse.community.evtwin.interface import EVtwin from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.plot import sph_particles_plot, native_plot from amuse.datamodel import Particle def create_particles(): star = Particle() star.mass = 3.0 | units.MSun stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) print("Evolving", star.mass, "star with", stellar_evolution.__class__.__name__, "up to", 100 | units.Myr) stellar_evolution.evolve_model(100 | units.Myr) print("Creating SPH particles from the (1D) stellar evolution model") sph_particles = convert_stellar_model_to_SPH( se_star, 1000 ).gas_particles stellar_evolution.stop() return sph_particles if __name__ == "__main__": sph_particles = create_particles() native_plot.figure(figsize=(6, 6), dpi=50) sph_particles_plot(sph_particles) native_plot.show()
1,131
28.025641
73
py
amuse
amuse-main/examples/simple/unstable_binary.py
# -*- coding: ascii -*- """ Evolves two stars dynamically (hermit, nbody code) each star will lose mass during the evolution (evtwin, stellar evolution code) We start with two stars, one 10.0 and one 1.0 solar mass star. These stars start orbiting with a stable kepler orbit. After 2 orbital periods the stars will begin to lose mass and the binary will become unstable. """ from __future__ import print_function from amuse.plot import xlabel, ylabel, plot from matplotlib import pyplot from math import pi from amuse.units.optparse import OptionParser from amuse.units import units from amuse.units import constants from amuse.units.nbody_system import nbody_to_si from amuse.community.evtwin.interface import EVtwin # from amuse.community.sse.interface import SSE from amuse.community.hermite.interface import Hermite from amuse.datamodel import Particles def set_up_initial_conditions(orbital_period, kinetic_to_potential_ratio): print("Setting up initial conditions") stars = Particles(2) stars.mass = [10.0, 1.0] | units.MSun stars.radius = 0 | units.RSun stars.position = [0.0, 0.0, 0.0] | units.AU stars.velocity = [0.0, 0.0, 0.0] | units.km / units.s print("Binary with masses: " + str(stars.mass) + ", and orbital period: ", orbital_period) semimajor_axis = ((constants.G * stars.total_mass() * (orbital_period / (2 * pi))**2.0)**(1.0 / 3.0)) separation = 2 * semimajor_axis * (1 - kinetic_to_potential_ratio) print("Initial separation:", separation.as_quantity_in(units.AU)) relative_velocity = ( (kinetic_to_potential_ratio / (1.0 - kinetic_to_potential_ratio)) * constants.G * stars.total_mass() / semimajor_axis ).sqrt() print("Initial relative velocity:", relative_velocity.as_quantity_in(units.km / units.s)) stars[0].x = separation stars[0].vy = relative_velocity stars.move_to_center() return stars def set_up_stellar_evolution_code(stars): stellar_evolution = EVtwin() stellar_evolution.initialize_code() # if you run with mesa, you can play with the wind efficiency # stellar_evolution.parameters.RGB_wind_scheme = 1 # stellar_evolution.parameters.reimers_wind_efficiency = 1.0e6 # # ridiculous, but instructive stellar_evolution.particles.add_particles(stars) return stellar_evolution def set_up_gravitational_dynamics_code(stars): convert_nbody = nbody_to_si(11.0 | units.MSun, 10.0 | units.AU) gravitational_dynamics = Hermite(convert_nbody) gravitational_dynamics.parameters.epsilon_squared = 0.0 | units.AU ** 2 view_on_the_primary = gravitational_dynamics.particles.add_particle( stars[0]) gravitational_dynamics.particles.add_particle(stars[1]) return gravitational_dynamics, view_on_the_primary def simulate_binary_evolution(binary, orbital_period, t_offset_stars, t_end): distance = [] | units.AU mass = [] | units.MSun time = [] | units.yr stellar_evolution = set_up_stellar_evolution_code(binary) gravitational_dynamics, primary = set_up_gravitational_dynamics_code( binary) from_se_to_gd = stellar_evolution.particles.new_channel_to( gravitational_dynamics.particles) current_time = 0.0 * t_end print("Evolving with stellar wind") while current_time < t_end: current_time += orbital_period / 10 gravitational_dynamics.evolve_model(current_time) stellar_evolution.evolve_model(current_time + t_offset_stars) from_se_to_gd.copy_attributes(['mass']) separation = ( gravitational_dynamics.particles[0].position - gravitational_dynamics.particles[1].position ).length() distance.append(separation) mass.append(primary.mass) time.append(current_time) print( "System evolved to time: ", current_time, ", primary mass:", primary.mass.as_quantity_in( units.MSun), ", separation:", separation.as_quantity_in(units.AU)) print("Evolution done") return distance, mass, time def orbit_plot(distance, mass, time): figure = pyplot.figure(figsize=(6, 10), dpi=100) subplot = figure.add_subplot(2, 1, 1) plot(time, distance) xlabel('t') ylabel('separation') pyplot.margins(0.05) subplot = figure.add_subplot(2, 1, 2) plot(time, ((mass - mass[0]) / mass[0]) * 100.0) xlabel('t') ylabel('mass') pyplot.margins(0.05) pyplot.show() def main( orbital_period=1000.0 | units.yr, kinetic_to_potential_ratio=0.8, periods=10, age=10 | units.Myr ): t_offset_stars = age t_end = periods * orbital_period binary = set_up_initial_conditions( orbital_period, kinetic_to_potential_ratio) distance, mass, time = simulate_binary_evolution( binary, orbital_period, t_offset_stars, t_end) orbit_plot(distance, mass, time) def new_option_parser(): result = OptionParser() result.add_option( "-o", "--orbitalperiod", default=1000 | units.yr, dest="orbital_period", help="initial orbital period of the binary (in years)", type="float", unit=units.yr ) result.add_option( "-k", "--kpratio", default=0.8, dest="kinetic_to_potential_ratio", help="kinetec to potential energy ratio, values less than 1.0 correspond to bound systems", type="float") result.add_option( "--periods", default=10, dest="periods", help="number of orbital periods to evolve the binary", type="int" ) result.add_option( "--age", default=10 | units.Myr, dest="age", help="initial age of the stars to start the simulation with", type="float", unit=units.Myr ) return result if __name__ == "__plot__": main(1000 | units.yr, 0.8, 10, 10 | units.Myr) if __name__ == "__main__": options, args = new_option_parser().parse_args() main(**options.__dict__)
6,092
31.935135
99
py
amuse
amuse-main/examples/simple/brunt.py
# -*- coding: ascii -*- # -*-noplot-*- from __future__ import print_function from matplotlib import pyplot from amuse.plot import semilogy, xlabel, ylabel from amuse.units import units from amuse.community.mesa.interface import MESA from amuse.datamodel import Particle def brunt_vaisala_frequency_squared_profile(mass, age): stellar_evolution = MESA() star = stellar_evolution.particles.add_particle(Particle(mass=mass)) star.evolve_for(age) radius_profile = star.get_radius_profile() brunt_profile = star.get_brunt_vaisala_frequency_squared_profile() stellar_evolution.stop() return radius_profile.as_quantity_in(units.RSun), brunt_profile def make_plot(radius_profile, brunt_profile, mass, age): figure = pyplot.figure() semilogy(radius_profile, -brunt_profile, 'g-', label=r'convective, $N^2$ < 0') semilogy(radius_profile, brunt_profile, 'r-', label=r'radiative, $N^2$ > 0') xlabel('Radius') ylabel(r'$\|N^2\|$') pyplot.title( 'Brunt-Vaisala frequency squared of a {0} star at {1}'.format(mass, age)) pyplot.legend(loc=3) pyplot.show() if __name__ == '__main__': mass = 1.0 | units.MSun age = 1.0 | units.Gyr radius_profile, brunt_profile = brunt_vaisala_frequency_squared_profile( mass, age) make_plot(radius_profile, brunt_profile, mass, age)
1,375
31.761905
81
py
amuse
amuse-main/examples/simple/supernova_in_binary_nbody.py
# -*- coding: ascii -*- from __future__ import print_function import numpy from amuse.units import constants, units, nbody_system from amuse.datamodel import Particles from amuse.community.hermite.interface import Hermite from amuse.ext.orbital_elements import orbital_elements_from_binary def get_relative_velocity(total_mass, semimajor_axis, ecc): return ( constants.G * total_mass * ((1.0 + ecc) / (1.0 - ecc)) / semimajor_axis).sqrt() def make_circular_binary(M, m, a): masses = [M.value_in(units.MSun), m.value_in(units.MSun)] | units.MSun orbital_period = ( 4 * numpy.pi**2 * a**3 / (constants.G * masses.sum()) ).sqrt().as_quantity_in(units.day) print(" Initializing inner binary") print(" Orbital period inner binary:", orbital_period) stars = Particles(2) stars.mass = masses stars.position = [0.0, 0.0, 0.0] | units.AU stars.velocity = [0.0, 0.0, 0.0] | units.km / units.s stars[0].x = a stars[0].vy = get_relative_velocity(stars.total_mass(), a, 0.0) stars.move_to_center() return stars # from Hills 1983 (Eq. 1) 1983ApJ...267..322H def post_supernova_semimajor_axis(M0, m0, M1, m1, a0, r0): dM = M0 - M1 a = 0.5 * (M0 + m0 - dM) / (0.5 * (M0 + m0) - (a0 / r0) * dM) return a # from Hills 1983 (Eq. 6) 1983ApJ...267..322H def post_supernova_eccentricity(M0, m0, M1, m1, a0, r0): dM = M0 - M1 e0 = 0.0 e = numpy.sqrt(1 - (1 - e0**2) * ((1 - (2 * a0 / r0) * \ (dM / (M0 + m0)))) / ((1 - dM / (m0 + m0))**2)) return e def supernova_in_binary_nbody(M0, m0, a0, tsn): stars = make_circular_binary(M0, m0, a0) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary( stars, G=constants.G) print("Initial binary: a=", a.in_( units.AU), "e=", e, "M=", stars[0].mass, "and m=", stars[1].mass) converter = nbody_system.nbody_to_si(M + m, a) gravity = Hermite(converter) gravity.particles.add_particles(stars) print("Integrate binary to t=", tsn.in_(units.day)) gravity.evolve_model(tsn) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary( stars, G=constants.G) print("Pre supernova orbit: a=", a.in_(units.AU), "e=", e) stars[0].mass *= 0.1 print("Reduce stellar mass to: M=", stars[0].mass, "and m=", stars[1].mass) v_kick = (0, 0, 0) | units.kms stars[0].velocity += v_kick gravity.evolve_model(2 * tsn) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary( stars, G=constants.G) print("Post supernova orbit: a=", a.in_(units.AU), "e=", e) r0 = a a_ana = post_supernova_semimajor_axis( M0, m0, stars[0].mass, stars[1].mass, a, r0) e_ana = post_supernova_eccentricity( M0, m0, stars[0].mass, stars[1].mass, a, r0) print( "Analytic solution to post orbit orbital parameters: a=", a_ana, "e=", e_ana, ) gravity.stop() if __name__ in ('__main__'): M = 10 | units.MSun m = 10 | units.MSun a = 1 | units.AU orbital_period = (4 * numpy.pi**2 * a**3 / (constants.G * (M + m))).sqrt() tsn = 10 * orbital_period supernova_in_binary_nbody(M, m, a, tsn)
3,242
32.091837
79
py
amuse
amuse-main/examples/simple/salpeter.py
# -*- coding: ascii -*- """ Generates a cluster using a plummer model with a salpeter Initial Mass Function. Compares the generated IMF against the expected line. """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.units import units from amuse.units import nbody_system from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution def new_cluster(number_of_stars=1000): masses = new_salpeter_mass_distribution( number_of_stars, mass_min=0.1 | units.MSun, mass_max=125.0 | units.MSun, alpha=-2.35 ) nbody_converter = nbody_system.nbody_to_si(masses.sum(), 1 | units.parsec) particles = new_plummer_model(number_of_stars, nbody_converter) particles.mass = masses particles.move_to_center() return particles def plot_particles_and_mass_distribution(particles): figure = pyplot.figure(figsize=(12, 6)) subplot = figure.add_subplot(1, 2, 1) subplot.scatter( particles.x.value_in(units.parsec), particles.y.value_in(units.parsec), s=particles.mass.value_in(units.MSun), # * len(particles), edgecolors='red', facecolors='red' ) subplot.set_xlim(-4, 4) subplot.set_ylim(-4, 4) subplot.set_xlabel('x (parsec)') subplot.set_ylabel('y (parsec)') subplot = figure.add_subplot(1, 2, 2) masses = particles.mass.value_in(units.MSun) bins = 10**numpy.linspace(-1, 2, 100) number_of_particles, bin_edges = numpy.histogram(masses, bins=bins) bin_sizes = bin_edges[1:] - bin_edges[:-1] y = number_of_particles / bin_sizes x = (bin_edges[1:] + bin_edges[:-1]) / 2.0 y = y[number_of_particles > 10.0] x = x[number_of_particles > 10.0] subplot.scatter(x, y) c = ((0.1**-1.35) - (125.0**-1.35)) / 1.35 subplot.plot(x, len(particles) / c * (x**-2.35)) subplot.set_xscale('log') subplot.set_yscale('log') subplot.set_xlabel('M [Msun]') subplot.set_ylabel('N') pyplot.show() if __name__ == "__main__": particles = new_cluster(20000) plot_particles_and_mass_distribution(particles)
2,175
26.544304
78
py
amuse
amuse-main/examples/simple/massloss.py
# -*- coding: ascii -*- """ Evolves the sun and earth where the sun will lose mass every 220th step. """ from __future__ import print_function import numpy from amuse.community.hermite.interface import Hermite # from amuse.community.sse.interface import SSE from amuse import datamodel from amuse.units import units from amuse.units import nbody_system from amuse.units.quantities import VectorQuantity from amuse.plot import ( plot, native_plot) def simulate_massloss(time): return units.MSun( 0.5 * (1.0 + 1.0 / (1.0 + numpy.exp((time.value_in(time.unit) - 70.0) / 15.))) ) if __name__ == "__main__": convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = datamodel.Particles(2) sun = particles[0] sun.mass = 1.0 | units.MSun sun.position = [0.0, 0.0, 0.0] | units.AU sun.velocity = [0.0, 0.0, 0.0] | units.AU / units.yr sun.radius = 1.0 | units.RSun earth = particles[1] earth.mass = 5.9736e24 | units.kg earth.radius = 6371.0 | units.km earth.position = [0.0, 1.0, 0.0] | units.AU earth.velocity = [2.0 * numpy.pi, -0.0001, 0.0] | units.AU / units.yr instance = Hermite(convert_nbody) instance.particles.add_particles(particles) channelp = instance.particles.new_channel_to(particles) start = 0 | units.yr end = 150 | units.yr step = 10 | units.day timerange = VectorQuantity.arange(start, end, step) masses = [] | units.MSun for i, time in enumerate(timerange): instance.evolve_model(time) channelp.copy() particles.savepoint(time) if (i % 220 == 0): instance.particles[0].mass = simulate_massloss(time) masses.append(instance.particles[0].mass) instance.stop() particle = particles[1] t, pos = particle.get_timeline_of_attribute_as_vector("position") distances = pos.lengths().as_quantity_in(units.AU) plot(timerange, distances, timerange, masses) native_plot.show()
2,003
27.225352
86
py
amuse
amuse-main/examples/simple/stellar_structure.py
# -*- coding: ascii -*- """ Make plots of the stellar structure of a star of given mass and age """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.plot import semilogy, xlabel, ylabel from amuse.units import units from amuse.community.evtwin.interface import EVtwin from amuse.datamodel import Particle def structure_from_star(mass, age): stellar_evolution = EVtwin() star = stellar_evolution.particles.add_particle(Particle(mass=mass)) star.evolve_for(age) radius_profile = star.get_radius_profile() density_profile = star.get_density_profile() if hasattr(star, "get_mass_profile"): mass_profile = star.get_mass_profile() * star.mass else: radii_cubed = radius_profile**3 radii_cubed.prepend(0 | units.m**3) mass_profile = ( (4.0 / 3.0 * numpy.pi) * density_profile * (radii_cubed[1:] - radii_cubed[:-1]) ) print("Derived mass profile from density and radius.") return dict( radius=radius_profile.as_quantity_in(units.RSun), density=density_profile, mass=mass_profile, temperature=star.get_temperature_profile(), pressure=star.get_pressure_profile(), composition=star.get_chemical_abundance_profiles(), species_names=star.get_names_of_species() ) def temperature_density_plot(data, mass, age): figure = pyplot.figure(figsize=(8, 10)) pyplot.subplot(2, 1, 1) ax = pyplot.gca() plotT = semilogy(data["radius"], data["temperature"], 'r-', label=r'$T(r)$') xlabel('Radius') ylabel('Temperature') ax.twinx() plotrho = semilogy(data["radius"], data["density"], 'g-', label=r'$\rho(r)$') plots = plotT + plotrho labels = [one_plot.get_label() for one_plot in plots] ax.legend(plots, labels, loc=3) ylabel('Density') pyplot.subplot(2, 1, 2) semilogy( data["radius"], data["composition"][0], label=data["species_names"][0]) semilogy( data["radius"], data["composition"][1], label=data["species_names"][1]) semilogy( data["radius"], data["composition"][2], label=data["species_names"][2]) semilogy( data["radius"], data["composition"][3], label=data["species_names"][3]) semilogy( data["radius"], data["composition"][4], label=data["species_names"][4]) pyplot.ylim(0.0, 1.0) xlabel('Radius') ylabel('Mass fraction') pyplot.legend() pyplot.suptitle('Structure of a {0} star at {1}'.format(mass, age)) pyplot.show() if __name__ == "__main__": mass = 1.0 | units.MSun age = 5.0 | units.Gyr data = structure_from_star(mass, age) temperature_density_plot(data, mass, age)
2,813
30.617978
72
py
amuse
amuse-main/examples/simple/boss_bodenheimer_test.py
# -*- coding: ascii -*- """ Fragmentation in a rotating protostar -- Boss & Bodenheimer (1979, BB79, http://adsabs.harvard.edu/abs/1979ApJ...234..289B) Calculate the collapse of an isothermal cloud with SPH code fi. The cloud is initially spherical, with an uniform density with a nonaxisymmetric perturbation of mode = 2 and with 50% amplitude. It rotates as a rigid body with a constant angular velocity around the z-axis. The collapse leads to formation of a binary system. arguments: N -- number of particles Mcloud -- mass of the cloud Rcloud -- radius of the cloud omega -- angular velocity of the cloud density_perturb -- amplitude of the density perturbation Plot 10 snapshots of the simulations (bb79_rho_*.png) -- log10(rho [amu/cm**3]). """ from __future__ import print_function import numpy # import string # import os # import sys from matplotlib import pyplot from matplotlib import rc from amuse.units import nbody_system from amuse.units import units from amuse.ext.boss_bodenheimer import bb79_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from amuse.community.fi.interface import Fi rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) def get_grid_posvel(N=100, grid_size=1 | units.parsec): """ gives x,y(,z,vx,vy,vz) Cartesian coordinate grid (where z=0, vx=vy=vz=0) -- for plotting SPH quantities in the xy plane -- N points on each axis; size of the grid 'grid_size' for x and y """ cell_center_positions_1d = numpy.linspace(-0.5, 0.5, N) x, y = numpy.meshgrid(cell_center_positions_1d, cell_center_positions_1d) x = x.flatten() y = y.flatten() x *= grid_size y *= grid_size z = x * 0.0 vx = 0.0 * x / (1.0 | units.s) vy = 0.0 * x / (1.0 | units.s) vz = 0.0 * x / (1.0 | units.s) return x, y, z, vx, vy, vz def plot_sph_rho(sph, N=100, grid_size=1 | units.parsec, plot_name="cloud_plot_rho.png", plot_title="SPH density"): """ plots the log10(SPH density) in the xy plane input: sph -- set of sph particles N -- number of grid points (in x and y) grid_size -- size of the grid (x and y) plot_name -- name for the output figure plot_title -- title of the plot """ # getting the grid x, y, z, vx, vy, vz = get_grid_posvel(N, grid_size) # getting density from the SPH data rho, rhovx, rhovy, rhovz, rhoe = sph.get_hydro_state_at_point( x, y, z, vx, vy, vz) rho = rho.reshape((N, N)) # plotting extent = (grid_size * (-0.5, 0.5, -0.5, 0.5)).value_in(units.parsec) pyplot.figure(figsize=(5, 5.2)) pyplot.imshow(numpy.log10(rho.value_in(units.amu / units.cm**3)), extent=extent) pyplot.title(plot_title) # pyplot.xlabel('x [pc]') # pyplot.ylabel('y [pc]') frame = pyplot.gca() frame.axes.get_xaxis().set_visible(False) frame.axes.get_yaxis().set_visible(False) cbar = pyplot.colorbar() cbar.set_label(r'$\log (\rho [\mathrm{amu}/\mathrm{cm}^3])$') pyplot.tight_layout() pyplot.savefig(plot_name) # pyplot.show() def bb79_cloud_evolve(N=50000, Mcloud=1. | units.MSun, Rcloud=3.2e16 | units.cm, omega=1.56e-12 | units.rad / units.s, density_perturb=0.5, t_total=8.3e11 | units.s): # mean density of the cloud rho_uni = Mcloud / (4. / 3. * numpy.pi * Rcloud**3) print(" ** mean density = ", rho_uni.in_(units.g / units.cm**3)) # free fall time of the cloud t_ff = numpy.sqrt(3. * numpy.pi / (32. * units.constants.G * rho_uni)) print(" ** free-fall time = ", t_ff.in_(units.yr)) conv = nbody_system.nbody_to_si(Mcloud, Rcloud) sph = Fi(conv) # the initial conditions of BB79 parts_bb79 = bb79_cloud(targetN=N, omega=omega, rho_perturb=0.5, ethep_ratio=0.25, convert_nbody=conv, base_grid=body_centered_grid_unit_cube).result sph.gas_particles.add_particles(parts_bb79) sph.parameters.use_hydro_flag = True sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.gamma = 1 sph.parameters.verbosity = 0 sph.parameters.timestep = 0.1 * t_ff print( "**evolving to time: (end time = ~ {0:.3f} t_ff)".format(t_total / t_ff)) # setting snapshots to be plotted nplot = 10 if nplot > 1: plot_timestep = t_total / (nplot - 1) else: plot_timestep = t_total # evolution of the cloud for i in range(nplot): ttarget = i * plot_timestep t_tff = ttarget / t_ff sph.evolve_model(ttarget) plot_i = "bb79_rho_{0:03d}.png".format(i) tt_tff = "{0:.3f}".format(t_tff) title_i = "$%s\,t_{\mathrm{ff}}$" % (tt_tff) print("\t {0:.3f} t_ff -> {1}".format(t_tff, plot_i)) plot_sph_rho(sph, N=300, grid_size=0.025 | units.parsec, plot_name=plot_i, plot_title=title_i) sph.stop() if __name__ == "__main__": bb79_cloud_evolve(N=50000, Mcloud=1. | units.MSun, Rcloud=3.2e16 | units.cm, omega=1.56e-12 | units.rad / units.s, density_perturb=0.5, t_total=8.3e11 | units.s) # ~1.5*t_ff
5,467
30.976608
81
py
amuse
amuse-main/examples/simple/hrdiagram.py
# -*- coding: ascii -*- """ Generates a Hertzsprung-Russell diagram for a single star """ from __future__ import print_function # import sys # import numpy from matplotlib import pyplot from amuse.plot import loglog, xlabel, ylabel from amuse.units import units from amuse.community.sse.interface import SSE from amuse import datamodel # from amuse.rfi.core import is_mpd_running end_time = 2 | units.Gyr stellar_mass = 2.0 | units.MSun def simulate_evolution_tracks(): stellar_evolution = SSE() star = datamodel.Particle() star.mass = stellar_mass star = stellar_evolution.particles.add_particle(star) luminosity_at_time = [] | units.LSun temperature_at_time = [] | units.K print("Evolving a star with mass:", stellar_mass) is_evolving = True while is_evolving and star.age < end_time: luminosity_at_time.append(star.luminosity) temperature_at_time.append(star.temperature) previous_age = star.age # if we do not specify an end_time in the evolve_model function # a stellar evolution code will evolve to the next # 'natural' timestep, this will ensure all interesting physics # is seen in the hr diagram stellar_evolution.evolve_model() is_evolving = (star.age != previous_age) stellar_evolution.stop() return temperature_at_time, luminosity_at_time def plot_track(temperature_at_time, luminosity_at_time): pyplot.figure(figsize=(8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperature_at_time, luminosity_at_time) xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.ylim(.1, 1.e4) pyplot.show() if __name__ == "__main__": temperatures, luminosities = simulate_evolution_tracks() plot_track(temperatures, luminosities)
1,860
27.630769
71
py
amuse
amuse-main/examples/simple/evolve_binary.py
# -*- coding: ascii -*- """ Evolves a stellar binary and reports the mass of each star during the evolution. Shows the type of each star as they change. """ from __future__ import print_function from amuse.community.seba.interface import SeBa from amuse.datamodel import Particles from amuse.units import constants, units import numpy from matplotlib import pyplot def evolve_binary(mass_of_star1, mass_of_star2, orbital_period, eccentricity): code = SeBa() stars = Particles(2) stars[0].mass = mass_of_star1 stars[1].mass = mass_of_star2 mu = stars.mass.sum() * constants.G semi_major_axis = ( ((orbital_period / (2.0 * numpy.pi))**2) * mu)**(1.0 / 3.0) binaries = Particles(1) binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = eccentricity binary.child1 = stars[0] binary.child2 = stars[1] # we add the single stars first, as the binaries will refer to these code.particles.add_particles(stars) code.binaries.add_particles(binaries) from_seba_to_model = code.particles.new_channel_to(stars) from_seba_to_model.copy() from_seba_to_model_binaries = code.binaries.new_channel_to(binaries) from_seba_to_model_binaries.copy() previous_type_child1 = binary.child1.stellar_type previous_type_child2 = binary.child2.stellar_type results = [] current_time = 0 | units.Myr while current_time < (1000 | units.Myr): code.update_time_steps() # The next line appears a bit weird, but saves time for this simple # test. deltat = max(1.0 * code.binaries[0].time_step, 0.1 | units.Myr) current_time = current_time + deltat code.evolve_model(current_time) from_seba_to_model.copy() from_seba_to_model_binaries.copy() if not binary.child1.stellar_type == previous_type_child1: print(binary.age, "Child 1, change of stellar type", previous_type_child1, ' -> ', binary.child1.stellar_type) previous_type_child1 = binary.child1.stellar_type if not binary.child2.stellar_type == previous_type_child2: print(binary.age, "Child 2, change of stellar type", previous_type_child2, ' -> ', binary.child2.stellar_type) previous_type_child2 = binary.child2.stellar_type results.append( (binary.age, binary.child1.mass, binary.child1.stellar_type, binary.child2.mass, binary.child2.stellar_type)) code.stop() return results def plot_masses(table): time = [] mass_child1 = [] mass_child2 = [] for age, mass1, type1, mass2, type2 in table: time.append(age.value_in(units.Myr)) mass_child1.append(mass1.value_in(units.MSun)) mass_child2.append(mass2.value_in(units.MSun)) figure = pyplot.figure(figsize=(8, 6)) plot = figure.add_subplot(1, 1, 1) plot.plot(time, mass_child1) plot.plot(time, mass_child2) plot.set_xlabel('Time') plot.set_ylabel('Mass') pyplot.show() if __name__ == "__main__": table = evolve_binary( 3.0 | units.MSun, 0.3 | units.MSun, 200 | units.day, 0.5 ) plot_masses(table)
3,237
30.134615
78
py
amuse
amuse-main/examples/simple/protoplanetarydisk.py
# -*- coding: ascii -*- """ Creates a protoplanetary disk around a sun-like star """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.community.fi.interface import Fi from amuse.units import units from amuse.units import nbody_system from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.datamodel import Particles def make_map(sph, N=100, L=1): x, y = numpy.indices((N + 1, N + 1)) x = L * (x.flatten() - N / 2.) / N y = L * (y.flatten() - N / 2.) / N z = x * 0. vx = 0. * x vy = 0. * x vz = 0. * x x = units.AU(x) y = units.AU(y) z = units.AU(z) vx = units.kms(vx) vy = units.kms(vy) vz = units.kms(vz) rho, rhovx, rhovy, rhovz, rhoe = sph.get_hydro_state_at_point( x, y, z, vx, vy, vz) rho = rho.reshape((N + 1, N + 1)) return numpy.transpose(rho) if __name__ == "__main__": N = 20000 tend = 1. | units.yr Mstar = 1. | units.MSun convert = nbody_system.nbody_to_si(Mstar, 1. | units.AU) proto = ProtoPlanetaryDisk( N, convert_nbody=convert, densitypower=1.5, Rmin=4, Rmax=20, q_out=1.) gas = proto.result gas.h_smooth = 0.06 | units.AU sun = Particles(1) sun.mass = Mstar sun.radius = 2. | units.AU sun.x = 0. | units.AU sun.y = 0. | units.AU sun.z = 0. | units.AU sun.vx = 0. | units.kms sun.vy = 0. | units.kms sun.vz = 0. | units.kms sph = Fi(convert) sph.parameters.use_hydro_flag = True sph.parameters.radiation_flag = False sph.parameters.self_gravity_flag = True sph.parameters.gamma = 1. sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.timestep = 0.125 | units.yr sph.gas_particles.add_particles(gas) sph.particles.add_particles(sun) sph.evolve_model(tend) L = 50 rho = make_map(sph, N=200, L=L) sph.stop() pyplot.figure(figsize=(8, 8)) pyplot.imshow(numpy.log10(1.e-5 + rho.value_in(units.amu / units.cm**3)), extent=[-L / 2, L / 2, -L / 2, L / 2], vmin=10, vmax=15) pyplot.title(tend) pyplot.xlabel('AU') pyplot.savefig('test.png') pyplot.show()
2,223
23.711111
78
py
amuse
amuse-main/examples/simple/lagrange_points.py
# -*- coding: ascii -*- """ Make a contour plot of the effective potential of the Sun-Earth system (left) and a system with a 10000 times more massive Earth with the Lagrangian points visible. """ from __future__ import print_function # import numpy from matplotlib import pyplot from amuse.plot import xlabel, ylabel, effective_iso_potential_plot from amuse.units import units, constants, nbody_system from amuse.community.hermite.interface import Hermite from amuse.datamodel import Particles def new_sun_earth_system(): particles = Particles(2) particles.mass = [1, 3.0024584e-6] | units.MSun particles.position = [[0, 0, 0], [1.0, 0, 0]] | units.AU particles.velocity = [0, 0, 0] | units.km / units.s particles[1].vy = ( constants.G * particles.total_mass() / particles[1].x).sqrt() return particles def setup_gravity_code(): converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) gravity = Hermite(converter) gravity.parameters.epsilon_squared = 1e-6 | units.RSun**2 gravity.particles.add_particles(new_sun_earth_system()) return gravity def make_effective_iso_potential_plot(gravity_code): omega = (constants.G * gravity_code.particles.total_mass() / (1.0 | units.AU**3)).sqrt() center_of_mass = gravity_code.particles.center_of_mass()[:2] figure = pyplot.figure(figsize=(9, 8)) current_axes = pyplot.subplot(2, 2, 1) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, fraction_screen_filled=0.7) xlabel('x') ylabel('y') current_axes = pyplot.subplot(2, 2, 3) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, xlim=[0.9, 1.1] | units.AU, ylim=[-0.1, 0.1] | units.AU, number_of_contours=20) xlabel('x') ylabel('y') gravity_code.particles[1].mass *= 10000 omega = (constants.G * gravity_code.particles.total_mass() / (1.0 | units.AU**3)).sqrt() center_of_mass = gravity_code.particles.center_of_mass()[:2] current_axes = pyplot.subplot(2, 2, 2) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, number_of_contours=20, fraction_screen_filled=0.7) xlabel('x') ylabel('y') current_axes = pyplot.subplot(2, 2, 4) current_axes.set_aspect("equal", adjustable="box") effective_iso_potential_plot(gravity_code, omega, center_of_rotation=center_of_mass, xlim=[0.6, 1.4] | units.AU, ylim=[-0.4, 0.4] | units.AU, number_of_contours=20, fraction_screen_filled=0.9) xlabel('x') ylabel('y') pyplot.show() if __name__ == "__main__": gravity = setup_gravity_code() make_effective_iso_potential_plot(gravity) gravity.stop()
3,488
36.923913
77
py
amuse
amuse-main/examples/simple/stellar_mean_mass.py
# -*- coding: ascii -*- """ Calculates the mean mass of a stellar popultion as a function of time. This routine was used to measure the <m> of a star cluster in order to incorporate <m>(t) and d<m>/dt in a parametrized cluster evolution code. """ from __future__ import print_function # import sys # import numpy # from matplotlib import pyplot # from amuse.plot import loglog, xlabel, ylabel from amuse.community.sse.interface import SSE from amuse.units import units from amuse.datamodel import Particles from amuse.ic.salpeter import new_salpeter_mass_distribution from optparse import OptionParser if __name__ == "__main__": result = OptionParser() result.add_option("-t", dest="t_end", type="float", default=12000, help="End time for calculation in Myr. [12000 Myr]") result.add_option("-d", dest="dt", type="float", default=10, help="output time step in Myr. [10 Myr]") result.add_option("-N", dest="N", type="int", default=10, help="number of stars to calculate <m>. [10]") result.add_option("-m", dest="Mmin", type="float", default=0.15, help="Minimal mass of the IMF in MSun. [0.15MSun]") result.add_option("-M", dest="Mmax", type="float", default=100, help="Maximal mass of the IMF in MSun. [100MSun]") result.add_option("-x", dest="x_imf", type="float", default=-2.35, help="Slope of the IMF. [-2.35]") result.add_option("-v", dest="verbose", action="store_true", default=False, help="verbose output [True]") o, arguments = result.parse_args() t_end = o.t_end | units.Myr dt = o.dt | units.Myr stellar_evolution = SSE() stellar_evolution.commit_parameters() stars = Particles(o.N) Mmin = o.Mmin | units.MSun Mmax = o.Mmax | units.MSun if o.verbose: print("#Selected parameters: ") print("#\tN=", o.N) print("#\tIMF=", o.Mmin, "MSun", o.Mmax, "MSun", o.x_imf) print("#\t t [Myr] \t <m> [MSun] \t\t d<m>/dt [MSun/Myr]") stars.mass = new_salpeter_mass_distribution( o.N, mass_min=Mmin, mass_max=Mmax, alpha=o.x_imf) stars = stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() t = 0 | units.Myr mm = stars.mass.sum() / len(stars) while t < t_end: mm_last = mm t += dt stellar_evolution.evolve_model(t) mm = stars.mass.sum() / len(stars) dmm_dt = (mm_last - mm) / dt if o.verbose: print("t = ", t, "<m>=", mm.as_quantity_in(units.MSun), " d<m>/dt = ", dmm_dt.as_quantity_in(units.MSun / units.Myr)) else: print("\t", t, "\t", mm.as_quantity_in(units.MSun), " \t ", dmm_dt.as_quantity_in(units.MSun / units.Myr))
2,863
38.232877
79
py
amuse
amuse-main/examples/simple/binary_population_synthesis.py
# -*- coding: ascii -*- """ Generates a grid of binaries with different, primary mass, mass ratio and separation and evolves these over time. """ from __future__ import print_function from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.community.seba.interface import SeBa # from amuse.community.bse.interface import BSE from matplotlib import pyplot import numpy # import time USE_VECTOR_OPERATIONS = True def multidimensional_meshgrid(*arrays): """ Utitility function to create a multidimensional grid based on a list of arrays. Each array defines a range in one dimension. """ reversed_quantities = tuple(reversed(arrays)) lengths = [len(x) for x in reversed_quantities] dim = len(reversed_quantities) size = 1 for length in lengths: size *= length result = [] for i, quantity in enumerate(reversed_quantities): shape = numpy.ones(dim, dtype=numpy.int) shape[i] = lengths[i] if quantities.is_quantity(quantity): array = quantity.value_in(quantity.unit) else: array = quantity array = array.reshape(shape) for j, length in enumerate(lengths): if j != i: array = array.repeat(length, axis=j) if quantities.is_quantity(quantity): result.append(quantity.unit.new_quantity(array)) else: result.append(array) return tuple(result[::-1]) def create_binary( stars, binaries, primary_mass, mass_ratio, separation, eccentricity): """ creates a single binary, the constituent stars will be accumulated in the stars partice set, the binary will be added to the binaries particle set. """ primary_star = datamodel.Particle() primary_star.mass = primary_mass # we add the particle to the stars set # and we get a reference to the particle in the stars set # back # we want to use that star in constructing the # binary, so that the binaries all refer to # the stars in the "stars set" primary_star = stars.add_particle(primary_star) secondary_star = datamodel.Particle() secondary_star.mass = primary_mass * mass_ratio secondary_star = stars.add_particle(secondary_star) binary = datamodel.Particle() binary.eccentricity = eccentricity binary.semi_major_axis = separation binary.child1 = primary_star binary.child2 = secondary_star binaries.add_particle(binary) def generate_initial_population_grid( min_mass, max_mass, number_of_mass_bins, min_ratio, max_ratio, number_of_ratio_bins, min_separation, max_separation, number_of_separation_bins, min_eccentricity, max_eccentricity, number_of_eccentricity_bins ): """ creates a set of binaries and a set of stars, the grid will be divided in equal parts amongst all dimensions (primary mass, ratio and separation), the total number of binaries will be the product of all bins. """ # quantities.linspace takes care of the units, # but is otherwhise equal to numpy.arange primary_masses = quantities.linspace( min_mass, max_mass, number_of_mass_bins) mass_ratios = quantities.linspace( min_ratio, max_ratio, number_of_ratio_bins) separations = quantities.linspace( min_separation, max_separation, number_of_separation_bins) eccentricities = quantities.linspace( min_eccentricity, max_eccentricity, number_of_eccentricity_bins) # We can create the binaries individualy (with nested for loops to # go through each dimension) or at once with vector operations. # As vector operations are handled by numpy (in C) these are # much faster (default in this script). if USE_VECTOR_OPERATIONS is True: grid = multidimensional_meshgrid( primary_masses, mass_ratios, separations, eccentricities) all_primary_masses = grid[0].flatten() all_mass_ratios = grid[1].flatten() all_separations = grid[2].flatten() all_eccentricities = grid[3].flatten() primary_stars = datamodel.Particles(mass=all_primary_masses) secondary_stars = datamodel.Particles( mass=all_primary_masses * all_mass_ratios) stars = datamodel.Particles() primary_stars = stars.add_particles(primary_stars) secondary_stars = stars.add_particles(secondary_stars) binaries = datamodel.Particles( semi_major_axis=all_separations, eccentricity=all_eccentricities ) binaries.child1 = list(primary_stars) binaries.child2 = list(secondary_stars) else: for primary_mass in primary_masses: for mass_ratio in mass_ratios: for separation in separations: for eccentricity in eccentricities: create_binary( stars, binaries, primary_mass, mass_ratio, separation, eccentricity ) return binaries, stars def evolve_population(binaries, stars, end_time, time_step): code = SeBa() # add the stars first, as the binaries will # refer to them code.particles.add_particles(stars) code.binaries.add_particles(binaries) channel_from_code_to_model_for_binaries = code.binaries.new_channel_to( binaries) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) # we evolve in steps of timestep, just to get some feedback print("start evolving...") time = 0.0 * end_time while time < end_time: time += time_step code.evolve_model(time) print("evolved to time: ", time.as_quantity_in(units.Myr)) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy() def make_hr_diagram(binaries): pyplot.figure(figsize=(8, 8)) pyplot.title('Binary population', fontsize=12) separation = binaries.semi_major_axis.value_in(units.RSun) eccentricity = binaries.eccentricity pyplot.hexbin( separation, eccentricity, gridsize=40, bins='log', extent=(0, 100, 0.0, 0.9) ) pyplot.xlabel('semi major axis (AU)') pyplot.ylabel('eccentricity') pyplot.show() if __name__ == "__main__": print("generating a binary population...") binaries, stars = generate_initial_population_grid( 0.5 | units.MSun, 1.5 | units.MSun, 3, # mass range 0.9, 0.9, 1, # mass ratios range 10 | units.RSun, 100 | units.RSun, 120, # semi major axis range 0.0, 1.0, 120 # eccentricity range ) print("generated a population of", len(binaries), "binaries") evolve_population(binaries, stars, 1 | units.Gyr, 250 | units.Myr) make_hr_diagram(binaries)
6,973
31.896226
79
py
amuse
amuse-main/examples/simple/molecular_cloud_chemistry.py
# -*- coding: ascii -*- """ Evolves a molecular cloud with chemical evolution The dynamics is evolved in the sph code Fi, chemistry with Krome, assuming an isothermal cloud (hence passive chemical evolution). Initial condition is a smooth spherical cloud with random velocities as in Bonnell et al. (2003) """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.units import units, constants, nbody_system from amuse.community.fi.interface import Fi from amuse.community.krome.interface import Krome from amuse.ext.molecular_cloud import molecular_cloud gamma = 1.4 meanmwt = 1.35 | units.amu ionization_rate=2.e-17 | units.s**-1 def get_n_T_xi(density, u): number_density=density/meanmwt temperature=((gamma - 1) * meanmwt * u / constants.kB) ionrate=ionization_rate*numpy.ones_like(density) return (number_density, temperature, ionrate) def update_chem(sph_parts, chem_parts): channel = sph_parts.new_channel_to(chem_parts) channel.transform(["number_density", "temperature", "ionrate"], get_n_T_xi, ["density", "u"]) def evolve_sph_with_chemistry(sph, chem, tend): sph.evolve_model(tend) update_chem(sph.particles, chem.particles) chem.evolve_model(tend) def run_mc(N=5000, Mcloud=10000. | units.MSun, Rcloud=1. | units.parsec): timestep = 0.005 | units.Myr end_time = 0.12 | units.Myr conv = nbody_system.nbody_to_si(Mcloud, Rcloud) parts = molecular_cloud(targetN=N, convert_nbody=conv, ethep_ratio=0.05, ekep_ratio=0.5).result rho_cloud = Mcloud / (4 / 3. * numpy.pi * Rcloud**3) tff = 1 / (4 * numpy.pi * constants.G * rho_cloud)**0.5 parts.density = rho_cloud update_chem(parts, parts) print("Tcloud:", parts.temperature.max().in_(units.K)) print("cloud n_H:", parts.number_density.max().in_(units.cm**-3)) print("freefall time:", tff.in_(units.Myr)) sph = Fi(conv) chem = Krome(redirection="none") sph.parameters.self_gravity_flag = True sph.parameters.use_hydro_flag = True sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.gamma = 1 sph.parameters.verbosity = 0 sph.parameters.timestep = timestep / 2 sph.gas_particles.add_particles(parts) chem.particles.add_particles(parts) tnow = sph.model_time f = pyplot.figure() pyplot.ion() pyplot.show() i = 0 while i < (end_time / timestep + 0.5): evolve_sph_with_chemistry(sph, chem, i * timestep) tnow = sph.model_time print("done with step:", i, tnow.in_(units.Myr)) i += 1 n = (sph.particles.density / meanmwt).value_in(units.cm**-3) fh2 = chem.particles.abundances[:, chem.species["H2"]] co = chem.particles.abundances[:, chem.species["CO"]] pyplot.clf() pyplot.loglog(n, fh2, 'r.') pyplot.loglog(n, co, 'g.') pyplot.xlim(1.e3, 1.e6) pyplot.ylim(1.e-6, 1) pyplot.xlabel("density (cm**-3)") pyplot.ylabel("H_2,CO abundance") f.canvas.flush_events() print("done. press key to exit") input() if __name__ == "__main__": run_mc(N=1000, Mcloud=2000. | units.MSun, Rcloud=.5 | units.parsec)
3,266
29.53271
97
py
amuse
amuse-main/examples/simple/isochrone.py
# -*- coding: ascii -*- """ Generates an isochrone of a cluster of stars in a Hertzsprung-Russell diagram """ from __future__ import print_function from matplotlib import pyplot from amuse.units import units from amuse.datamodel import Particles from amuse.ic.brokenimf import new_scalo_mass_distribution from amuse.ext.particles_with_color import new_particles_with_blackbody_color from amuse.community.seba.interface import SeBa def simulate_stellar_evolution(particles, endtime): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) from_code_to_model = stellar_evolution.particles.new_channel_to(particles) print("Evolving {0} stars using {1} up to {2}.".format( len(particles), stellar_evolution.__class__.__name__, endtime)) stellar_evolution.evolve_model(endtime) from_code_to_model.copy_all_attributes() stellar_evolution.stop() def plot_isochrone(particles): particles = new_particles_with_blackbody_color(particles) pyplot.figure(figsize=(7, 8)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) pyplot.scatter( particles.temperature.value_in( units.K), particles.luminosity.value_in( units.LSun), s=particles.radius.maximum( 0.1 | units.RSun).value_in( units.RSun) * 100, c=particles.color, edgecolors="none", ) pyplot.xlabel('Effective Temperature (K)') pyplot.ylabel('Luminosity (L$_{\odot}$)') pyplot.xscale('log') pyplot.yscale('log') pyplot.xlim(20e3, 2e3) pyplot.ylim(1.0e-3, 1.0e3) pyplot.gca().set_axis_bgcolor('#808080') pyplot.show() if __name__ == "__main__": particles = Particles(mass=new_scalo_mass_distribution(4000)) simulate_stellar_evolution(particles, 0.5 | units.Gyr) plot_isochrone(particles)
1,830
35.62
78
py
amuse
amuse-main/examples/simple/kelvin_helmholtz.py
# -*- coding: ascii -*- """ Runs the Kelvin-Helmholtz Instability problem in two dimensions with Athena. """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.community.athena.interface import Athena from amuse.units.generic_unit_system import ( length, mass, speed, time, density ) from amuse.datamodel import Grid GAMMA = 1.4 DIMENSIONS_OF_MESH = (200, 200, 1) PERTUBATION_AMPLITUDE = 0.1 | speed def new_instance_of_hydro_code(number_of_workers=1): result = Athena(number_of_workers=number_of_workers) result.parameters.gamma = GAMMA result.parameters.courant_number = 0.8 return result def set_parameters(instance): instance.parameters.mesh_size = DIMENSIONS_OF_MESH instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") def new_grid(): grid = Grid.create(DIMENSIONS_OF_MESH, [1, 1, 1] | length) clear_grid(grid) return grid def clear_grid(grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid(grid): vx = 0.5 | speed p = 2.5 | (mass / (length * time**2)) halfway = DIMENSIONS_OF_MESH[0] / 2 - 1 outerregion = numpy.logical_or( grid.y <= 0.25 | length, grid.y >= 0.75 | length) innerregion = numpy.logical_and( grid.y > 0.25 | length, grid.y < 0.75 | length) grid[outerregion].rho = 1 | density grid[outerregion].rhovx = vx * grid[outerregion].rho grid[innerregion].rho = 2.0 | density grid[innerregion].rhovx = -vx * grid[innerregion].rho grid.energy = p / (GAMMA - 1) def pertubate_grid(grid): grid.rhovx += grid.rho * PERTUBATION_AMPLITUDE * \ (numpy.random.rand(*grid.shape) - 0.5) grid.rhovy += grid.rho * PERTUBATION_AMPLITUDE * \ (numpy.random.rand(*grid.shape) - 0.5) grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho def simulate_kelvin_helmholtz_instability(end_time): instance = new_instance_of_hydro_code() set_parameters(instance) print("setup grid") for x in instance.itergrids(): inmem = x.copy() clear_grid(inmem) initialize_grid(inmem) pertubate_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print("start evolve") dt = end_time / 10.0 t = dt while t < end_time: instance.evolve_model(t) print("time : ", t) t += dt print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def plot_grid(grid): rho = grid.rho[..., 0].value_in(density) figure = pyplot.figure(figsize=(6, 6)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('kelvin_helmholtz.png') pyplot.show() if __name__ == "__main__": grids = simulate_kelvin_helmholtz_instability(1.0 | time) plot_grid(grids[0])
3,526
25.125926
76
py
amuse
amuse-main/examples/simple/collision.py
""" Evolves a cluster until a collision is detected between two stars in the cluster. The stars in the cluster are distributed using a plummer sphere, the masses are set according to a Salpeter initial mass function. By default the radii of all stars are equal and very large. All units are in nbody units. """ import numpy from matplotlib import pyplot from amuse.units import nbody_system from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution_nbody from amuse.community.hermite.interface import Hermite def new_cluster(number_of_stars=1000, radius=None): """ Return a new cluster of stars with the given radii and a salpeter mass distribution. """ if radius is None: radius = (0.5 / number_of_stars) | nbody_system.length particles = new_plummer_model(number_of_stars) particles.mass = new_salpeter_mass_distribution_nbody(number_of_stars) particles.radius = radius particles.move_to_center() return particles def plot_particles_and_highlight_collision(particles, particles1, particles2): """ Plot the stars and on top of these plot the particles involved in the collision. """ figure = pyplot.figure() subplot = figure.add_subplot(1, 1, 1) subplot.scatter( particles.x.value_in(nbody_system.length), particles.y.value_in(nbody_system.length), s=(2 * subplot.bbox.width * particles.radius.value_in(nbody_system.length)) ** 2, edgecolors='none', facecolors='red', marker='o', ) subplot.scatter( particles1.x.value_in(nbody_system.length), particles1.y.value_in(nbody_system.length), s=2 * (2 * subplot.bbox.width * particles1.radius.value_in(nbody_system.length)) ** 2, edgecolors='none', facecolors='black', marker='o', ) subplot.scatter( particles2.x.value_in(nbody_system.length), particles2.y.value_in(nbody_system.length), s=2 * (2 * subplot.bbox.width * particles2.radius.value_in(nbody_system.length)) ** 2, edgecolors='none', facecolors='black', marker='o', ) subplot.set_xlim(-1, 1) subplot.set_ylim(-1, 1) subplot.set_xlabel('x (nbody length)') subplot.set_ylabel('y (nbody length)') pyplot.show() if __name__ == "__main__": numpy.random.seed(1212) particles = new_cluster(128) code = Hermite() code.particles.add_particles(particles) stopping_condition = code.stopping_conditions.collision_detection stopping_condition.enable() code.evolve_model(4 | nbody_system.time) if not stopping_condition.is_set(): raise Exception( "No stopping collision detected in the given timeframe.") plot_particles_and_highlight_collision( particles, stopping_condition.particles(0), stopping_condition.particles(1))
2,959
27.737864
78
py
amuse
amuse-main/examples/simple/gas_in_cluster.py
# -*- coding: ascii -*- """ Simultaniously evolves gas and stars in a cluster. The stars and gas particles evolve in their respective codes (Hermite and Gadget2) The force of the gas particles on the star particles is calculated by a seperate code (BHTree) The force of the star particles on the gas particles is calculated by the star code (Hermite) The bridge works in S.I. units, but for this example all times and energies are reported in nbody units. """ from __future__ import print_function from amuse.couple import bridge from amuse.community.bhtree.interface import BHTree from amuse.community.hermite.interface import Hermite from amuse.community.gadget2.interface import Gadget2 from amuse.ic import plummer from amuse.ic import gasplummer from amuse.units import units # from amuse.units import constants # from amuse.units import quantities from amuse.units import nbody_system import numpy from matplotlib import pyplot class BridgeStarAndGasPlummerCode(object): """ Calculates a cluster with stars and gas, using a fixed set of codes (Hermite for stars, Gadget2 for gas and BHTree for gas to star interaction). """ def __init__( self, nstars=10, ngas=None, total_mass=1000 | units.MSun, gas_fraction=0.9, rscale=1.0 | units.parsec, star_smoothing_fraction=0.001, gas_smoothing_fraction=0.05, seed=None, interaction_timestep=0.01 | nbody_system.time, diagnostic_timestep=0.1 | nbody_system.time ): if seed is not None: numpy.random.seed(seed) if ngas is None: ngas = nstars * 10 self.ngas = ngas self.nstars = nstars self.total_mass = total_mass self.gas_fraction = gas_fraction self.star_fraction = 1.0 - self.gas_fraction self.rscale = rscale self.star_epsilon = star_smoothing_fraction * self.rscale self.gas_epsilon = gas_smoothing_fraction * self.rscale self.star_mass = self.star_fraction * self.total_mass self.gas_mass = self.gas_fraction * self.total_mass self.converter = nbody_system.nbody_to_si(self.total_mass, self.rscale) self.interaction_timestep_in_si = self.converter.to_si( interaction_timestep) self.diagnostic_timestep_in_si = self.converter.to_si( diagnostic_timestep) self.time = 0.0 * self.interaction_timestep_in_si self.times = [] | nbody_system.time self.energy_at_time = [] | nbody_system.energy self.coreradius_at_time = [] | self.rscale.unit def setup(self): self.create_codes() self.initialize_data() self.create_bridge() self.code = self.bridge_system self.print_log() self.store_values() def create_codes(self): self.star_code = self.new_star_code_hermite() self.gas_code = self.new_gas_code_gadget() def new_code_to_calculate_gravity_of_gas_particles(): result = BHTree(self.converter) return result calculate_gravity_code = bridge.CalculateFieldForCodes( # the code that calculates the acceleration field new_code_to_calculate_gravity_of_gas_particles, # the codes to calculate the acceleration field of input_codes=[self.gas_code] ) self.gas_to_star_codes = [calculate_gravity_code] self.star_to_gas_codes = [self.star_code] def initialize_data(self): self.particles = self.new_particles_cluster() self.gas_particles = self.new_gas_cluster() self.star_code.particles.add_particles(self.particles) self.gas_code.gas_particles.add_particles(self.gas_particles) self.channel_from_code_to_memory_for_stars = \ self.star_code.particles.new_channel_to(self.particles) self.channel_from_code_to_memory_for_gas = \ self.gas_code.gas_particles.new_channel_to(self.gas_particles) def create_bridge(self): self.bridge_system = bridge.Bridge( timestep=self.interaction_timestep_in_si, use_threading=False ) self.bridge_system.add_system( self.gas_code, self.star_to_gas_codes ) self.bridge_system.add_system( self.star_code, self.gas_to_star_codes ) def stop(self): self.star_code.stop() self.gas_code.stop() def new_gas_code_gadget(self): result = Gadget2(self.converter) return result def new_star_code_hermite(self): result = Hermite(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 return result def new_particles_cluster(self): particles = plummer.new_plummer_model( self.nstars, convert_nbody=self.converter) particles.radius = self.star_epsilon particles.mass = (1.0 / self.nstars) * self.star_mass return particles def new_gas_cluster(self): particles = gasplummer.new_plummer_gas_model( self.ngas, convert_nbody=self.converter) particles.h_smooth = self.gas_epsilon particles.mass = (1.0 / self.ngas) * self.gas_mass return particles def evolve_model(self, time_end): time_end_in_si = self.converter.to_si(time_end) while self.time < time_end_in_si: self.time += self.diagnostic_timestep_in_si self.code.evolve_model(self.time) print("evolved to time:", self.converter.to_nbody(self.code.time)) self.store_values() self.channel_from_code_to_memory_for_stars.copy() self.channel_from_code_to_memory_for_gas.copy() self.print_log() def print_log(self): time = self.converter.to_nbody(self.time).value_in(nbody_system.time) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) print("Time :", time) print("Energy :", energy) print("Virial radius :", coreradius) def store_values(self): time = self.converter.to_nbody(self.time) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody(sum_energy) coreradius = self.star_code.particles.virial_radius() self.times.append(time) self.energy_at_time.append(energy) self.coreradius_at_time.append(coreradius) if __name__ == "__main__": code = BridgeStarAndGasPlummerCode( nstars=100, diagnostic_timestep=0.5 | nbody_system.time ) code.setup() code.evolve_model(4.0 | nbody_system.time) figure = pyplot.figure(figsize=(5, 10)) subplot = figure.add_subplot(2, 1, 1) subplot.plot( code.times.value_in(nbody_system.time), code.coreradius_at_time.value_in(units.parsec) ) subplot.set_title('code radius') subplot.set_xlabel('time (nbody)') subplot.set_ylabel('radius (parsec)') subplot = figure.add_subplot(2, 1, 2) subplot.plot( code.times.value_in( nbody_system.time), (code.energy_at_time - code.energy_at_time[0]) / code.energy_at_time[0], 'g') subplot.set_title('energy error') subplot.set_xlabel('time (nbody)') subplot.set_ylabel('(E-E0)/E') pyplot.show()
7,737
31.107884
79
py
amuse
amuse-main/examples/simple/evolve_orbit_in_potential.py
# -*- coding: ascii -*- """ Evolve the orbital evolution in the galactic center potential with different N-body codes. All codes use default settings and are integrated using Bridge. Since it is only a single particle being evolved, and the potential is handled by bridge (externally) there should not be any difference between the codes. """ from __future__ import print_function import numpy from itertools import cycle from amuse.units import units, quantities, nbody_system from amuse.units.optparse import OptionParser from amuse.datamodel import Particle, Particles from amuse.support.exceptions import AmuseException from amuse.support.console import set_printing_strategy from matplotlib import pyplot from amuse import plot as aplot from amuse.ext import static_potentials from amuse.couple.bridge import Bridge from amuse.community.ph4.interface import ph4 from amuse.community.huayno.interface import Huayno from amuse.community.adaptb.interface import Adaptb from amuse.community.bhtree.interface import BHTree from amuse.community.tupan.interface import Tupan codelist = {"huayno": Huayno, "ph4": ph4, "adaptb": Adaptb, "bhtree": BHTree, "tupan": Tupan} coordinate_correction = [-8.08, 0, 6.68] | units.parsec def subplot(potential, orbits, codes, fit_orbit, labels): hor, vert = labels X = numpy.linspace(-160, 160, 100) | units.parsec Y = numpy.linspace(-160, 160, 100) | units.parsec X, Y = quantities.meshgrid(X, Y) if labels == 'xy': pot_args = [X, Y, 0 | units.parsec] fit_horizontal = fit_orbit[0] fit_vertical = fit_orbit[1] elif labels == 'xz': pot_args = [X, 0 | units.parsec, Y] fit_horizontal = fit_orbit[0] fit_vertical = fit_orbit[2] elif labels == 'yz': pot_args = [0 | units.parsec, X, Y] fit_horizontal = fit_orbit[1] fit_vertical = fit_orbit[2] phi = potential.get_potential_at_point(None, *pot_args) aplot.imshow_color_plot(X, Y, phi, cmap="Blues") del aplot.UnitlessArgs.arg_units[2] aplot.scatter(0 | units.parsec, 0 | units.parsec, c='black') aplot.plot(fit_horizontal, fit_vertical, c="green", ls="--", label="Kruijssen et al. 2014") colors = cycle(['red', 'black', 'yellow', 'grey', 'green']) for full_orbit, code in zip(orbits, codes): horizontal = full_orbit.x if hor == 'x' else full_orbit.y vertical = full_orbit.y if vert == 'y' else full_orbit.z color = next(colors) aplot.plot(horizontal, vertical, c=color, label=code) aplot.scatter(horizontal[-1], vertical[-1], c=color, edgecolor=color) pyplot.axis('equal') aplot.xlim([-150, 150] | units.parsec) aplot.ylim([-150, 150] | units.parsec) aplot.xlabel(hor) aplot.ylabel(vert) def plot_orbit(potential, orbits, codes, fit_orbit, filename): pyplot.figure(figsize=(10, 10)) pyplot.subplot(221) subplot(potential, orbits, codes, fit_orbit, "xy") pyplot.subplot(222) subplot(potential, orbits, codes, fit_orbit, "xz") pyplot.subplot(223) subplot(potential, orbits, codes, fit_orbit, "yz") pyplot.legend(loc='center left', bbox_to_anchor=(1.2, 0.5)) if filename is None: pyplot.show() else: pyplot.savefig(filename) def load_fit_orbit(): (t, x, y, z, R, vx, vy, vz, vorb, l, b, vlos, mu_l, mub, mu_x, mu_y) = numpy.loadtxt("orbit_KDL15.dat", unpack=True) fit_orbit = [] | units.parsec for var in (x, y, z): fit_orbit.append(var | units.parsec) return fit_orbit def setup_system(): """ Galacitic center potential and Arches cluster position from Kruijssen 2014 """ potential = static_potentials.Galactic_Center_Potential_Kruijssen() cluster = Particle() # At time 2.05 in KDL15 cluster.position = [-17.55767, -53.26560, -9.39921] | units.parsec cluster.velocity = [-187.68008, 80.45276, 33.96556] | units.kms cluster.position += coordinate_correction return potential, cluster def setup_bridge(potential, cluster, current_age, timestep, orbit, code): converter = nbody_system.nbody_to_si( current_age, cluster.position.length()) gravity = codelist[code](converter) cluster.mass = 0 | units.MSun gravity.particles.add_particle(cluster) bridge = Bridge(timestep=timestep, use_threading=False) bridge.add_system(gravity, (potential,)) gravity_to_orbit = gravity.particles.new_channel_to(orbit.particles) return bridge, gravity, gravity_to_orbit def evolve_bridged_orbit_in_potential(potential, cluster, code, timestep, current_age): orbit = static_potentials.Position_In_Potential(potential, cluster) bridge, gravity, gravity_to_orbit = setup_bridge( potential, cluster, current_age, timestep, orbit, code) print(current_age, "->", orbit.particle.position) # Evolving backward gravity.particles.velocity *= -1 while bridge.model_time < current_age - (timestep / 2.): # print bridge.model_time, "-", gravity.particles.position[0] bridge.evolve_model(bridge.model_time + timestep) gravity_to_orbit.copy() gravity.particles.velocity *= -1 gravity.model_time = 0 | units.Myr bridge.time = 0 | units.Myr cluster = gravity.particles[0] orbit.particle = cluster bridge, gravity, gravity_to_orbit = setup_bridge( potential, cluster, current_age, timestep, orbit, code) print(bridge.model_time, "->", orbit.particle.position) # Evolving forward full_orbit = Particles() while bridge.model_time < current_age - (timestep / 2.): full_orbit.add_particle(orbit.particle.copy()) bridge.evolve_model(bridge.model_time + timestep) gravity_to_orbit.copy() full_orbit.add_particle(orbit.particle.copy()) print(bridge.model_time, "->", orbit.particle.position) full_orbit.position -= coordinate_correction return full_orbit def evolve_orbit_and_plot(codes, filename, parameters): potential, cluster = setup_system() orbits = [] for code in codes: print("evolving with", code) if code in codelist: full_orbit = evolve_bridged_orbit_in_potential( potential, cluster.copy(), code, **parameters) else: raise AmuseException("Unknow code: {}".format(code)) orbits.append(full_orbit) print() fit_orbit = load_fit_orbit() plot_orbit(potential, orbits, codes, fit_orbit, filename) def parse_arguments(): parser = OptionParser() parser.add_option("-t", dest="timestep", type="float", unit=units.Myr, default=0.1, help="The timestep of the integrator [%default %unit].") parser.add_option("-a", dest="current_age", type="float", unit=units.Myr, default=3.5, help="The current age of the cluster [%default %unit].") parser.add_option("-c", dest="codes", action="append", type="string", help="The code to evolve the particle (can be used" "multiple times). Available codes: {}." .format(list(codelist.keys()))) parser.add_option("-f", dest="filename", type="string", default=None, help="Save the plot in a file with 'name'" "[show matplotlib if not given].") options, args = parser.parse_args() codes = options.codes or ["huayno"] filename = options.filename parameters = options.__dict__ del parameters['codes'] del parameters['filename'] return codes, filename, parameters if __name__ == "__main__": set_printing_strategy("custom", preferred_units=[units.MSun, units.parsec, units.Myr, units.kms]) codes, filename, parameters = parse_arguments() evolve_orbit_and_plot(codes, filename, parameters)
8,013
33.692641
78
py
amuse
amuse-main/examples/simple/plot_with_units.py
# -*- coding: ascii -*- """ Creates a number of plots using the AMUSE unit aware plot functions. """ from __future__ import print_function from amuse.units import units, quantities from amuse.plot import ( native_plot, plot, scatter, xlabel, ylabel, hist ) import numpy as np if __name__ == "__main__": # latex_support() x = np.pi / 20.0 * (range(-10, 10) | units.m) y1 = units.MSun.new_quantity(np.sin(x.number)) y2 = units.MSun.new_quantity(x.number) native_plot.subplot(2, 2, 1) plot(x, y2, label='model') scatter(x, y1, label='data') xlabel('x') ylabel('mass [$M_\odot$]') # overrides auto unit! native_plot.legend(loc=2) x = list(range(50)) | units.Myr y1 = quantities.new_quantity( np.sin(np.arange(0, 1.5, 0.03)), 1e50 * units.erg) y2 = -(1e43 | units.J) - y1 native_plot.subplot(2, 2, 2) plot(x, y1, label='$E_\mathrm{kin}$') plot(x, y2, label='$E_\mathrm{pot}$') xlabel('t') ylabel('E') native_plot.legend() x = list(range(7)) | units.day y1 = [0, 4, 2, 3, 2, 5, 1] y2 = [3, 0, 2, 2, 3, 0, 4] native_plot.subplot(2, 2, 3) plot(x, y1, 'ks', label='coffee') plot(x, y2, 'yo', label='tea') xlabel('time') ylabel('consumption / day') native_plot.legend() y1 = units.N.new_quantity(np.random.normal(0.0, 1.0, 100)) x = units.N.new_quantity(np.arange(-3, 3, 0.1)) y2 = np.exp(-np.arange(-3, 3, 0.1)**2) / np.sqrt(np.pi) native_plot.subplot(2, 2, 4) plot(x, y2, 'y--', label='model') hist(y1, bins=12, range=(-3, 3), normed=True, label='data') xlabel('force') ylabel('pdf') native_plot.legend() native_plot.show()
1,688
28.12069
68
py
amuse
amuse-main/examples/simple/galactic_center.py
# -*- coding: ascii -*- """ Evolves a cluster in the potention of the galactic center Uses the bridge integrator to couple different codes. In this example a cluster is evolved circling the galactic center, represented by a static potential. """ from __future__ import print_function # import numpy from amuse.units import units from amuse.units import constants from amuse.units import nbody_system from amuse.ext.bridge import bridge # from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.fi.interface import Fi # from amuse.community.gadget2.interface import Gadget2 from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model class GalacticCenterGravityCode(object): """ Implements a code simulating the galactic center. As the center itself does not evolve we only need to define the 'get_gravity_at_point' and 'get_potential_at_point'. Note that both functions get arrays of points. """ def __init__( self, R=1000. | units.parsec, M=1.6e10 | units.MSun, alpha=1.2): self.R = R self.M = M self.alpha = alpha def get_gravity_at_point(self, eps, x, y, z): r2 = x**2 + y**2 + z**2 r = r2**0.5 m = self.M * (r / self.R)**self.alpha fr = constants.G * m / r2 ax = -fr * x / r ay = -fr * y / r az = -fr * z / r return ax, ay, az def get_potential_at_point(self, eps, x, y, z): r2 = x**2 + y**2 + z**2 r = r2**0.5 c = constants.G * self.M / self.R**self.alpha phi = c / (self.alpha - 1) * \ (r**(self.alpha - 1) - self.R**(self.alpha - 1)) return phi def vcirc(self, r): m = self.M * (r / self.R)**self.alpha vc = (constants.G * m / r)**0.5 return vc def king_model_cluster(interface, N=1024, W0=3, Mcluster=4.e4 | units.MSun, Rcluster=.7 | units.parsec, parameters=[]): """ helper function to setup an nbody king model cluster (returns code with particles) """ converter = nbody_system.nbody_to_si(Mcluster, Rcluster) parts = new_king_model(N, W0, convert_nbody=converter) parts.radius = 0.0 | units.parsec nb = interface(converter) for name, value in parameters: setattr(nb.parameters, name, value) nb.particles.add_particles(parts) return nb def shift_sys(system, dx, dy, dz, dvx, dvy, dvz): """ helper function to shift system """ parts = system.particles.copy() parts.x = parts.x + dx parts.y = parts.y + dy parts.z = parts.z + dz parts.vx = parts.vx + dvx parts.vy = parts.vy + dvy parts.vz = parts.vz + dvz channel = parts.new_channel_to(system.particles) channel.copy_attributes(["x", "y", "z", "vx", "vy", "vz"]) # parts.copy_values_of_state_attributes_to(system.particles) if __name__ == "__main__": # parameter setup: N = 1024 W0 = 3 Rinit = 50. | units.parsec timestep = 0.01 | units.Myr Mcluster = 4.e4 | units.MSun Rcluster = 0.7 | units.parsec # make cluster and Galactic center cluster = king_model_cluster( Fi, N, W0, Mcluster, Rcluster, parameters=[ ("epsilon_squared", (0.01 | units.parsec)**2), ("periodic_box_size", 200 | units.parsec), ("timestep", timestep / 4) ] ) center = GalacticCenterGravityCode() # shift the cluster to an orbit around GC # (note the systems share the same coordinate frame, although units may # differ) vcirc = center.vcirc(Rinit) shift_sys(cluster, Rinit, 0 | units.parsec, 0. | units.parsec, 0 | units.kms, 0.8 * vcirc, 0 | units.kms) # setup bridge; cluster is evolved under influence of GC sys = bridge(verbose=False) sys.add_system(cluster, (center,), False) # evolve and make plots times = units.Myr([0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4]) f = pyplot.figure(figsize=(8, 16)) for i, t in enumerate(times): sys.evolve_model(t, timestep=timestep) x = sys.particles.x.value_in(units.parsec) y = sys.particles.y.value_in(units.parsec) subplot = f.add_subplot(4, 2, i + 1) subplot.plot(x, y, 'r .') subplot.plot([0.], [0.], 'b +') subplot.set_xlim(-60, 60) subplot.set_ylim(-60, 60) subplot.set_title(t) if i == 7: subplot.set_xlabel('parsec') cluster.stop() pyplot.show() # pyplot.savefig('test.eps')
4,519
28.933775
79
py
amuse
amuse-main/examples/simple/molecular_cloud.py
# -*- coding: ascii -*- """ Evolves a molecular cloud with explictly split gravtiy evolution The gas is evolved in a sph code, and it's gravity is determined by a tree code. Initial condition is a smooth spherical cloud with random velocities as in Bonnell et al. (2003) """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.units import nbody_system from amuse.units import units from amuse.community.fi.interface import Fi from amuse.community.bhtree.interface import BHTree from amuse.ext.molecular_cloud import molecular_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from amuse.couple import bridge def make_map(sph, N=100, grid_size=1 | units.parsec): cell_center_positions_1d = numpy.linspace(-0.5, 0.5, N) x, y = numpy.meshgrid(cell_center_positions_1d, cell_center_positions_1d) x = x.flatten() y = y.flatten() x *= grid_size y *= grid_size z = x * 0.0 vx = 0.0 * x / (1.0 | units.s) vy = 0.0 * x / (1.0 | units.s) vz = 0.0 * x / (1.0 | units.s) rho, rhovx, rhovy, rhovz, rhoe = sph.get_hydro_state_at_point( x, y, z, vx, vy, vz) rho = rho.reshape((N, N)) return rho def run_mc(N=5000, Mcloud=10000. | units.MSun, Rcloud=1. | units.parsec): conv = nbody_system.nbody_to_si(Mcloud, Rcloud) interaction_timestep = 0.01 | units.Myr time_end = 0.36 | units.Myr parts = molecular_cloud( targetN=N, convert_nbody=conv, base_grid=body_centered_grid_unit_cube).result sph = Fi(conv) # need to turn off self gravity, the bridge will calculate this sph.parameters.self_gravity_flag = False # some typical Fi flags (just for reference, most are default values) sph.parameters.use_hydro_flag = True sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.gamma = 1 sph.parameters.verbosity = 0 # setting the hydro timestep is important # the sph code will take 2 timesteps every interaction timestep sph.parameters.timestep = interaction_timestep / 2 sph.gas_particles.add_particles(parts) def new_code_to_calculate_gravity_of_gas_particles(): result = BHTree(conv) return result calculate_gravity_code = bridge.CalculateFieldForCodes( # the code that calculates the acceleration field new_code_to_calculate_gravity_of_gas_particles, # the codes to calculate the acceleration field of input_codes=[sph] ) bridged_system = bridge.Bridge() bridged_system.timestep = interaction_timestep bridged_system.add_system( # the code to move the particles of sph, # the codes that provide the acceleration field [calculate_gravity_code] ) fig = pyplot.figure(figsize=(12, 12)) ncolumn = 2 nrow = 2 nplot = ncolumn * nrow grid_size = 3 | units.parsec extent = (grid_size * (-0.5, 0.5, -0.5, 0.5)).value_in(units.parsec) if nplot > 1: plot_timestep = time_end / (nplot - 1) else: plot_timestep = time_end for i in range(nplot): ttarget = i * plot_timestep print("evolving to time:", ttarget.as_quantity_in(units.Myr)) bridged_system.evolve_model(ttarget) rho = make_map(sph, N=200, grid_size=grid_size) subplot = fig.add_subplot(ncolumn, nrow, i + 1) subplot.imshow( numpy.log10(1.e-5 + rho.value_in(units.amu / units.cm**3)), extent=extent, vmin=1, vmax=5 ) subplot.set_title(ttarget.as_quantity_in(units.Myr)) sph.stop() pyplot.show() if __name__ == "__main__": run_mc(10000, Mcloud=1000. | units.MSun, Rcloud=1. | units.parsec)
3,786
27.261194
77
py
amuse
amuse-main/examples/simple/save_and_load_particles.py
# -*- coding: ascii -*- """ Saves and loads a set of particles. The 'write_set_to_file' and 'read_set_from_file' functionso can hadle files in a variety of formats. """ from __future__ import print_function # from amuse.units import nbody_system from amuse.ic.plummer import new_plummer_model from amuse.plot import plot, native_plot # the imports needed to read and write a set from amuse.io import write_set_to_file from amuse.io import read_set_from_file import os.path if __name__ == "__main__": if os.path.exists('plummer128.hdf'): os.remove('plummer128.hdf') # generate a particle set plummer = new_plummer_model(128) # write the set to file 'testfile' # the third argument is the file format, 'amuse' is an hdf5 based format # that saves all information. Other formats # available are e.g. csv, txt, gadget, starlab write_set_to_file(plummer, 'plummer128.hdf', 'amuse') # reading back the file # we close the file, causing all data to be copied to memory # instead of being read from an open file particles = read_set_from_file('plummer128.hdf', 'amuse', close_file=True) # plotting plot(particles.x, particles.y, 'r.') native_plot.xlim(-5, 5) native_plot.ylim(-5, 5) native_plot.show()
1,277
30.170732
78
py
amuse
amuse-main/examples/simple/pythagorean.py
# -*- coding: ascii -*- """ Calculates the Pythagorean 3-body problem using different values for the smoothing length in the n-body code. """ from __future__ import print_function # import numpy # import time # from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.hermite.interface import Hermite # from amuse.community.huayno.interface import Huayno # from amuse.community.bhtree.interface import BHTree from amuse.units import nbody_system from amuse.units.quantities import AdaptingVectorQuantity from matplotlib import pyplot from amuse.datamodel import Particles def new_particles(): particles = Particles(3) particles.mass = [3., 4., 5.] | nbody_system.mass particles.position = [ [1, 3, 0], [-2, -1, 0], [1, -1, 0], ] | nbody_system.length particles.velocity = [0., 0., 0.] | nbody_system.speed particles.radius = 0 | nbody_system.length return particles def run_pyth(interface, tend=100, dt=0.125, parameters=[]): code = interface() for name, value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(new_particles()) code.commit_particles() x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() t = 0. | nbody_system.time while(t < tend - dt / 2): t = t + dt code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) code.stop() return x, y if __name__ == "__main__": codes_to_run = [('Hermite0, $\eta=0.03$', Hermite, [("dt_param", 0.03)]), ('Hermite0, $\eta=0.01$', Hermite, [("dt_param", 0.01)]), ('Hermite0, $\eta=0.003$', Hermite, [("dt_param", 0.003)]), ('Hermite0, $\eta=0.001$', Hermite, [("dt_param", 0.001)])] N = (len(codes_to_run) - 1) / 2 + 1 f = pyplot.figure(figsize=(8, 4 * N)) for i, (label, interface, parameters) in enumerate(codes_to_run): x, y = run_pyth(interface, tend=100 | nbody_system.time, dt=0.0625 | nbody_system.time, parameters=parameters) x = x.value_in(nbody_system.length) y = y.value_in(nbody_system.length) subplot = f.add_subplot(N, 2, i + 1) subplot.plot(x[:, 0], y[:, 0], 'r') subplot.plot(x[:, 1], y[:, 1], 'b') subplot.plot(x[:, 2], y[:, 2], 'g') subplot.set_title(label) subplot.set_xlim(-8, 8) subplot.set_ylim(-6, 6) pyplot.show()
2,491
30.15
79
py
amuse
amuse-main/examples/simple/__init__.py
0
0
0
py
amuse
amuse-main/examples/simple/grid_potential.py
# -*- coding: ascii -*- from __future__ import print_function from amuse.units import units, nbody_system from amuse.datamodel import Particle from amuse.community.athena.interface import Athena from amuse.community.hermite.interface import Hermite from matplotlib import pyplot def hydro_grid_in_potential_well(mass=1 | units.MSun, length=100 | units.AU): converter = nbody_system.nbody_to_si(mass, length) # calculate density in field based on solar wind # gives a very low number molar_mass_hydrogen_proton = 1 | units.g / units.mol density_hydrogen_in_stellar_wind = 10 | 1 / units.cm**3 particles_per_mol = 6.022e23 | 1 / units.mol density_hydrogen_in_stellar_wind_in_moles = ( density_hydrogen_in_stellar_wind / particles_per_mol ) density_gas = 100 * ( density_hydrogen_in_stellar_wind_in_moles * molar_mass_hydrogen_proton ).as_quantity_in(units.MSun / units.AU**3) # override with higher number for plotting density_gas = 1e-3 | units.MSun / units.AU**3 instance = Athena(converter) instance.initialize_code() instance.parameters.nx = 50 instance.parameters.ny = 50 instance.parameters.nz = 1 instance.parameters.length_x = length instance.parameters.length_y = length instance.parameters.length_z = length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("outflow", "outflow") # instance.stopping_conditions.number_of_steps_detection.enable() instance.set_has_external_gravitational_potential(1) instance.commit_parameters() grid_in_memory = instance.grid.copy() grid_in_memory.rho = density_gas pressure = 1 | units.Pa grid_in_memory.energy = pressure / (instance.parameters.gamma - 1) channel = grid_in_memory.new_channel_to(instance.grid) channel.copy() instance.initialize_grid() particle = Particle( mass=mass, position=length * [0.5, 0.5, 0.5], velocity=[0.0, 0.0, 0.0] | units.kms ) gravity = Hermite(converter) dx = (grid_in_memory.x[1][0][0] - grid_in_memory.x[0] [0][0]).as_quantity_in(units.AU) gravity.parameters.epsilon_squared = dx**2 gravity.particles.add_particle(particle) potential = gravity.get_potential_at_point( 0 * instance.potential_grid.x.flatten(), instance.potential_grid.x.flatten(), instance.potential_grid.y.flatten(), instance.potential_grid.z.flatten() ) potential = potential.reshape(instance.potential_grid.x.shape) instance.potential_grid.potential = potential instance.evolve_model(100 | units.yr) print(instance.get_timestep().value_in(units.yr)) value_to_plot = instance.grid.rho[:, :, 0].value_in( units.MSun / units.AU**3) # value_to_plot = potential[...,...,0].value_in(potential.unit) plot_grid(value_to_plot) def plot_grid(x): figure = pyplot.figure(figsize=(6, 6)) plot = figure.add_subplot(1, 1, 1) mappable = plot.imshow(x, origin='lower') pyplot.colorbar(mappable) # figure.savefig('orszag_tang.png') pyplot.show() if __name__ == '__main__': hydro_grid_in_potential_well()
3,310
32.444444
77
py
amuse
amuse-main/examples/simple/grav_stellar_simple.py
# -*- coding: ascii -*- """ simple coupling of a stellar evolution and a gravitational code to simulate a cluster of stars. """ from __future__ import print_function import os from amuse.units.optparse import OptionParser from amuse.units import units, nbody_system from amuse.datamodel.particles import Channels from amuse.community.hermite.interface import Hermite from amuse.community.seba.interface import SeBa from amuse.couple.bridge import Bridge from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution from matplotlib import pyplot from amuse import plot as aplot from amuse.support.console import set_printing_strategy def create_stars(number_of_stars, size): masses = new_salpeter_mass_distribution( number_of_stars, mass_min=2 | units.MSun) converter = nbody_system.nbody_to_si(masses.sum(), size) stars = new_plummer_model(number_of_stars, convert_nbody=converter) stars.mass = masses stars.zams_mass = masses return stars, converter def plot_results(stars, time): mass_loss = stars.zams_mass - stars.mass x = stars.x.in_(units.parsec) y = stars.y.in_(units.parsec) pyplot.figure(figsize=(8, 8)) aplot.plot(x, y, "*") for x, y, mass_loss in zip(x.number, y.number, mass_loss): pyplot.annotate( "%0.2f" % abs(mass_loss.number), xy=(x, y + 2), horizontalalignment='center', verticalalignment='bottom', ) pyplot.axis('equal') pyplot.xlim([-60, 60]) pyplot.ylim([-60, 60]) aplot.xlabel("x") aplot.ylabel("y") pyplot.title("time = " + str(time)) if not os.path.exists("plots"): os.mkdir("plots") name = "plots/plot_{0:=05}.png".format(int(time.value_in(units.Myr))) print("creating", name) pyplot.savefig(name) pyplot.close() def gravity_and_stellar_evolution( number_of_stars, size, end_time, sync_timestep=1 | units.Myr, plot_timestep=10 | units.Myr): stars, converter = create_stars(number_of_stars, size) gravity = Hermite(converter) stellar = SeBa() bridge = Bridge() gravity.particles.add_particles(stars) stellar.particles.add_particles(stars) bridge.add_system(gravity) bridge.add_system(stellar) bridge.channels.add_channel(stellar.particles.new_channel_to( gravity.particles, attributes=["mass", "radius"])) bridge.timestep = sync_timestep plot_channels = Channels() plot_channels.add_channel(stellar.particles.new_channel_to(stars)) plot_channels.add_channel(gravity.particles.new_channel_to(stars)) time = 0 | units.Myr while time <= end_time: bridge.evolve_model(time) plot_channels.copy() plot_results(stars, time) time += plot_timestep def parse_arguments(): parser = OptionParser() parser.add_option( "-N", dest="number_of_stars", type="int", default=100, help="The number of stars in the cluster [%default].") parser.add_option( "-s", dest="size", type="float", unit=units.parsec, default=10, help="The total size of the cluster [%default %unit].") parser.add_option( "-t", dest="end_time", type="float", unit=units.Gyr, default=0.1, help="The end time of the simulation [%default %unit].") options, args = parser.parse_args() return options.__dict__ if __name__ == "__main__": options = parse_arguments() set_printing_strategy( "custom", preferred_units=[ units.MSun, units.parsec, units.Myr ], precision=3) gravity_and_stellar_evolution(**options)
3,683
27.338462
79
py
amuse
amuse-main/examples/simple/orszag_tang.py
# -*- coding: ascii -*- """ Runs the Orszag-Tang Vortex problem described in the Athena test-suite (http://www.astro.virginia.edu/VITA/ATHENA/ot.html): 'The Orszag-Tang Vortex is a well-known test for MHD codes. The intial conditions lead to a system of supersonic MHD turbulence, making this problem a good test of the algorithm's ability to handle such turbulence and MHD shocks.' """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.community.athena.interface import Athena from amuse.units.generic_unit_system import ( mass, length, speed, time, current ) from amuse.datamodel import Grid density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) magnetic_field = mass / current / time**2 vector_potential = magnetic_field * length PI = numpy.pi GAMMA = 5.0 / 3.0 DIMENSIONS_OF_MESH = (256, 256, 1) DIMENSIONS_OF_A_MESH = (258, 258, 1) B0 = 1.0 / numpy.sqrt(4.0 * PI) | magnetic_field D0 = 25.0 / (36.0 * PI) | density V0 = 1.0 | speed P0 = 5.0 / (12.0 * PI) | energy def new_instance_of_hydro_code(number_of_workers=1): result = Athena(number_of_workers=number_of_workers, mode='mhd') result.initialize_code() result.parameters.gamma = GAMMA result.parameters.courant_number = 0.8 return result def set_parameters(instance): instance.parameters.mesh_size = DIMENSIONS_OF_MESH instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") result = instance.commit_parameters() def new_grid(): grid = Grid.create(DIMENSIONS_OF_MESH, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(grid): grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy def clear_magnetic_field_grid(grid): grid.B1i = 0.0 | magnetic_field grid.B2i = 0.0 | magnetic_field grid.B3i = 0.0 | magnetic_field return grid def initialize_grid(grid, magentic_field_grid): temp = [1, 1, 1] | length l = 1.0 | length A_grid = Grid.create( DIMENSIONS_OF_A_MESH, temp + grid.cellsize() * [2, 2, 0] ) A_grid.position -= A_grid.cellsize() * [0.5, 0.5, 0.0] A_grid.Az = ( B0 * l / (4.0 * PI) * numpy.cos(4.0 * PI / l * A_grid.x) + B0 * l / (2.0 * PI) * numpy.cos(2.0 * PI / l * A_grid.y) ) assert grid.cellsize().x == A_grid.cellsize().x assert grid.cellsize().y == A_grid.cellsize().y # assert grid.dim[0] == A_grid.dim[0] magentic_field_grid.B1i = ( A_grid.Az[:-1, 1:, ...] - A_grid.Az[:-1, :-1, ...] ) / A_grid.cellsize().y magentic_field_grid.B2i = ( - ( A_grid.Az[1:, :-1, ...] - A_grid.Az[:-1, :-1, ...] ) / A_grid.cellsize().x ) magentic_field_grid.B3i = 0.0 | magnetic_field # magentic_field_grid.B1i[-1,...,...] = magentic_field_grid.B1i[0,...,...] # magentic_field_grid.B2i[...,-1,...] = magentic_field_grid.B2i[...,0,...] magentic_field_grid.B1c = 0.0 | magnetic_field magentic_field_grid.B2c = 0.0 | magnetic_field magentic_field_grid.B3c = 0.0 | magnetic_field magentic_field_grid.divB = 0.0 | (magnetic_field / length) magentic_field_grid.B1c[:-1, ..., ...] = ( magentic_field_grid.B1i[:-1, ..., ...] + magentic_field_grid.B1i[1:, ..., ...]) * 0.5 magentic_field_grid.B2c[..., :-1, ...] = ( magentic_field_grid.B2i[..., :-1, ...] + magentic_field_grid.B2i[..., 1:, ...]) * 0.5 magentic_field_grid.B3c = magentic_field_grid.B3i # magentic_field_grid.B1c[-1,...,...] = magentic_field_grid.B1c[0,...,...] # magentic_field_grid.B2c[...,-1,...] = magentic_field_grid.B2c[...,0,...] mu0 = 1.0 | (mass * length / time**2 / current**2) magentic_field_grid.divB[0:-1, 0:-1, ...] = ( ( magentic_field_grid.B1i[:-1, :-1, ...] - magentic_field_grid.B1i[1:, :-1, ...] ) / grid.cellsize().x + ( magentic_field_grid.B2i[:-1, :-1, ...] - magentic_field_grid.B2i[:-1, 1:, ...] ) / grid.cellsize().y ) assert (abs(magentic_field_grid.divB[:-1, :-1, :-1]) < 1.0e-10 | magentic_field_grid.divB.unit).all() assert magentic_field_grid.B1i.unit == magnetic_field grid.rho = D0 grid.rhovx = -D0 * V0 * numpy.sin(2.0 * PI / l * grid.y) grid.rhovy = D0 * V0 * numpy.sin(2.0 * PI / l * grid.x) grid.rhovz = 0.0 | momentum print("sum rho vx:", grid.rhovx.sum()) print("sum rho vy:", grid.rhovy.sum()) print("sum rho vz:", grid.rhovz.sum()) grid.energy = ( P0 / (GAMMA - 1) + 0.5 * (grid.rhovx**2 + grid.rhovy**2 + grid.rhovz**2) / grid.rho + 0.5 * ( magentic_field_grid.B1c[:-1, :-1, :-1]**2 + magentic_field_grid.B2c[:-1, :-1, :-1]**2 + magentic_field_grid.B3c[:-1, :-1, :-1]**2 ) / mu0 ) def simulate_orszag_tang_problem(end_time): instance = new_instance_of_hydro_code() set_parameters(instance) print("setup grid") for hydro_grid, mhd_grid in instance.iter_hydro_and_mhd_grids(): inmem = hydro_grid.copy() inmem_mhd = mhd_grid.copy() clear_grid(inmem) clear_magnetic_field_grid(inmem_mhd) initialize_grid(inmem, inmem_mhd) from_model_to_code = inmem.new_channel_to(hydro_grid) from_model_to_code.copy() from_model_to_code = inmem_mhd.new_channel_to(mhd_grid) from_model_to_code.copy() instance.initialize_grid() print("start evolve") dt = end_time / 10 t = dt while t < end_time: instance.evolve_model(t) print("time : ", t) t += dt print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result if __name__ == "__main__": rho = grid.rho[..., ..., 0].value_in(density) print(rho) figure = pyplot.figure(figsize=(6, 6)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('orszag_tang.png') pyplot.show() if __name__ in ("__main__", "__plot__"): grids = simulate_orszag_tang_problem(0.2 | time) plot_grid(grids[0])
6,607
29.036364
79
py
amuse
amuse-main/examples/simple/galactic_center_in_code.py
# -*- coding: ascii -*- """ Evolves a cluster orbiting a massive central particle. """ from __future__ import print_function # import numpy from amuse.units import units from amuse.units import constants from amuse.units import nbody_system from amuse.datamodel import particles from amuse.community.phigrape.interface import PhiGRAPE from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model def new_galactic_center(mass): result = particles.Particle() result.mass = mass result.position = [0, 0, 0] | units.parsec result.velocity = [0, 0, 0] | units.kms result.radius = 0 | units.parsec return result def circular_velocity_for_stable_orbit(radius, central_mass): return (constants.G * central_mass / radius)**0.5 def new_cluster( number_of_particles, W0, converter ): particles = new_king_model(N, W0, convert_nbody=converter) particles.radius = 0.0 | units.parsec return particles def new_gravity_code(converter, timestep=0.0025 | units.Myr): result = PhiGRAPE(converter) result.parameters.epsilon_squared = (0.01 | units.parsec)**2 return result def shift_particles(particles, dx, dy, dz, dvx, dvy, dvz): particles.x += dx particles.y += dy particles.z += dz particles.vx += dvx particles.vy += dvy particles.vz += dvz if __name__ == "__main__": # parameter setup: N = 128 W0 = 3 Rinit = 50. | units.parsec timestep = 0.01 | units.Myr Mcluster = 4.e4 | units.MSun Rcluster = 0.7 | units.parsec central_mass = 1.6e7 | units.MSun converter = nbody_system.nbody_to_si(Mcluster, Rcluster) cluster = new_cluster(number_of_particles=N, W0=W0, converter=converter) code = new_gravity_code(converter, timestep=timestep) galactic_center = new_galactic_center(central_mass) # shift the cluster to an orbit around GC # (note the systems share the same coordinate frame, although units may # differ) vcirc = circular_velocity_for_stable_orbit(Rinit, central_mass) shift_particles( cluster, Rinit, 0 | units.parsec, 0. | units.parsec, 0 | units.kms, 0.8 * vcirc, 0 | units.kms ) code.particles.add_particles(cluster) # add galactic center to the code code.particles.add_particle(galactic_center) print("Start evolution") # evolve and make plots times = units.Myr([0., 0.2, 0.4, 0.6]) f = pyplot.figure(figsize=(8, 8)) for i, time in enumerate(times): code.evolve_model(time) print("Evolved to time:", time) x = code.particles.x.value_in(units.parsec) y = code.particles.y.value_in(units.parsec) subplot = f.add_subplot(2, 2, i + 1) subplot.plot(x, y, 'r .') subplot.plot([0.], [0.], 'b +') subplot.set_xlim(-60, 60) subplot.set_ylim(-60, 60) subplot.set_title(time) if i == 7: subplot.set_xlabel('parsec') code.stop() pyplot.show()
3,000
26.53211
76
py
amuse
amuse-main/examples/simple/sunandearth.py
# -*- coding: ascii -*- """ Evolves the dynamic evolution of the earth around the sun. """ from __future__ import print_function from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse.community.hermite.interface import Hermite from matplotlib import pyplot from amuse import datamodel def new_system_of_sun_and_earth(): stars = datamodel.Particles(2) sun = stars[0] sun.mass = 1.0 | units.MSun sun.position = (0.0, 0.0, 0.0) | units.m sun.velocity = (0.0, 0.0, 0.0) | (units.m / units.s) sun.radius = 1.0 | units.RSun earth = stars[1] earth.mass = 5.9736e24 | units.kg earth.radius = 6371.0 | units.km earth.position = (149.5e6, 0.0, 0.0) | units.km earth.velocity = (0.0, 29800, 0.0) | (units.m / units.s) return stars def simulate_system_until(particles, end_time): convert_nbody = nbody_system.nbody_to_si( 1.0 | units.MSun, 149.5e6 | units.km) instance = Hermite(convert_nbody) instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.particles.add_particles(particles) t0 = 0 | units.day dt = 10 | units.day t = t0 earth = instance.particles[1] x_values = quantities.AdaptingVectorQuantity() y_values = quantities.AdaptingVectorQuantity() while t < end_time: instance.evolve_model(t) x_values.append(earth.x) y_values.append(earth.y) t += dt instance.stop() return x_values, y_values def plot_track(x, y): figure = pyplot.figure(figsize=(5, 5)) plot = figure.add_subplot(1, 1, 1) x_values_in_AU = x.value_in(units.AU) y_values_in_AU = y.value_in(units.AU) plot.plot(x_values_in_AU, y_values_in_AU, color="b") plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) plot.set_xlabel('x (AU)') plot.set_ylabel('y (AU)') pyplot.show() if __name__ == "__main__": particles = new_system_of_sun_and_earth() x, y = simulate_system_until(particles, 20 | units.yr) plot_track(x, y)
2,057
22.655172
60
py
amuse
amuse-main/examples/textbook/plot_hydro_disk_with_bump.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import os import sys import numpy import matplotlib #matplotlib.use('Agg') from matplotlib import pyplot #from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from amuse.units.optparse import OptionParser from time import sleep from amuse.ext.orbital_elements import orbital_elements_from_binary def read_planetary_system(filename): #lim, snapshot_id): source = Particles(0) gas = Particles(0) time = 0 | units.yr bodies = read_set_from_file(filename, "amuse") i = 0 for bi in bodies.history: i+=1 if i%2: source = bi else: gas = bi break print("N=", len(source), len(gas)) return source, gas def mu(X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception("Error in calculating mu: mass fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) def plot_single_image(source, disk): lim = 150#|units.AU index = 4 left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.05 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] fig = pyplot.figure(figsize=(16,14)) time = disk.get_timestamp() xy = pyplot.axes(rect_scatter) xz = pyplot.axes(rect_histx) yz = pyplot.axes(rect_histy) xy.set_xlabel("X [AU]") xy.set_ylabel("Y [AU]") xz.set_ylabel("Z [AU]") yz.set_xlabel("Z [AU]") positions = disk.position x, y, z = positions.x.value_in(units.AU), positions.y.value_in(units.AU), positions.z.value_in(units.AU) vx, vy, vz = disk.vx.value_in(units.kms), disk.vy.value_in(units.kms), disk.vz.value_in(units.kms) v = numpy.sqrt(vx**2+vy**2+vz**2) v_max = max(v) v_min = min(v) stars = source xs, ys, zs = stars.position.x.value_in(units.AU), stars.position.y.value_in(units.AU), stars.position.z.value_in(units.AU) # sizes = 1000 # sizes = 1000*disk.rho/disk.rho.max() alpha = 0.2 us = disk.u xion = disk.xion print(xion) u_min, u_max = min(us), max(us) xion_min, xion_max = min(xion), max(xion) print("u=", u_min, u_max) Ts = mu() / constants.kB * disk.u T_min = max(20|units.K, mu() / constants.kB * u_min) T_max = min(1800|units.K, mu() / constants.kB * u_max) print("T=", T_min, T_max) print("X=", xion_min, xion_max) log_u = numpy.log((us / u_min)) / numpy.log((u_max / u_min)) clipped_log_u = numpy.minimum(numpy.ones_like(log_u), numpy.maximum(numpy.zeros_like(log_u), log_u)) log_v = numpy.log((v / v_min)) / numpy.log((v_max / v_min)) clipped_log_v = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), log_v)) log_T = numpy.log((Ts / T_min)) / numpy.log((T_max / T_min)) clipped_log_T = numpy.minimum(numpy.ones_like(log_T), numpy.maximum(numpy.zeros_like(log_T), log_T)) ps = disk.rho p_min, p_max = min(ps), max(ps) log_p = numpy.log((ps / p_min)) / numpy.log((p_max / p_min)) clipped_log_p = numpy.minimum(numpy.ones_like(log_p), numpy.maximum(numpy.zeros_like(log_p), log_p)) blue = clipped_log_T red = clipped_log_p green = clipped_log_v colors = numpy.transpose(numpy.array([red, green, blue])) sizes = 2*2000*disk.h_smooth/disk.h_smooth.max() xy.scatter(x, y, sizes, c=colors, edgecolors = "none", alpha = alpha) s = 50*stars.mass/stars.mass.min() xy.scatter(xs, ys, s, c='b', edgecolors = "none", alpha = 1) xy.set_xlim( (-lim, lim) ) xy.set_ylim( (-lim, lim) ) sizes = 20*200*disk.h_smooth/disk.h_smooth.max() xz.scatter(x, z, sizes, c=colors, edgecolors = "none", alpha = alpha) xz.scatter(xs, zs, s, c='b', edgecolors = "none", alpha = 1) yz.scatter(z, y, sizes, c=colors, edgecolors = "none", alpha = alpha) yz.scatter(zs, ys, s, c='b', edgecolors = "none", alpha = 1) xz.set_xlim( xy.get_xlim() ) yz.set_ylim( xy.get_xlim() ) yz.set_xlim( (-0.2*lim, 0.2*lim) ) xz.set_ylim( (-0.2*lim, 0.2*lim) ) # yz.set_xlim( (-lim, lim) ) # xz.set_ylim( (-lim, lim) ) filename = "fig_hydro_disk_with_bump_i{0:04}".format(index) fig.savefig(filename) # pyplot.show() def main(filename=None): #, lim=-1|units.AU, image_id=-1): output_single_image(filename) """ if filename: output_single_image(lim, image_id) else: output_multiple_images(lim) """ def calculate_orbital_elements(star, planet): from amuse.ext.orbital_elements import orbital_elements_from_binary p = Particles() p.add_particle(star) p.add_particle(planet) M, m, a, e, ta_out, inc, lan_out, aop_out = orbital_elements_from_binary(p, G=constants.G) #print "Orbital elements:", M, m, a, e, ta_out, inc, lan_out, aop_out return a, e, inc def output_single_image(filename): source, disk = read_planetary_system(filename) print(disk[0].position.in_(units.AU)) snapshot_id = 1 lim = 150|units.AU plot_single_image(source, disk) def output_multiple_images(lim): snapshot_id = 0 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) while os.path.exists(filename): bodies = read_set_from_file(filename, "amuse") for bi in bodies.history: if len(bi)<=20: planets = bi.copy() time = bi.get_timestamp() print("Orbits at t=", time, planets.semimajor_axis.in_(units.AU), planets.eccentricity) else: disk = bi.copy() time = bi.get_timestamp() print("Snapshot=", snapshot_id, time) if image_id<0 or image_id == snapshot_id: plot_single_image(planets, disk) if image_id == snapshot_id: print("Stop plotting") break snapshot_id += 1 filename = "planetary_system_i{0:04}.amuse".format(snapshot_id) def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "hydro_disk_with_bump_i0004.amuse", help="output filename [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
6,970
33.681592
126
py
amuse
amuse-main/examples/textbook/NonConservativeMassTransfer.py
#!/usr/bin/python from numpy import * from amuse.lab import * #a XiTau = 263.973|units.RSun = 1.2272459225 AU #HD a= 171.109773416 RSun = quantity<0.795511639712 AU> def orbital_separation_after_mass_transfer(a, md, mdf, ma, maf, nj) : mt = ma+md mtf = maf+mdf fa = ((mdf*maf)/(md*ma))**(-2.) * (mtf/mt)**(2.*nj+1.) # print "double_star.orbital_separation_after_mass_transfer()", fa return a*fa def alpha_lambda_due_to_mass_ejection(ai, af, dM, m1, dm1, m2, dm2): al = -1 * ((m1+m1)*dM/ai) / (2. * ( (m1+dm1)*(m2+dm2)/ai - m1*m2/af)) return al def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="mdonor",type="float",default=5.50|units.MSun) result.add_option("-m", unit=units.MSun, dest="macc",type="float",default=6.30|units.MSun) result.add_option("--dMd", unit=units.MSun, dest="dmd",type="float",default=-0.06|units.MSun) result.add_option("--dma", unit=units.MSun, dest="dma",type="float",default=0.02|units.MSun) result.add_option("-a", unit=units.AU, dest="a",type="float",default=1.2272459225|units.AU) result.add_option("--dt", unit=units.day, dest="dt",type="float",default=1400.|units.day) result.add_option("--nj", dest="nj",type="float",default=3) return result def main(dt, a, mdonor, dmd, macc, dma, nj): mdonor_new = mdonor+dmd macc_new = macc+dma a_new = orbital_separation_after_mass_transfer(a, mdonor, mdonor_new, macc, macc_new, nj) print("a_old=", a.as_quantity_in(units.AU)) print("a_new=", a_new.as_quantity_in(units.AU)) if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
1,955
36.615385
74
py
amuse
amuse-main/examples/textbook/plot_supernova_IIp_and_disk_temperature.py
import numpy from matplotlib import pyplot from amuse.lab import * from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct from supernova_IIp_Lightcurve import Supernova_IIp def read_supernova_irradiation_file(filename): t = [] Tmean = [] Tmax = [] for line in open(filename): if 'Time' in line: sl = line.split() t.append(float(sl[1])) if 'Temperature:' in line: sl = line.split() Tmean.append(float(sl[3])) Tmax.append(float(sl[1])) return numpy.asarray(t, dtype="float"), Tmean, Tmax def read_Earthorbit(): t = [] e = [] a = [] tmax = 1.e+6 for line in open('Eart_Orbit_Eps-3.data'): if '#' not in line: sl = line.split() t.append(float(sl[0])) a.append(float(sl[1])) e.append(float(sl[2])) if t[-1]>tmax: break return t, a, e if __name__ in ('__main__', '__plot__'): to = 50|units.day t_offset = to + (((0.15|units.parsec)/(1|units.lightyear)) | units.yr) filename = 'SN10a.R0.15.i15.data' time, Tmean, Tmax = read_supernova_irradiation_file(filename) time += t_offset.value_in(units.day) t_offset = to + (((0.3|units.parsec)/(1|units.lightyear)) | units.yr) filename = 'SN11aof.R0.3.i45.data' t3pc_N7, Tmean3pc_N7, Tmax3pc_N7 = read_supernova_irradiation_file(filename) t3pc_N7 += t_offset.value_in(units.day) t_offset = to + (((0.4|units.parsec)/(1|units.lightyear)) | units.yr) filename = 'SN11aof.R0.4.i15.data' t3pc_N8, Tmean3pc_N8, Tmax3pc_N8 = read_supernova_irradiation_file(filename) t3pc_N8 += t_offset.value_in(units.day) PS1_11aof = Supernova_IIp("11aof", to) t = 10**numpy.arange(-2, 3., 0.01) | units.day L11aof = [] | units.erg/units.s for ti in t: L11aof.append(PS1_11aof.luminosity_at_time(ti)) L11aof = numpy.log10(L11aof.value_in(units.LSun)) PS1_10a = Supernova_IIp("10a", to) L10a = [] | units.erg/units.s for ti in t: L10a.append(PS1_10a.luminosity_at_time(ti)) L10a = numpy.log10(L10a.value_in(units.LSun)) from matplotlib import pyplot, rc x_label = "$t$ [day]" y_label = "L [L$_\odot$]" figure = single_frame(x_label, y_label, xsize=14, ysize=10) ax1 = pyplot.gca() cols = get_distinct(4) font = {'size' : 20} rc('font', **font) ax1.plot(t.value_in(units.day), L11aof, ls='-', c=cols[0]) ax1.plot(t.value_in(units.day), L10a, ls='--', c=cols[0]) ax1.set_xlabel('time [day]') ax1.set_ylabel('log$_{10}$(L/L$_\odot$)', color=cols[0]) for tl in ax1.get_yticklabels(): tl.set_color(cols[0]) ax2 = ax1.twinx() ax2.plot(time, Tmean, cols[1], ls='--') ax2.plot(t3pc_N7, Tmean3pc_N7, cols[1]) ax2.plot(t3pc_N8, Tmean3pc_N8, cols[1], lw=4) ax2.set_ylabel('mean temperature [K]', color=cols[1]) for tl in ax2.get_yticklabels(): tl.set_color(cols[1]) t_cooling = [950, 1061] T_cooling = [1600, 800] ax2.plot(t_cooling, T_cooling, cols[3], lw=1) ax2.text(t_cooling[0]+20, T_cooling[0]-100, "cooling of 0.3 K/h", rotation=-76.5, color=cols[3]) pyplot.show() # pyplot.savefig("supernova_IIp_and_disk_temperature")
3,335
32.029703
100
py
amuse
amuse-main/examples/textbook/multiple_stellar_code.py
from amuse.lab import * ###BOOKLISTSTART### def evolve_with_different_stellar_model(): times = [10, 100, 1000] | units.Myr stars = Particles(mass=[1, 2, 4]|units.MSun) stellars = [SeBa(), MESA(), SSE()] channels = [] for star, stellar in zip(stars, stellars): stellar.particles.add_particle(star) channels.append(stellar.particles.new_channel_to(stars)) for time, channel, stellar in zip(times, channels, stellars): stellar.evolve_model(time) channel.copy() for time, star in zip(times, stars): print("Time=", time, "M=", star.mass) stellar.stop() ###BOOKLISTSTOP### def evolve_with_same_stellar_model(): time = [10, 100, 1000] | units.Myr stars = Particles(mass=[1, 2, 4]|units.MSun) stellar = SeBa() stellar.particles.add_particles(stars) channel = stellar.particles.new_channel_to(stars) for ti, si in zip(time, stellar.particles): si.evolve_for(ti) channel.copy() print("Time=", stellar.model_time, "age=", stars.age, \ "\n\tmass=", stars.mass) stellar.stop() if __name__ in ('__main__', '__plot__'): set_printing_strategy("custom",\ preferred_units = [units.MSun, units.RSun, units.Myr],\ precision = 6, prefix = "", separator = "[", suffix = "]") evolve_with_same_stellar_model()
1,350
31.95122
66
py
amuse
amuse-main/examples/textbook/merge_two_stars_sph_evolve.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.ext.sph_to_star import convert_SPH_to_stellar_model from prepare_figure import single_frame from distinct_colours import get_distinct def plot_clumps(groups): number_of_particles_in_group = [] fraction_of_mass_in_group = [] print("N =", len(groups)) ci = ['r', 'b', 'g', 'k'] figure = pyplot.figure(figsize=(6,6)) i = 0 alpha = 1 sizes = 50 for group in groups: pyplot.scatter(group.x.value_in(units.RSun), group.y.value_in(units.RSun), sizes, ci[i], edgecolors = "none", alpha = alpha) i += 1 pyplot.xlabel('x (RSun)') pyplot.ylabel('y (RSun)') size = 100. pyplot.xlim(-size, size) pyplot.ylim(-size, size) pyplot.axis('equal') pyplot.savefig('clumps') pyplot.show() def find_clumps(particles, unit_converter): hop = Hop(unit_converter) hop.particles.add_particles(particles) hop.calculate_densities() mean_densty = hop.particles.density.mean() hop.parameters.peak_density_threshold = mean_densty hop.parameters.saddle_density_threshold = 0.99*mean_densty hop.parameters.outer_density_threshold = 0.01*mean_densty hop.do_hop() result = [x.get_intersecting_subset_in(particles) for x in hop.groups()] hop.stop() return result def evolve_single_star(mass, tend): star = Particles(1) star.mass = mass stellar_evolution = MESA() stellar_evolution.particles.add_particles(star) time = [] | units.Myr mass = [] | units.MSun radius = [] | units.RSun temperature = [] | units.K luminosity = [] | units.LSun stellar_type = [] while stellar_evolution.model_time<tend: stellar_evolution.evolve_model() time.append(stellar_evolution.model_time) mass.append(stellar_evolution.particles[0].mass) radius.append(stellar_evolution.particles[0].radius) temperature.append(stellar_evolution.particles[0].temperature) luminosity.append(stellar_evolution.particles[0].luminosity) stellar_type.append(stellar_evolution.particles[0].stellar_type) print("Time=", time[-1], stellar_type[-1], mass[-1], radius[-1], \ temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)) if stellar_type[-1] >= 4 | units.stellar_type: break stellar_evolution.stop() return time, stellar_type, mass, radius, temperature, luminosity def merge_two_stars_sph_and_evolve(Mprim, Msec, tcoll, tend): stars = Particles(2) stars.mass = [Mprim.value_in(units.MSun), Msec.value_in(units.MSun)] | units.MSun stellar_evolution = MESA() stellar_evolution.particles.add_particles(stars) # Evolve the stars to tcoll. while stellar_evolution.model_time < tcoll: stellar_evolution.evolve_model() print("Time=", stellar_evolution.model_time, \ stellar_evolution.particles[0].stellar_type, \ stellar_evolution.particles[0].mass, \ stellar_evolution.particles[0].radius, \ stellar_evolution.particles[0].temperature.in_(units.K), \ stellar_evolution.particles[0].luminosity.in_(units.LSun)) print(stars) # Convert to SPH particles (nsph per solar mass). nsph = 100 Nprim = int(nsph*stellar_evolution.particles[0].mass.value_in(units.MSun)) mgas = stellar_evolution.particles[0].mass/Nprim Nsec = int(stellar_evolution.particles[1].mass/mgas) print("N gas =", Nprim, Nsec) sph_primary = convert_stellar_model_to_SPH( stellar_evolution.particles[0], Nprim, seed=12345 ).gas_particles sph_secondary = convert_stellar_model_to_SPH( stellar_evolution.particles[1], Nsec, seed=12345 ).gas_particles stellar_evolution.stop() # Merge the stars using SPH. distance = 2 | units.RSun sph_secondary.x += distance vx = numpy.sqrt(2*constants.G*stars.mass.sum()/distance) sph_secondary.vx -= vx print('distance =', distance, 'vx =', vx.in_(units.kms), end=' ') print('d/v =', (distance/vx).in_(units.hour)) sph_particles = Particles() sph_particles.add_particles(sph_primary) sph_particles.add_particles(sph_secondary) sph_particles.move_to_center() converter = nbody_system.nbody_to_si(1|units.hour, 1|units.RSun) hydrodynamics = Gadget2(converter) hydrodynamics.gas_particles.add_particles(sph_particles) tf = 10.|units.hour hydrodynamics.evolve_model(tf) hydrodynamics.gas_particles.copy_values_of_attributes_to(["x", "y", "z", "vx", "vy", "vz", "density", "u", "pressure"], sph_particles) hydrodynamics.stop() # Convert back to a stellar model. print("N all =", len(sph_particles)) sph_particles.move_to_center() clumps = find_clumps(sph_particles, converter) sph_particles = clumps[0] print("N blob =", len(sph_particles)) #plot_clumps(clumps) print("convert SPH to stellar model") sph_particles.move_to_center() merged_star = convert_SPH_to_stellar_model(sph_particles) # Evolve the stellar model. print("initiate stellar evolution model") #stellar_evolution = MESA(redirect="none") stellar_evolution = EVtwin(redirect="none") stellar_evolution.new_particle_from_model(merged_star, 0.0|units.Myr) print("star:", stellar_evolution.particles) print("evolve star") time = [] | units.Myr mass = [] | units.MSun radius = [] | units.RSun temperature = [] | units.K luminosity = [] | units.LSun stellar_type = [] while stellar_evolution.model_time < (tend-tcoll): try: stellar_evolution.evolve_model() time.append(stellar_evolution.model_time) mass.append(stellar_evolution.particles[0].mass) radius.append(stellar_evolution.particles[0].radius) temperature.append(stellar_evolution.particles[0].temperature) luminosity.append(stellar_evolution.particles[0].luminosity) stellar_type.append(stellar_evolution.particles[0].stellar_type) print("Time=", time[-1], stellar_type[-1], mass[-1], radius[-1], \ temperature[-1].in_(units.K), luminosity[-1].in_(units.LSun)) if stellar_type[-1] >= 4 | units.stellar_type: break except: print('Code crashed at time', stellar_evolution.model_time) break stellar_evolution.stop() return time, stellar_type, mass, radius, temperature, luminosity def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("--tcoll", unit=units.Myr, dest="tcoll", type="float", default = 150|units.Myr, help="evolution time scale [%default]") result.add_option("--tend", unit=units.Myr, dest="tend", type="float", default = 2|units.Gyr, help="evolution time scale [%default]") result.add_option("-M", unit=units.MSun, dest="Mprim", type="float", default = 3|units.MSun, help="stellar mass [%default]") result.add_option("-m", unit=units.MSun, dest="Msec", type="float", default = 1|units.MSun, help="stellar mass [%default]") return result if __name__ == "__main__": # High-level structure of merge_two_stars_and_evolve.py and # merge_two_stars_sph_evolve.py are designed to be identical. set_printing_strategy("custom", #nbody_converter = converter, precision = 11, prefix = "", separator = " [", suffix = "]") o, arguments = new_option_parser().parse_args() Mprim = o.Mprim Msec = o.Msec tend = o.tend tcoll = o.tcoll color = get_distinct(4) # 0 = cyan, 1 = red, 2 = mustard, 3 = green x_label = "T [K]" y_label = "L [$L_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) pyplot.xlim(2.e+4, 3.e+3) pyplot.ylim(20., 2.e+3) print("Evolve single star of mass", Mprim.in_(units.MSun)) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mprim, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[1], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[1], s=150, marker='^', edgecolor='k', zorder=2) tms = 0 |units.Myr for i in range(len(stp)): if stp[i] < 2 | units.stellar_type: tms = time[i] if tms <= 1|units.Myr: tms = 10|units.Myr print("Main sequence lifetime =", tms.in_(units.Myr)) tcoll = 0.5*tms icoll = 0 for i in range(len(stp)): if time[i] <= tcoll: icoll = i pyplot.scatter(temperature[icoll].value_in(units.K), luminosity[icoll].value_in(units.LSun), c=color[2], s=150, marker='o', edgecolor='k', zorder=2) print("Evolve single star of mass", (Mprim+Msec).in_(units.MSun)) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mprim+Msec, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[0], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[0], s=150, marker='^', edgecolor='k', zorder=2) print("Evolve two single stars and collide at", tcoll.in_(units.Myr)) time, stp, mass, radius, temperature, luminosity \ = merge_two_stars_sph_and_evolve(Mprim, Msec, tcoll, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[2], ls="--", lw=3, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[2], s=150, marker='o', edgecolor='k', zorder=3) Mmerger = mass[0] print("Evolve single star of mass", Mmerger) time, stp, mass, radius, temperature, luminosity \ = evolve_single_star(Mmerger, tend) pyplot.plot(temperature.value_in(units.K), luminosity.value_in(units.LSun), c=color[3], lw=2, zorder=1) pyplot.scatter(temperature[0].value_in(units.K), luminosity[0].value_in(units.LSun), c=color[3], s=150, marker='^', edgecolor='k', zorder=2) ax = pyplot.gca() ax.tick_params(axis='both', which='both', direction='in') save_file = 'merge_two_stars_sph_evolve.pdf' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
11,648
37.319079
79
py
amuse
amuse-main/examples/textbook/basic_multiples_nbody.py
import numpy from amuse.units import nbody_system from amuse.ic.plummer import new_plummer_model from amuse.community.ph4.interface import ph4 from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples # Awkward syntax here because multiples needs a function that resets # and returns a small-N integrator. SMALLN = None def init_smalln(): global SMALLN SMALLN = SmallN() def new_smalln(): SMALLN.reset() return SMALLN def stop_smalln(): global SMALLN SMALLN.stop() def print_diagnostics(grav, E0=None): # Simple diagnostics. ke = grav.kinetic_energy pe = grav.potential_energy Nmul, Nbin, Emul = grav.get_total_multiple_energy() print('') print('Time =', grav.get_time()) print(' top-level kinetic energy =', ke) print(' top-level potential energy =', pe) print(' total top-level energy =', ke + pe) print(' ', Nmul, 'multiples,', 'total energy =', Emul) E = ke + pe + Emul print(' uncorrected total energy =', E) # Apply known corrections. Etid = grav.multiples_external_tidal_correction \ + grav.multiples_internal_tidal_correction # tidal error Eerr = grav.multiples_integration_energy_error # integration error E -= Etid + Eerr print(' corrected total energy =', E) if E0 is not None: print(' relative energy error=', (E-E0)/E0) return E def integrate_system(N, t_end, seed=None): gravity = ph4() gravity.initialize_code() gravity.parameters.set_defaults() if seed is not None: numpy.random.seed(seed) stars = new_plummer_model(N) stars.mass = 1./N | nbody_system.mass stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) id = numpy.arange(N) stars.id = id+1 # Set dynamical radii for encounters. stars.radius = 0.5*stars.mass.number | nbody_system.length gravity.particles.add_particles(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() init_smalln() kep = Kepler(unit_converter=None) kep.initialize_code() multiples_code = multiples.Multiples(gravity, new_smalln, kep) multiples_code.neighbor_perturbation_limit = 0.05 multiples_code.global_debug = 1 # global_debug = 0: no output from multiples # 1: minimal output # 2: debugging output # 3: even more output print('') print('multiples_code.neighbor_veto =', \ multiples_code.neighbor_veto) print('multiples_code.neighbor_perturbation_limit =', \ multiples_code.neighbor_perturbation_limit) print('multiples_code.retain_binary_apocenter =', \ multiples_code.retain_binary_apocenter) print('multiples_code.wide_perturbation_limit =', \ multiples_code.wide_perturbation_limit) # Advance the system. E0 = print_diagnostics(multiples_code) multiples_code.evolve_model(t_end) print_diagnostics(multiples_code, E0) gravity.stop() kep.stop() stop_smalln() if __name__ in ('__main__'): N = 100 t_end = 10.0 | nbody_system.time integrate_system(N, t_end) #, 42)
3,322
27.895652
72
py
amuse
amuse-main/examples/textbook/gravity_gravity.py
#from __future__ import print_function import numpy from amuse.units import units from amuse.units import quantities from amuse.units import constants from amuse.units import nbody_system from amuse.ext.bridge import bridge from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.ph4.interface import ph4 from amuse.community.fi.interface import Fi from amuse.community.bhtree.interface import BHTree from amuse.community.gadget2.interface import Gadget2 from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model from amuse.ext.galactics_model import new_galactics_model from amuse.lab import new_powerlaw_mass_distribution def make_king_model_cluster(nbodycode, N, W0, Mcluster, Rcluster, parameters = []): converter=nbody_system.nbody_to_si(Mcluster,Rcluster) bodies=new_king_model(N,W0,convert_nbody=converter) code=nbodycode(converter) for name,value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(bodies) return code from prepare_figure import single_frame from distinct_colours import get_distinct from matplotlib.colors import LogNorm def plot_galaxy_and_stars(galaxy, stars): colors = get_distinct(3) single_frame('X [pc]', 'Y [pc]') xlim = 60 pyplot.xlim(-xlim, xlim) pyplot.ylim(-xlim, xlim) ax = pyplot.gca() import numpy as np import pandas as pd from scipy import stats, integrate import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) p = galaxy.select(lambda x: x<60|units.parsec,["x"]) p = p.select(lambda x: x>-60|units.parsec,["x"]) p = p.select(lambda y: y<60|units.parsec,["y"]) p = p.select(lambda y: y>-60|units.parsec,["y"]) x = p.x.value_in(units.parsec) y = p.y.value_in(units.parsec) sns.kdeplot(x, y, ax=ax) m = 100*numpy.sqrt(stars.mass/stars.mass.max()) pyplot.scatter(stars.x.value_in(units.parsec), stars.y.value_in(units.parsec), c=colors[0], s=m, lw=0) # pyplot.show() pyplot.savefig("Fujii_Comparison_Figure") from amuse.lab import new_plummer_model def evolve_cluster_in_galaxy(N, W0, Rinit, tend, timestep, M, R): R_galaxy=0.1 | units.kpc M_galaxy=1.6e10 | units.MSun converter=nbody_system.nbody_to_si(M_galaxy, R_galaxy) galaxy=new_plummer_model(10000,convert_nbody=converter) print("com:", galaxy.center_of_mass().in_(units.kpc)) print("comv:", galaxy.center_of_mass_velocity().in_(units.kms)) print(len(galaxy)) galaxy_code = BHTree(converter, number_of_workers=2) galaxy_code.parameters.epsilon_squared = (0.01 | units.kpc)**2 channe_to_galaxy = galaxy_code.particles.new_channel_to(galaxy) channe_to_galaxy.copy() galaxy_code.particles.add_particles(galaxy) inner_stars = galaxy.select(lambda r: r.length()<Rinit,["position"]) Minner = inner_stars.mass.sum() print("Minner=", Minner.in_(units.MSun)) print("Ninner=", len(inner_stars)) vc_inner = (constants.G*Minner/Rinit).sqrt() converter=nbody_system.nbody_to_si(Mcluster,Rcluster) stars=new_king_model(N,W0,convert_nbody=converter) masses = new_powerlaw_mass_distribution(N, 0.1|units.MSun, 100|units.MSun, -2.35) stars.mass = masses stars.scale_to_standard(converter) stars.x += Rinit stars.vy += 0.8*vc_inner cluster_code=ph4(converter, number_of_workers=2) cluster_code.particles.add_particles(stars) channel_to_stars=cluster_code.particles.new_channel_to(stars) system=bridge(verbose=False) system.add_system(cluster_code, (galaxy_code,)) system.add_system(galaxy_code, (cluster_code,)) system.timestep = 0.1*timestep times = quantities.arange(0|units.Myr, tend, timestep) for i,t in enumerate(times): print("Time=", t.in_(units.Myr)) channe_to_galaxy.copy() channel_to_stars.copy() inner_stars = galaxy.select(lambda r: r.length()<Rinit,["position"]) print("Minner=", inner_stars.mass.sum().in_(units.MSun)) system.evolve_model(t,timestep=timestep) plot_galaxy_and_stars(galaxy, stars) galaxy_code.stop() cluster_code.stop() if __name__ == "__main__": N=1024 W0 = 3 Rinit=50. | units.parsec timestep = 0.1 | units.Myr # endtime = 1.8| units.Myr # endtime = 1.4| units.Myr endtime = 2.35| units.Myr Mcluster = 5.e4 | units.MSun Rcluster = 0.8 | units.parsec evolve_cluster_in_galaxy(N, W0, Rinit, endtime, timestep, Mcluster, Rcluster)
4,555
34.874016
106
py
amuse
amuse-main/examples/textbook/hydro_give_or_take.py
import numpy from amuse.lab import * from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere def hydro_sink_particles(sinks, gas): removed_particles = Particles() for s in sinks: xs,ys,zs=s.x,s.y,s.z radius_squared = s.sink_radius**2 #print "R=", s.key, numpy.sqrt(radius_squared).in_(units.AU) insink=gas.select_array(lambda x,y,z: (x-xs)**2+(y-ys)**2+(z-zs)**2 < radius_squared,['x','y','z']) if len(insink)>0: cm=s.position*s.mass p=s.velocity*s.mass s.mass+=insink.total_mass() s.position=(cm+insink.center_of_mass()*insink.total_mass())/s.mass s.velocity=(p+insink.total_momentum())/s.mass removed_particles.add_particles(insink) return removed_particles def new_sph_particles_from_stellar_wind(stars, mgas): new_sph=datamodel.Particles(0) for si in stars: Ngas = int(-si.Mwind/mgas) if Ngas==0: continue Mgas = mgas*Ngas si.Mwind += Mgas si.mass -= Mgas add=datamodel.Particles(Ngas) add.mass = mgas add.h_smooth=0. | units.parsec dx,dy,dz=uniform_unit_sphere(Ngas).make_xyz() add.x=si.x+(dx * si.wind_radius) add.y=si.y+(dy * si.wind_radius) add.z=si.z+(dz * si.wind_radius) for ri in range(len(add)): r = add[ri].position-si.position r = r/r.length() v_wind = (constants.G*si.mass/(add[ri].position-si.position).length()).sqrt() add[ri].u= 0.5 * (v_wind)**2 add[ri].vx=si.vx + r[0]*si.terminal_wind_velocity add[ri].vy=si.vy + r[1]*si.terminal_wind_velocity add[ri].vz=si.vz + r[2]*si.terminal_wind_velocity new_sph.add_particles(add) return new_sph def v_terminal_teff(star): t4=(numpy.log10(star.temperature.value_in(units.K))-4.).clip(0.,1.) return (30 | units.km/units.s) + ((4000 | units.km/units.s)*t4) def new_hydro_code(hydro_code, dt, converter): hydro = hydro_code(converter, redirection="none") hydro.parameters.use_hydro_flag=True hydro.parameters.timestep=dt return hydro def remove_gas(gas, rremove): escaped_gas = Particles() if len(gas)>=1: # escaped_gas = gas.select_array(lambda r: r.length()>rremove,["position"]) # escaped_gas = gas[gas.position.length()>rremove].as_set() radius_squared = rremove**2 escaped_gas=gas.select_array(lambda x,y,z: (x**2+y**2+z**2) >= radius_squared,['x','y','z']) # print len(escaped_gas), escaped_gas.position.length() return escaped_gas def main(filename): stars = Particles(2) stars.mass = (1.924785833858, 1.0) | units.MSun # age=1494.4Myr separation = 10|units.AU vc = numpy.sqrt(constants.G*stars.mass.sum()/separation) stars[0].position = (1, 0, 0) * separation stars[0].velocity = (0, 1, 0) * vc stars[1].position = (0, 0, 0) | units.AU stars[1].velocity = (0, 0, 0) | units.kms stars.move_to_center() dt = 1|units.day stars.dmdt = [-0.11, 0.0] |units.MSun/units.Myr stars.temperature = [3309.6, 5672.25] | units.K stars.terminal_wind_velocity=v_terminal_teff(stars) stars.Mwind = 0.0|units.MSun stars.radius = [0.992, 0.00434665] |units.AU stars.wind_radius = [1, 0] * stars.radius R_BH = 2*constants.G*stars[1].mass/stars[0].terminal_wind_velocity**2 print("Bondi Hoyle accretion radius:", R_BH) stars.sink_radius = [0, 1] * R_BH #print "stars R=", stars.key, stars.sink_radius mgas = 0.1*abs(stars.dmdt.sum()*dt) converter=nbody_system.nbody_to_si(1|units.MSun, 1|units.AU) gas = Particles(0) gas.mass = mgas gas.position = (0,0,0)|units.AU gas.velocity = (0,0,0)|units.kms gas.u = 0 | units.m**2 * units.s**-2 gas.h_smooth= 1*units.RSun hydro = new_hydro_code(Fi, dt, converter) hydro.gas_particles.add_particles(gas) hydro.dm_particles.add_particles(stars) hydro_to_framework = hydro.gas_particles.new_channel_to(gas, attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "u", "rho", "h_smooth"]) generated_gas = Particles() accreted_gas = Particles() escaped_gas = Particles() dt_snap = 1|units.yr t_snap = dt_snap while hydro.model_time < 10000|units.yr: time = hydro.model_time stars.Mwind += stars.dmdt*dt accreted = hydro_sink_particles(stars, gas) if len(accreted)>0: print("N accreted:", time.in_(units.yr), len(accreted), \ "m=", accreted.mass.sum().in_(units.MSun)) accreted_gas.add_particles(accreted.copy()) gas.remove_particles(accreted) hydro.gas_particles.remove_particles(accreted) escaped = remove_gas(gas, 5*separation) if len(escaped): print("N escaped:", len(escaped)) escaped_gas.add_particles(escaped.copy()) gas.remove_particles(escaped) hydro.gas_particles.remove_particles(escaped) new_sph = new_sph_particles_from_stellar_wind(stars, mgas) if len(new_sph)>0: #print "N wind:", len(new_sph) generated_gas.add_particles(new_sph.copy()) gas.add_particles(new_sph) hydro.gas_particles.add_particles(new_sph) if len(gas)>100: #gas.synchronize_to(hydro.gas_particles) hydro.evolve_model(hydro.model_time+dt) hydro_to_framework.copy() if time>t_snap: t_snap += dt_snap write_set_to_file(gas, filename, 'hdf5') print("time=", hydro.model_time, "Ngas=", len(gas), \ mgas*len(gas)) print("T=", time, "M=", stars[0].mass, stars[1].mass) print("Gas = ", len(generated_gas), len(accreted_gas), \ len(escaped_gas)) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "hydro_outflow.h5", help="output filename [hydro.hdf5]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.AU, units.Myr], precision = 14, prefix = "", separator = " [", suffix = "]") main(o.filename)
6,603
37.847059
109
py
amuse
amuse-main/examples/textbook/merge_two_galaxies.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.galactics_model import new_galactics_model from prepare_figure import single_frame def make_plot(disk1, disk2, filename): x_label = "X [kpc]" y_label = "Y [kpc]" figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=14) from distinct_colours import get_distinct c = get_distinct(2) pyplot.xlim(-300, 300) pyplot.ylim(-300, 300) pyplot.scatter(disk1.x.value_in(units.kpc), disk1.y.value_in(units.kpc), c=c[0], alpha=1, s=1, lw=0) pyplot.scatter(disk2.x.value_in(units.kpc), disk2.y.value_in(units.kpc), c=c[1], alpha=1, s=1, lw=0) pyplot.savefig(filename) def make_galaxies(M_galaxy, R_galaxy, n_halo, n_bulge, n_disk): converter=nbody_system.nbody_to_si(M_galaxy, R_galaxy) galaxy1 = new_galactics_model(n_halo, converter, #do_scale = True, bulge_number_of_particles=n_bulge, disk_number_of_particles=n_disk) galaxy2 = Particles(len(galaxy1)) galaxy2.mass = galaxy1.mass galaxy2.position = galaxy1.position galaxy2.velocity = galaxy1.velocity galaxy1.rotate(0., numpy.pi/2, numpy.pi/4) galaxy1.position += [100.0, 100, 0] | units.kpc # galaxy1.velocity += [-3000.0, 0.0, -3000.0] | units.km/units.s galaxy1.velocity += [-10.0, 0.0, -10.0] | units.km/units.s galaxy2.rotate(numpy.pi/4, numpy.pi/4, 0.0) galaxy2.position -= [100.0, 0, 0] | units.kpc galaxy2.velocity -= [0.0, 0.0, 0] | units.km/units.s return galaxy1, galaxy2, converter def simulate_merger(galaxy1, galaxy2, converter, n_halo, t_end): converter = nbody_system.nbody_to_si(1.0e12|units.MSun, 100|units.kpc) dynamics = Gadget2(converter, number_of_workers=4) dynamics.parameters.epsilon_squared = (100 | units.parsec)**2 set1 = dynamics.particles.add_particles(galaxy1) set2 = dynamics.particles.add_particles(galaxy2) dynamics.particles.move_to_center() disk1 = set1[:n_halo] disk2 = set2[:n_halo] make_plot(disk1, disk2, "Galaxy_merger_t0Myr") dynamics.evolve_model(t_end) make_plot(disk1, disk2, "Galaxy_merger_t"+str(t_end.value_in(units.Myr))+"Myr") dynamics.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="M_galaxy", default = 1.0e12 | units.MSun, help="Galaxy mass [%default]") result.add_option("-R", unit=units.kpc, dest="R_galaxy", default = 10 | units.kpc, help="Galaxy size [%default]") result.add_option("--n_bulge", dest="n_bulge", default = 10000, help="number of stars in the bulge [%default]") result.add_option("--n_disk", dest="n_disk", default = 10000, help="number of stars in the disk [%default]") result.add_option("--n_halo", dest="n_halo", default = 20000, help="number of stars in the halo [%default]") result.add_option("--t_end", unit=units.Myr, dest="t_end", default = 200|units.Myr, help="End of the simulation [%default]") return result if __name__ == '__main__': o, arguments = new_option_parser().parse_args() galaxy1, galaxy2, converter = make_galaxies(o.M_galaxy, o.R_galaxy, o.n_halo, o.n_bulge, o.n_disk) simulate_merger(galaxy1, galaxy2, converter, o.n_halo, o.t_end)
3,708
41.632184
78
py
amuse
amuse-main/examples/textbook/helium_star.py
""" Creates a helium burning star from the inner shells of a main sequence star. """ from __future__ import print_function from amuse.units import units from amuse.datamodel import Particle from amuse.community.mesa.interface import MESA from matplotlib import pyplot from amuse.plot import loglog, xlabel, ylabel, scatter def main(): temperatures_original = [] | units.K luminosities_original = [] | units.LSun temperatures_helium = [] | units.K luminosities_helium = [] | units.LSun star = Particle() star.mass = 12.0 | units.MSun stop_radius = 90 | units.RSun # Avoid the model going through a blue loop stellar_evolution = MESA() se_star = stellar_evolution.particles.add_particle(star) # This method is only really useful if you need a helium star from an exisiting model # With the new interface you can do: stellar_evolution.pure_he_stars.add_particles(star) # Which is much faster print("Evolving a", star.mass, "star with", stellar_evolution.__class__.__name__, end=' ') print("until its radius exceeds", stop_radius) while (se_star.radius < stop_radius): se_star.evolve_one_step() temperatures_original.append(se_star.temperature) luminosities_original.append(se_star.luminosity) ###BOOKLISTSTART1### number_of_zones = se_star.get_number_of_zones() composition = se_star.get_chemical_abundance_profiles() index = (composition[0] > 1.0e-9).nonzero()[0][0] # first zone with X > 1.0e-9 print("Creating helium star, from the inner", index, "(out of", str(number_of_zones)+") shells.") helium_star = stellar_evolution.new_particle_from_model(dict( mass = (se_star.get_cumulative_mass_profile() * se_star.mass)[:index], radius = se_star.get_radius_profile()[:index], rho = se_star.get_density_profile()[:index], temperature = se_star.get_temperature_profile()[:index], luminosity = se_star.get_luminosity_profile()[:index], X_H = composition[0][:index], X_He = composition[1][:index] + composition[2][:index], X_C = composition[3][:index], X_N = composition[4][:index], X_O = composition[5][:index], X_Ne = composition[6][:index], X_Mg = composition[7][:index], X_Si = composition[7][:index]*0.0, X_Fe = composition[7][:index]*0.0), 0.0 | units.Myr) ###BOOKLISTSTOP1### print("\nStar properties before helium star evolution:\n", stellar_evolution.particles) for i in range(1000): helium_star.evolve_one_step() temperatures_helium.append(helium_star.temperature) luminosities_helium.append(helium_star.luminosity) print("\nStar properties after helium star evolution:\n", stellar_evolution.particles) stellar_evolution.stop() return temperatures_original, luminosities_original, \ temperatures_helium, luminosities_helium from distinct_colours import get_distinct from prepare_figure import single_frame def plot_tracks(temperatures_original, luminosities_original, temperatures_helium, luminosities_helium): x_label = "T [K]" y_label = "L [$L_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) colors = get_distinct(2) loglog(temperatures_original, luminosities_original, label='progenitor', c=colors[0]) loglog(temperatures_helium, luminosities_helium, label='helium star', c=colors[1]) scatter(temperatures_helium[-1], luminosities_helium[-1], marker='*', s=400, c=colors[1]) xlabel('Effective Temperature') ylabel('Luminosity') pyplot.xlim(1.0e5, 4000) pyplot.ylim(1.0,1.0e5) pyplot.legend(loc=4, fontsize=24) save_file = 'HertzsprungRussel_HeliumStar.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() if __name__ == "__main__": temperatures_original, luminosities_original, \ temperatures_helium, luminosities_helium = main() plot_tracks(temperatures_original, luminosities_original, temperatures_helium, luminosities_helium)
4,261
38.831776
92
py
amuse
amuse-main/examples/textbook/hydro_sink_particles.py
from amuse.lab import * def hydro_sink_particles(sinks, gas): removed_particles = Particles() for s in sinks: xs,ys,zs=s.x,s.y,s.z radius_squared = s.radius**2 insink=gas.select_array(lambda x,y,z: (x-xs)**2+(y-ys)**2+(z-zs)**2 < radius_squared,['x','y','z']) if len(insink)==0: return insink cm=s.position*s.mass p=s.velocity*s.mass s.mass+=insink.total_mass() s.position=(cm+insink.center_of_mass()*insink.total_mass())/s.mass s.velocity=(p+insink.total_momentum())/s.mass removed_particles.add_particles(insink) return removed_particles def main(N, Mtot, Rvir, rsink): converter=nbody_system.nbody_to_si(Mtot, Rvir) bodies = new_plummer_gas_model(N, convert_nbody=converter) sink = Particles(1) sink.mass = 0 | units.MSun sink.radius = rsink sink.position = (0, 0, 0) | units.AU sink.velocity = (0, 0, 0) | units.kms accreted = hydro_sink_particles(sink, bodies) print("Particles in sink: N=", len(accreted), " M=", sink.mass) print("sink position=", sink.position.as_quantity_in(units.AU)) print("sink velocity=", sink.velocity.as_quantity_in(units.kms)) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of sph particles [100]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1|units.MSun, help="Mass of molcular cloud [%default]") result.add_option("-R", unit=units.AU, dest="Rvir", type="float", default = 100|units.AU, help="Radius of cloud [%default]") result.add_option("-r", unit=units.AU, dest="rsink", type="float", default = 100|units.AU, help="Radius of the sink [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,115
37.472727
109
py
amuse
amuse-main/examples/textbook/stellar_isochrone.py
""" Evolve a population of N stars. Initial mass function between Mmin and Mmax with stellar evolution for metallicity z. """ import sys import numpy from amuse.lab import * from matplotlib import pyplot from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def _get_stellar_temperature_and_luminosity(stars, C, z=0.02, t_end=100|units.Myr, write=False): if C.find("SeBa") >= 0 : stellar = SeBa() filename = "Stellar_SeBa.h5" if C.find("SSE") >= 0 : stellar = SSE() filename = "Stellar_SSE.h5" if C.find("MESA") >= 0 : stellar = MESA() filename = "Stellar_MESA.h5" if C.find("EVtwin") >= 0 : stellar = SeBa() filename = "Stellar_EVtwin.h5" stellar.parameters.metallicity = z stellar.particles.add_particles(stars) for si in stellar.particles: try: si.evolve_for(t_end) except: print("Failed to evolve star: m=", si.mass.in_(units.MSun)) if write: write_set_to_file(stellar.particles, filename, 'hdf5') stellar.stop() def get_stellar_temperature_and_luminosity(stars, C, z=0.02, t_end=100|units.Myr, write=False): if C.find("SeBa") >= 0 : filename = "Stellar_SeBa.h5" stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particles(stars) channel_to_framework = stellar.particles.new_channel_to(stars) stellar.evolve_model(t_end) channel_to_framework.copy_attributes(["radius", "temperature", "luminosity"]) stellar.stop() else: if C.find("MESA") >= 0 : filename = "Stellar_MESA.h5" if C.find("EVtwin") >= 0 : filename = "Stellar_EVtwin.h5" for si in stars: stellar = MESA() stellar.parameters.metallicity = z stellar.particles.add_particle(si) channel_to_framework = stellar.particles.new_channel_to(stars) try: stellar.evolve_model(t_end) channel_to_framework.copy_attributes(["radius", "temperature", "luminosity"]) print("Successfully evolved star: m=", si.mass.in_(units.MSun)) except: print("Failed to evolve star: m=", si.mass.in_(units.MSun)) stellar.stop() if write: write_set_to_file(stars, filename, 'hdf5') def plot_HRD(filename, color): stars = read_set_from_file(filename, 'hdf5') T = stars.temperature.value_in(units.K) L = stars.luminosity.value_in(units.LSun) R = stars.radius.value_in(units.RSun) R = 80*numpy.sqrt(R) pyplot.scatter(T, L, c=color, lw=0, s=R) def main(N, t_end, z, C="SeBa", plot=False): if "SeBa" not in C: x_label = "T [K]" y_label = "L [L$_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) color = get_distinct(4) pyplot.xlim(1.e+5, 1.e+3) pyplot.ylim(1.e-4, 1.e+4) filename = "Stellar_"+"SeBa"+".h5" plot_HRD(filename, color[0]) filename = "Stellar_"+C+".h5" plot_HRD(filename, color[1]) save_file = 'HRD_N3000at4500Myr.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') elif not plot: numpy.random.seed(1) masses = new_salpeter_mass_distribution(N) stars = Particles(mass=masses) get_stellar_temperature_and_luminosity(stars, C=C, z=z, t_end=t_end, write=True) else: x_label = "T [K]" y_label = "L [L$_\odot$]" figure = single_frame(x_label, y_label, logx=True, logy=True, xsize=14, ysize=10) color = get_distinct(4) pyplot.xlim(1.e+5, 1.e+3) pyplot.ylim(1.e-4, 1.e+4) filename = "Stellar_"+C+".h5" plot_HRD(filename, color[0]) save_file = 'HRD_N3000at4500Myr.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-C", dest="C", default = "SeBa", help="stellar evolution code [SeBa]") result.add_option("-N", dest="N", type="int",default = 3000, help="number of stars [3000]") result.add_option("-t", dest="t_end", unit=units.Myr, type="float", default = 4500.0|units.Myr, help="end time of the simulation [4500] Myr") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") result.add_option("-p", dest="plot", action="store_true", default = False, help="plot") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,316
35.170068
79
py
amuse
amuse-main/examples/textbook/plot_hydro_density_distributions.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.plot import sph_particles_plot from prepare_figure import figure_frame from distinct_colours import get_distinct ###BOOKLISTSTART1### def stellar_model(N, M, t=0.0|units.Myr): star = Particle(mass=M) stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) print("Evolving", star.mass, "to t=", t.in_(units.Myr)) stellar_evolution.evolve_model(t) print("Stellar type:", stellar_evolution.particles.stellar_type.number) print("Creating SPH particles from the (1D) stellar evolution model") sph_particles = convert_stellar_model_to_SPH(se_star, N).gas_particles stellar_evolution.stop() return sph_particles ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def plot_ZAMS_stellar_model(N, M): sph_particles = stellar_model(N, M) x_label = "x [R$_\odot$]" y_label = "y [R$_\odot$]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-2, 2, -2, 2)|units.RSun) ax.set_facecolor('white') save_file = 'stellar_2MSunZAMS_projected.png' pyplot.savefig(save_file) print('Saved figure in file', save_file, '\n') pyplot.show() ###BOOKLISTSTOP2### ###BOOKLISTSTART3### from amuse.ext.molecular_cloud import molecular_cloud def GMC_model(N, M, R): converter = nbody_system.nbody_to_si(M, R) sph_particles = molecular_cloud(targetN=N, convert_nbody=converter).result sph = Fi(converter) sph.gas_particles.add_particle(sph_particles) sph.evolve_model(1|units.day) ch = sph.gas_particles.new_channel_to(sph_particles) ch.copy() sph.stop() return sph_particles ###BOOKLISTSTOP3### def plot_GMC_model(N, M, R): sph_particles = GMC_model(N, M, R) x_label = "x [pc]" y_label = "y [pc]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-20, 20, -20, 20)|units.parsec) ax.set_facecolor('white') file = 'molecular_cloud_projected.png' pyplot.savefig(file) print('Saved figure in file', file) if __name__ in ("__main__","__plot__"): N = 10000 M = 10000. | units.MSun R = 10. | units.parsec M = 2 | units.MSun print('') plot_ZAMS_stellar_model(N, M) plot_GMC_model(N, M, R) print('')
2,543
31.202532
78
py
amuse
amuse-main/examples/textbook/three_body_bridge_order4m4.py
import numpy from amuse.lab import * from amuse.ext.composition_methods import * from amuse.couple import bridge from amuse.ext.solarsystem import new_solar_system def new_system_of_sun_and_earth(): stars = Particles(3) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) moon = stars[2] moon.mass = units.kg(7.3477e22 ) moon.radius = units.km(1737.10) moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity return stars def main(): filename = "SunAndEarthAndMoon_TBB.h5" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] moon = ss[2] print(moon) converter=nbody_system.nbody_to_si(star.mass, 1|units.AU) star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) moon_gravity = ph4(converter) moon_gravity.particles.add_particle(moon) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss) write_set_to_file(ss.savepoint(0.0|units.Myr), filename, 'hdf5', append_to_file=False, version='2') gravity = bridge.Bridge(use_threading=False, method=SPLIT_4TH_S_M4) ####gravity = bridge.Bridge(use_threading=False, method=SPLIT_6TH_SS_M13) gravity.add_system(star_gravity, (planet_gravity,moon_gravity) ) gravity.add_system(planet_gravity, (star_gravity,moon_gravity) ) gravity.add_system(moon_gravity, (star_gravity,planet_gravity) ) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init DDE_max = 0 gravity.timestep = 1|units.day time = zero dt = 30|units.day t_end = 100 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() channel_from_moon_to_framework.copy() write_set_to_file(ss.savepoint(time), filename, 'hdf5', version='2') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot DDE = (Etot_prev-Etot)/Etot DDE_max = max(abs(DDE_max), abs(DDE)) print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", DDE, "dde_min=", DDE_max) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
3,114
32.858696
103
py
amuse
amuse-main/examples/textbook/plot_solar_cluster.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import sys import numpy import matplotlib matplotlib.use('Agg') from matplotlib import pyplot #from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store from optparse import OptionParser from amuse.units.optparse import OptionParser from time import sleep from distinct_colours import get_distinct def plot_single_image(particles, lim): # nullfmt = NullFormatter() # no labels left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left+width+0.05 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] colors = get_distinct(4) # pyplot.rcParams.update({'font.size': 30}) fig = pyplot.figure(figsize=(12,12)) # ax = pyplot.gca() # ax.minorticks_on() # switch on the minor ticks # ax.locator_params(nbins=3) time = particles.get_timestamp() # pyplot.title("Cluster at t="+str(time.in_(units.Gyr))) xy = pyplot.axes(rect_scatter) xy.text(11,11, "Galaxy at t="+str(time.in_(units.Gyr)), ha='left', va='bottom') xz = pyplot.axes(rect_histx) yz = pyplot.axes(rect_histy) xy.set_xlabel("X [kpc]") xy.set_ylabel("Y [kpc]") xz.set_ylabel("Z [kpc]") yz.set_xlabel("Z [kpc]") xy.scatter([0.0], [0.0], s=200, c=colors[1], marker='+') xz.scatter([0.0], [0.0], s=200, c=colors[1], marker='+') yz.scatter([0.0], [0.0], s=200, c=colors[1], marker='+') xy.scatter([8.5], [0.0], s=100, c=colors[2], marker='o', lw=0) xz.scatter([8.5], [0.0], s=100, c=colors[2], marker='o', lw=0) yz.scatter([0.0], [0.0], s=100, c=colors[2], marker='o', lw=0) # axHistx.xaxis.set_major_formatter(nullfmt) # axHisty.yaxis.set_major_formatter(nullfmt) positions = particles.position x, y, z = positions.x.value_in(units.kpc), positions.y.value_in(units.kpc), positions.z.value_in(units.kpc) xy.scatter(x, y, c=colors[0], lw=0) xy.set_xlim( (-lim, lim) ) xy.set_ylim( (-lim, lim) ) xz.scatter(x, z, c=colors[0], lw=0) yz.scatter(z, y, c=colors[0], lw=0) xz.set_xlim( xy.get_xlim() ) # yz.set_xlim( (-0.2*lim, 0.2*lim) ) # yz.set_xlim( xy.get_xlim() ) yz.set_ylim( xy.get_xlim() ) yz.set_xlim( (-0.1*lim, 0.1*lim) ) xz.set_ylim( (-0.1*lim, 0.1*lim) ) # pyplot.show() # fig.savefig('test.png') fig.savefig('SolarSiblings_static_galaxy') # fig.savefig('test.eps') def main(filename, lim=-1|units.parsec, image_id=-1): if image_id<0: pyplot.ion() mc = read_set_from_file(filename, "hdf5") # particles time = 0 snapshot_id = 0 for si in mc.history: snapshot_id += 1 time = si.get_timestamp() print("Snapshot=", snapshot_id, time.in_(units.Gyr)) if image_id<0 or image_id == snapshot_id: m = 1 plot_single_image(si, lim.value_in(units.kpc)) if image_id == snapshot_id: break if image_id<0: pyplot.draw() pyplot.cla() def new_option_parser(): result = OptionParser() result.add_option("-f", dest="filename", default = "proto_solar_cluster.hdf5", help="output filename [%default]") result.add_option("-l", unit=units.parsec, dest="lim", type="float", default = 10|units.kpc, help="axis length [%default]") result.add_option("-i", dest="image_id", type="int", default = -1, help="image id [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,853
32.807018
111
py
amuse
amuse-main/examples/textbook/planetary_system.py
import math import numpy from amuse.lab import * from amuse.ext.protodisk import ProtoPlanetaryDisk from optparse import OptionParser from amuse.couple import bridge import make_planets_oligarch from amuse.ext.orbital_elements import orbital_elements_from_binary def calculate_orbital_elements(star, planet): p = Particles() p.add_particle(star) p.add_particle(planet) M, m, a, e, ta_out, outc_out, lan_out, aop_out \ = orbital_elements_from_binary(p, G=constants.G) return a, e from amuse.ext.orbital_elements import new_binary_from_orbital_elements def make_planetesimal_disk(Nplanetesimals): amin = 6.4|units.AU amax = 30|units.AU emax = 0.1 imax = 1 a = amin + (amax-amin)*numpy.random.random_sample(Nplanetesimals) e = emax*numpy.random.random_sample(Nplanetesimals) i = imax*numpy.random.random_sample(Nplanetesimals) ta = 0 # numpy.acos(np.random.uniform(0,2*numpy.pi,Nplanetesimals)) loan = 0 aof = 0 mp = 0.1 | units.MEarth planetesimals = Particles(Nplanetesimals) for i, pi in enumerate(planetesimals): b = new_binary_from_orbital_elements(Mstar, mp, a[i], e[i], ta, inc[i], loan, aof, G=constant.G) pi.mass = mp pi.position = b[1].position pi.velocity = b[1].velocity return planetesimals def initialize_star_and_planetary_system(Mstar, Ndisk, Mdisk, Rmin, Rmax): converter=nbody_system.nbody_to_si(Mstar, Rmin) disk_massfraction = Mdisk/Mstar disk = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=Rmin.value_in(units.AU), Rmax=Rmax.value_in(units.AU), q_out=1.0, discfraction=disk_massfraction).result #disk.h_smooth= Rmin/Ndisk star = Particles(1) star.mass = Mstar star.radius = 1| units.RSun star.position = (0,0,0) | units.AU star.velocity = (0,0,0) | units.kms planets = make_planets_oligarch.new_system(Mstar, star.radius, Rmin, Rmax, Mdisk) star.add_particles(planets[0].planets) print(star) return star, disk def main(Mstar, Ndisk, fmdisk, Rmin, Rmax, t_end, n_steps): Mdisk = fmdisk * Mstar converter=nbody_system.nbody_to_si(Mstar, Rmax) star_and_planets, disk \ = initialize_star_and_planetary_system(Mstar, Ndisk, Mdisk, Rmin, Rmax) hydro=Fi(converter) hydro.parameters.use_hydro_flag=True hydro.parameters.radiation_flag=False hydro.parameters.self_gravity_flag=True hydro.parameters.gamma=1. hydro.parameters.isothermal_flag=True hydro.parameters.integrate_entropy_flag=False hydro.parameters.timestep=0.125 | units.yr hydro.gas_particles.add_particles(disk) gravity = Hermite(converter) gravity.particles.add_particles(star_and_planets) planet_attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "semimajor_axis", "eccentricity"] disk_attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "u", "rho", "h_smooth"] channel_to_planets = gravity.particles.new_channel_to(star_and_planets) channel_from_hydro_to_framework \ = hydro.particles.new_channel_to(disk, attributes=disk_attributes) channel_from_hydro_to_framework.copy() moving_bodies = ParticlesSuperset([star_and_planets, disk]) moving_bodies.move_to_center() index = 0 filename = "planetary_system_i{0:04}.amuse".format(index) write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes, overwrite_file=True) write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes, append_to_file=True) gravity_hydro = bridge.Bridge(use_threading=False) gravity_hydro.add_system(gravity, (hydro,) ) gravity_hydro.add_system(hydro, (gravity,) ) Etot_init = gravity_hydro.kinetic_energy + gravity_hydro.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit dt = t_end/float(n_steps) gravity_hydro.timestep = dt/10. while time < t_end: time += dt gravity_hydro.evolve_model(time) Etot_prev_se = gravity_hydro.kinetic_energy \ + gravity_hydro.potential_energy channel_to_planets.copy() channel_from_hydro_to_framework.copy() for pi in star_and_planets[1:]: a, e = calculate_orbital_elements(star_and_planets[0], pi) pi.semimajor_axis = a pi.eccentricity = e index += 1 filename = "planetary_system_i{0:04}.amuse".format(index) write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes, overwrite_file=True) write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes, append_to_file=True) Ekin = gravity_hydro.kinetic_energy Epot = gravity_hydro.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity_hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="n_steps", type="float", default = 100, help="number of diagnostics time steps [10]") result.add_option("--Ndisk", dest="Ndisk", type="int",default = 100000, help="number of disk particles [100]") result.add_option("--Mstar", unit=units.MSun, dest="Mstar", type="float",default = 1.73|units.MSun, help="stellar mass [%default]") result.add_option("--fmdisk", dest="fmdisk", type="float",default = 0.01, help="disk mass [%default]") result.add_option("--Rmin", unit=units.AU, dest="Rmin", type="float",default = 1.0|units.AU, help="minimal disk radius [%default]") result.add_option("--Rmax", unit=units.AU, dest="Rmax", type="float",default = 100|units.AU, help="maximal disk radius [%defualt]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 1000.0|units.yr, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
6,786
37.129213
100
py
amuse
amuse-main/examples/textbook/gravity_stellar_eventdriven.py
import numpy from amuse.lab import * from amuse.io import store from amuse.community.seba.interface import SeBa def merge_two_stars(bodies, particles_in_encounter): com_pos = particles_in_encounter.center_of_mass() com_vel = particles_in_encounter.center_of_mass_velocity() new_particle=Particles(1) new_particle.mass = particles_in_encounter.total_mass() new_particle.age = min(particles_in_encounter.age) \ * max(particles_in_encounter.mass)/new_particle.mass new_particle.position = com_pos new_particle.velocity = com_vel new_particle.radius = 0 | units.RSun bodies.add_particles(new_particle) bodies.remove_particles(particles_in_encounter) def resolve_collision(collision_detection, gravity, stellar, bodies): if collision_detection.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print("At time=", gravity.model_time.in_(units.Myr), \ "number of encounters=", len(collision_detection.particles(0))) Nenc = 0 for ci in range(len(collision_detection.particles(0))): particles_in_encounter \ = Particles(particles=[collision_detection.particles(0)[ci], collision_detection.particles(1)[ci]]) particles_in_encounter \ = particles_in_encounter.get_intersecting_subset_in(bodies) merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) Nenc += 1 print("Resolve encounter Number:", Nenc) dE_coll = E_coll - (gravity.kinetic_energy + gravity.potential_energy) print("dE_coll =", dE_coll, "N_enc=", Nenc) ###BOOKLISTSTART3### def resolve_supernova(supernova_detection, bodies, time): if supernova_detection.is_set(): print("At time=", time.in_(units.Myr), \ len(supernova_detection.particles(0)), 'supernova(e) detected') Nsn = 0 for ci in range(len(supernova_detection.particles(0))): print(supernova_detection.particles(0)) particles_in_supernova \ = Particles(particles=supernova_detection.particles(0)) natal_kick_x = particles_in_supernova.natal_kick_x natal_kick_y = particles_in_supernova.natal_kick_y natal_kick_z = particles_in_supernova.natal_kick_z particles_in_supernova \ = particles_in_supernova.get_intersecting_subset_in(bodies) particles_in_supernova.vx += natal_kick_x particles_in_supernova.vy += natal_kick_y particles_in_supernova.vz += natal_kick_z Nsn += 1 print('Resolved', Nsn, 'supernova(e)') ###BOOKLISTSTOP3### def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): numpy.random.seed(1) ###BOOKLISTSTART1### masses = new_salpeter_mass_distribution(N, Mmin, Mmax) Mtot_init = masses.sum() converter=nbody_system.nbody_to_si(Mtot_init,Rvir) bodies = new_king_model(N, W0,convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) collision_detection = gravity.stopping_conditions.collision_detection collision_detection.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) stellar.evolve_model(0|units.Myr) supernova_detection = stellar.stopping_conditions.supernova_detection supernova_detection.enable() channel_from_se = stellar.particles.new_channel_to(bodies) channel_from_gd = gravity.particles.new_channel_to(bodies) channel_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se.copy_attributes(["mass","radius", "age", "temperature", "luminosity"]) ###BOOKLISTSTOP1### write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nsn = 0 dE_coll = zero time = zero ###BOOKLISTSTART2### while time < t_end: dt_min = min(dt, stellar.particles.time_step.min()) print("Time steps:", dt.in_(units.Myr), dt_min.in_(units.Myr)) time += dt_min bodies.radius *= 1.e+5 channel_to_gd.copy_attributes(["mass", "radius", "vx", "vy", "vz"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) resolve_collision(collision_detection, gravity, stellar, bodies) channel_from_gd.copy() time = gravity.model_time E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) resolve_supernova(supernova_detection, bodies, time) channel_from_se.copy_attributes(["mass", "radius", "age", "temperature", "luminosity"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) ###BOOKLISTSTOP2### gravity.stop() stellar.stop() def print_diagnostics(time, Mtot, Etot, dE_dyn, dE_coll, dE_stellar): print("T=", time.in_(units.Myr), end=' ') print("M=", Mtot.in_(units.MSun), end=' ') print("E= ", Etot, end=' ') print("dE(dyn)=", dE_dyn/Etot, end=' ') print("dE(coll)=", dE_coll/Etot, end=' ') print("dE(se)=", dE_stellar/Etot) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "gravity_stellar.hdf5", help="output filename [%default]") result.add_option("-N", dest="N", type="int",default = 10, help="number of stars [%default]") result.add_option("--dt", unit=units.Myr, dest="dt", type="float",default = 1|units.Myr, help="output timesteps [%default]") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float",default = 100, help="maximal stellar mass [%default.value_in(units.MSun))]") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float",default = 10, help="minimal stellar mass [%default.value_in(units.MSun)]") result.add_option("-R", unit=units.parsec, dest="Rvir", type="float",default = 0.1, help="cluser virial radius [%default.value_in(units.parsec)]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 50.0, help="end time of the simulation [%default.value_in(units.Myr]") result.add_option("-W", dest="W0", type="float", default = 12.0, help="Dimension-less depth of the King potential (W0) [%default]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
7,592
41.183333
88
py
amuse
amuse-main/examples/textbook/plot_sstar_orbits.py
import os.path import math import numpy from amuse.lab import * from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.ext.evrard_test import uniform_unit_sphere import time from initialize_sstars import * from amuse.community.adaptb.interface import Adaptb from gravity_class import Gravity #from prepare_figure import single_frame, figure_frame, set_tickmarks #from distinct_colours import get_distinct def _plot_orbits(x, y, z): from matplotlib import pyplot, rc fig = pyplot.figure(figsize=(14,14)) font = {'size' : 30} rc('font', **font) pyplot.figaspect(1.0) pyplot.scatter(x[0].value_in(units.AU), y[0].value_in(units.AU), 200, lw=0) pyplot.plot(x.value_in(units.AU), y.value_in(units.AU), lw=2) pyplot.xlabel("$X [AU]$") pyplot.ylabel("$Y [AU]$") pyplot.xlim(-15000, 15000) pyplot.ylim(-30000, 10000) # pyplot.show() pyplot.savefig("SStars_1Jan2001_orbits") def plot_orbits(x, y, z): from matplotlib import pyplot, rc fig = pyplot.figure(figsize=(14,14)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) font = {'size' : 30} rc('font', **font) pyplot.figaspect(1.0) pyplot.scatter(x[0].value_in(units.AU), y[0].value_in(units.AU), 200, lw=0) pyplot.plot(x.value_in(units.AU), y.value_in(units.AU), lw=2) pyplot.xlabel("$X [AU]$") pyplot.ylabel("$Y [AU]$") pyplot.xlim(-10000, 10000) pyplot.ylim(-10000, 10000) # pyplot.show() pyplot.savefig("SStars_1Jan2001_orbits") def main(t_end=1, n_steps=1, filename=None): black_hole, stars = initialize_sstars(2001|units.yr, S_name, S_a_arcsec, S_ecc, S_inc, S_omra, S_Omega, S_tperi, S_Period) print("N=", len(stars)) gravity = Gravity(Mercury, [black_hole, stars]) model_time = gravity.model_time model_time = 0 | units.Myr dt_diag = t_end/float(n_steps) t_diag = model_time dt = dt_diag x = [] | units.AU y = [] | units.AU z = [] | units.AU while model_time < t_end: model_time += dt gravity.evolve_model(model_time) x.append(gravity.particles.x) y.append(gravity.particles.y) z.append(gravity.particles.z) gravity.stop() plot_orbits(x, y, z) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="n_steps", type="int", default = 100, help="number of diagnostics time steps [10]") result.add_option("-f", dest="filename", default = None, help="write output filename") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 500|units.yr, # dest="t_end", type="float", default = 1678|units.yr, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,020
32.566667
126
py
amuse
amuse-main/examples/textbook/merge_two_stars_sph_convergence.py
import sys import numpy from matplotlib import pyplot from amuse.lab import * from amuse.plot import plot from amuse.ext.sph_to_star import convert_SPH_to_stellar_model from prepare_figure import * from distinct_colours import get_distinct def return_evolved_star_hydro(mass, time, Nsph): star = Particle(mass=mass) stellar = EVtwin() star = stellar.particles.add_particle(star) stellar.evolve_model(time) Nsph = Nsph * int(mass.value_in(units.MSun)) star_in_sph = convert_stellar_model_to_SPH(star, Nsph).gas_particles stellar.stop() return star_in_sph def merge_two_stars_sph(Mprim, Msec, t_coll, Nsph, opening_angle): primary_in_sph = return_evolved_star_hydro(Mprim, t_coll, int(Nsph*Mprim/(1.|units.MSun))) # primary_in_sph = relax_sph_realization(primary_in_sph) secondary_in_sph = return_evolved_star_hydro(Msec, t_coll, int(Nsph*Msec/(1.|units.MSun))) # secondary_in_sph = relax_sph_realization(secondary_in_sph) R = primary_in_sph.x.max() + secondary_in_sph.x.max() M = primary_in_sph.mass.sum() + secondary_in_sph.mass.sum() secondary_in_sph.x += 0.8*R secondary_in_sph.y += 0.6*R secondary_in_sph.vx -= (constants.G*M/R).sqrt() converter=nbody_system.nbody_to_si(Mprim, 1.0|units.AU) hydro = Gadget2(converter, number_of_workers=4) # hydro = Fi(converter) hydro.parameters.opening_angle = opening_angle """ print "Opening criterion:", hydro.parameters.opening_angle print "Opening criterion:", hydro.get_gdgop() print "Opening criterion:", hydro.parameters.opening_angle print "Opening criterion:", hydro.get_gdgop() """ hydro.gas_particles.add_particles(primary_in_sph) hydro.gas_particles.add_particles(secondary_in_sph) hydro.evolve_model(2.0|units.hour) hydro.gas_particles.new_channel_to(primary_in_sph).copy() hydro.gas_particles.new_channel_to(secondary_in_sph).copy() hydro.stop() return primary_in_sph, secondary_in_sph def relax_sph_realization(sph_star): dynamical_timescale = sph_star.dynamical_timescale() converter = nbody_system.nbody_to_si(dynamical_timescale, 1|units.RSun) hydro = Gadget2(converter, number_of_workers=2) hydro.gas_particles.add_particles(sph_star) to_hydro = sph_star.new_channel_to(hydro.gas_particles) to_framework = hydro.gas_particles.new_channel_to(sph_star) ts_factor = 2.5 t_end = ts_factor * sph_star.dynamical_timescale(mass_fraction=0.9) n_steps = ts_factor * 100 velocity_damp_factor = 1.0 - (ts_factor*2*numpy.pi)/n_steps dt = t_end/float(n_steps) time = 0|units.day while time < t_end: time += dt hydro.evolve_model(time) hydro.gas_particles.velocity = velocity_damp_factor * hydro.gas_particles.velocity to_framework.copy() hydro.stop() return sph_star def merge_and_plot_distribution(Mprim, Msec, t_coll, Nsph, opening_angle, c, label): p, s = merge_two_stars_sph(Mprim, Msec, t_coll, Nsph, opening_angle) merger = ParticlesSuperset([p, s]) com = merger.center_of_mass() merger.r = ((merger.x-com[0])**2 + (merger.y-com[1])**2 + (merger.z-com[2])**2).sqrt() merger = merger.sorted_by_attributes("r") n = [] m = 0 mi = 1.0*(Mprim+Msec).value_in(units.MSun)/len(merger) for i in range(len(merger.r)): m += mi n.append(m) pyplot.plot(merger.r.value_in(units.RSun), n, c=c, label=label) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mprim", type="float",default = 10|units.MSun, help="Mass of the primary star [%default] MSun") result.add_option("-m", unit=units.MSun, dest="Msec", type="float",default = 1|units.MSun, help="Mass of the secondary star [%default] MSun") result.add_option("-N", dest="Nsph", type="int",default = 100, help="Number of sph particles per MSun [%default]") result.add_option("-t", unit=units.Myr, dest="t_coll", type="float", default = 0.01|units.Myr, help="end time of the simulation [%default] Myr") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) pyplot.xlabel("R [R$_\odot$]") pyplot.ylabel("$M_{<r}$") ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) merge_and_plot_distribution(o.Mprim, o.Msec, o.t_coll, 10, 0.5, colors[0], "$N_{sph} = 10/M_\odot$") merge_and_plot_distribution(o.Mprim, o.Msec, o.t_coll, 100, 0.5, colors[1], "$N_{sph} = 100/M_\odot$") merge_and_plot_distribution(o.Mprim, o.Msec, o.t_coll, 1000, 0.5, colors[2], "$N_{sph} = 10^3/M_\odot$") merge_and_plot_distribution(o.Mprim, o.Msec, o.t_coll, 10000, 0.5, colors[3], "$N_{sph} = 10^4/M_\odot$") # pyplot.show() # pyplot.semilogx() pyplot.xlim(0, 20) pyplot.ylim(0, 12) pyplot.legend(loc=4, fontsize=24) pyplot.savefig("stellar_merger_convergence")
5,347
40.78125
109
py
amuse
amuse-main/examples/textbook/basic_multiples_si.py
import numpy from amuse.units import nbody_system, units, constants from amuse.ic.plummer import new_plummer_model from amuse.community.ph4.interface import ph4 from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples # Awkward syntax here because multiples needs a function that resets # and returns a small-N integrator. ###BOOKLISTSTART1### SMALLN = None def init_smalln(converter): global SMALLN SMALLN = SmallN(convert_nbody=converter) def new_smalln(): SMALLN.reset() return SMALLN ###BOOKLISTSTOP1### def stop_smalln(): global SMALLN SMALLN.stop() def print_diagnostics(grav, E0=None): # Simple diagnostics. ke = grav.kinetic_energy pe = grav.potential_energy Nmul, Nbin, Emul = grav.get_total_multiple_energy() print('') print('Time =', grav.get_time().in_(units.Myr)) print(' top-level kinetic energy =', ke) print(' top-level potential energy =', pe) print(' total top-level energy =', ke + pe) print(' ', Nmul, 'multiples,', 'total energy =', Emul) E = ke + pe + Emul print(' uncorrected total energy =', E) # Apply known corrections. Etid = grav.multiples_external_tidal_correction \ + grav.multiples_internal_tidal_correction # tidal error Eerr = grav.multiples_integration_energy_error # integration error E -= Etid + Eerr print(' corrected total energy =', E) if E0 is not None: print(' relative energy error=', (E-E0)/E0) return E ###BOOKLISTSTART2### def integrate_system(N, t_end, seed=None): total_mass = N|units.MSun length = 1|units.parsec converter = nbody_system.nbody_to_si(total_mass, length) gravity = ph4(convert_nbody=converter) gravity.initialize_code() gravity.parameters.set_defaults() gravity.parameters.epsilon_squared = (0.0|units.parsec)**2 if seed is not None: numpy.random.seed(seed) stars = new_plummer_model(N, convert_nbody=converter) stars.mass = total_mass/N stars.scale_to_standard(convert_nbody=converter, smoothing_length_squared = gravity.parameters.epsilon_squared) id = numpy.arange(N) stars.id = id+1 stars.radius = 0.5/N | units.parsec gravity.particles.add_particles(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() init_smalln(converter) kep = Kepler(unit_converter=converter) kep.initialize_code() multiples_code = multiples.Multiples(gravity, new_smalln, kep, constants.G) multiples_code.neighbor_perturbation_limit = 0.05 multiples_code.global_debug = 1 ###BOOKLISTSTOP2### # global_debug = 0: no output from multiples # 1: minimal output # 2: debugging output # 3: even more output print('') print('multiples_code.neighbor_veto =', \ multiples_code.neighbor_veto) print('multiples_code.neighbor_perturbation_limit =', \ multiples_code.neighbor_perturbation_limit) print('multiples_code.retain_binary_apocenter =', \ multiples_code.retain_binary_apocenter) print('multiples_code.wide_perturbation_limit =', \ multiples_code.wide_perturbation_limit) time = numpy.sqrt(length**3/(constants.G*total_mass)) print('\ntime unit =', time.in_(units.Myr)) ###BOOKLISTSTART3### E0 = print_diagnostics(multiples_code) multiples_code.evolve_model(t_end) print_diagnostics(multiples_code, E0) ###BOOKLISTSTOP3### gravity.stop() kep.stop() stop_smalln() if __name__ in ('__main__'): N = 100 t_end = 10.0 | units.Myr integrate_system(N, t_end, 42)
3,848
30.54918
72
py
amuse
amuse-main/examples/textbook/plot_accretion_from_windy_star.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import sys import numpy from matplotlib import pyplot from amuse.lab import * from prepare_figure import single_frame from distinct_colours import get_distinct def Bondi_Hoyle_Littleton_accretion_rate(Mb, vs, a0, Mdot_donor): a = (3.e-7 | units.MSun/units.yr) b = (Mb/(1|units.MSun))**2 c = ((10|units.kms)/vs)**4 d = ((100|units.AU)/a0)**2 e = (Mdot_donor/(1.e-4 | units.MSun/units.yr)) print(a, b, c, d, e) Mdot_BHL = a*b*c*d*e #Mdot_BHL = (3.e-7 | units.MSun/units.yr) * (Mb/(1|units.MSun))**2 ((10|units.kms)/vs)**4 * ((100|units.AU)/a0)**2 * (Mdot_donor/(1.e-4 | units.MSun/units.yr)) return Mdot_BHL def read_accretion_rate(filename): t = [] | units.yr m = [] | units.MSun n = [] for line in open(filename): if "N accreted:" in line: l = line.split() t.append(float(l[2])|units.Myr) n.append(float(l[4])) m.append(float(l[6])|units.MSun) return t, n, m def plot_accretion_from_wind(filename, color): t, dn, dm = read_accretion_rate(filename) m = numpy.cumsum(dm) #MMoon = 3.69145063653e-08 | units.MSun #m /= MMoon m /= (1.e-9|units.MSun) pyplot.plot(t.value_in(units.yr), m, c=color) # pyplot.show() def v_terminal_teff(temperature): print(numpy.log10(temperature.value_in(units.K))-3.) t4=(numpy.log10(temperature.value_in(units.K))-4.).clip(0.,1.) print(t4) return (30 | units.km/units.s) + ((4000 | units.km/units.s)*t4) def main(): """ Mb = (2. + 1.) | units.MSun Mb = 2. | units.MSun a0 = 10. | units.AU # vs = 35. | units.kms vs = 30. | units.kms Mdot_donor = 0.11 |units.MSun/units.Myr Mdot = Bondi_Hoyle_Littleton_accretion_rate(Mb, vs, a0, Mdot_donor) print Mdot.in_(units.MEarth/units.yr) t = numpy.arange(0, 3, 0.1) | units.yr mdot = Mdot*t t += 4 | units.yr """ Mb = (2. + 1.) | units.MSun Mb = 2. | units.MSun a0 = 10. | units.AU #vs = 30. | units.kms # vs = 18. | units.kms vs = 17.26 | units.kms vorb = numpy.sqrt(constants.G*Mb/a0) print("vorb=", vorb.in_(units.kms)) k = vorb/vs m1 = 1.924785833858|units.MSun m2 = 1.|units.MSun mu = m2/(m1+m2) Mdot_donor = 0.11 |units.MSun/units.Myr cvw = 0. print("k and mu:", k, mu) Mdot = Mdot_donor * mu**2 * k**4/(1 + k**2 + cvw**2)**(3./2.) # print "Mdot:", Mdot.in_(units.MEarth/units.yr) print("Mdot:", Mdot.in_(units.MSun/units.Myr)) t = numpy.arange(0, 3, 0.1) | units.yr mdot = Mdot*t t += 4.2 | units.yr c = get_distinct(3) x_label = 't [yr]' y_label = 'M [$10^{-9}$M$_{\odot}$]' figure = single_frame(x_label, y_label, logy=False, xsize=14, ysize=10) filename = "hydro_give_or_take.data" print(t, mdot.value_in(units.MSun)) mdot /= (1.e-9|units.MSun) pyplot.plot(t.value_in(units.yr), mdot, c=c[2]) plot_accretion_from_wind(filename, c[0]) filename = "hydro_give_or_take_gravity_NoG.data" plot_accretion_from_wind(filename, c[1]) pyplot.savefig("hydro_accretion_from_windy_star") # pyplot.show() if __name__ in ('__main__', '__plot__'): main()
3,325
28.433628
163
py
amuse
amuse-main/examples/textbook/gravity_stellar_collision.py
""" N-body integration of N particles with a Salpeter initial mass function between Mmin and Mmax and with stellar evolution with metallicity z. """ from amuse.lab import * from amuse.io import store from amuse.community.seba.interface import SeBa ###BOOKLISTSTART1### def merge_two_stars(bodies, particles_in_encounter): com_pos = particles_in_encounter.center_of_mass() com_vel = particles_in_encounter.center_of_mass_velocity() new_particle = Particles(1) new_particle.mass = particles_in_encounter.total_mass() new_particle.age = min( particles_in_encounter.age ) * max(particles_in_encounter.mass) / new_particle.mass new_particle.position = com_pos new_particle.velocity = com_vel new_particle.radius = particles_in_encounter.radius.sum() bodies.add_particles(new_particle) print( f"Two stars (M={particles_in_encounter.mass}) collided with " f"d={com_pos.length()}" ) bodies.remove_particles(particles_in_encounter) ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def resolve_collision(collision_detection, gravity, stellar, bodies): if collision_detection.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print("Collision at time=", gravity.model_time.in_(units.Myr)) for ci in range(len(collision_detection.particles(0))): particles_in_encounter = Particles( particles=[ collision_detection.particles(0)[ci], collision_detection.particles(1)[ci] ] ) particles_in_encounter = \ particles_in_encounter.get_intersecting_subset_in(bodies) d = ( particles_in_encounter[0].position - particles_in_encounter[1].position ).length() if particles_in_encounter.collision_radius.sum() > d: merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) else: print("Failed to resolve encounter: stars too small.") dE_coll = E_coll - ( gravity.kinetic_energy + gravity.potential_energy ) print("Energy error in the collision: dE =", dE_coll) ###BOOKLISTSTOP2### def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): masses = new_salpeter_mass_distribution(N, Mmin, Mmax) Mtot_init = masses.sum() # converter = nbody_system.nbody_to_si(Mtot_init, Rvir) converter = nbody_system.nbody_to_si(Mtot_init, dt) bodies = new_king_model(N, W0, convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_stellar = stellar.particles.new_channel_to(bodies, attributes=["mass", "radius", "age"], target_names=["mass", "radius", "age"]) channel_from_gravity = gravity.particles.new_channel_to(bodies, attributes=["x", "y", "z", "vx", "vy", "vz", "mass", "radius"], target_names=["x", "y", "z", "vx", "vy", "vz", "mass", "collision_radius"]) channel_to_gravity = bodies.new_channel_to( gravity.particles, attributes=["mass", "collision_radius"], target_names=["mass", "radius"]) channel_from_stellar.copy() write_set_to_file(bodies.savepoint(0 | units.Myr), filename, 'hdf5', overwrite_file=True) E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 dE_coll = zero time = zero ###BOOKLISTSTART3### while time < t_end: time += dt E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy \ + gravity.potential_energy) channel_from_stellar.copy() bodies.collision_radius = 1.e+5 * bodies.radius channel_to_gravity.copy() E_dyn = gravity.kinetic_energy + gravity.potential_energy while gravity.model_time < time: gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gravity.copy() resolve_collision(stopping_condition, gravity, stellar, bodies) write_set_to_file(bodies.savepoint(time), filename, 'hdf5', append_to_file=True) print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) ###BOOKLISTSTOP3### gravity.stop() stellar.stop() def print_diagnostics(time, Mtot, Etot, dE_dyn, dE_coll, dE_stellar): print("Time=", time, end=' ') print("Mtot=", Mtot, end=' ') print("Etot= ", Etot, end=' ') print("dE(dyn)=", dE_dyn/Etot, end=' ') print("dE(coll)=", dE_coll/Etot, end=' ') print("dE(se)=", dE_stellar/Etot) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option( "-f", dest="filename", default="gravity_stellar.hdf5", help="output filename [%default]") result.add_option( "-N", dest="N", type="int", default=100, help="number of stars [%default]") result.add_option( "--dt", unit=units.Myr, dest="dt", type="float", default=1 | units.Myr, help="output timesteps [%default]") result.add_option( "-M", unit=units.MSun, dest="Mmax", type="float", default=100, help="maximum stellar mass [%default.value_in(units.MSun))]") result.add_option( "-m", unit=units.MSun, dest="Mmin", type="float", default=0.1, help="minimum stellar mass [%default.value_in(units.MSun)]") result.add_option( "-R", unit=units.parsec, dest="Rvir", type="float", default=1.0, help="cluser virial radius [%default.value_in(units.parsec)]") result.add_option( "-t", unit=units.Myr, dest="t_end", type="float", default=10.0, help="end time of the simulation [%default.value_in(units.Myr]") result.add_option( "-W", dest="W0", type="float", default=7.0, help="Dimensionless depth King potential depth (W0) [%default]") result.add_option("-z", dest="z", type="float", default=0.02, help="metalicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() set_printing_strategy("custom", preferred_units=[units.MSun, units.RSun, units.Myr], precision=4, prefix="", separator=" [", suffix="]") main(**o.__dict__)
7,077
37.89011
93
py
amuse
amuse-main/examples/textbook/plot_M67Data.py
#!/usr/bin/python from __future__ import division from matplotlib import pyplot import os def logLuminosity(V): VminMv = 9.7 MBolSun = 4.74 Mv = V - VminMv L = (MBolSun - Mv)/2.5 return L def logTeff(BminV): logT = (14.551 - BminV)/3.684 if logT > 3.961: a,b,c = [.344,-3.402,8.037] logT = (-b - (b*b-4*a*c)**.5)/(2.*a) return logT def Teff(BminV): return 10.**logTeff(BminV) class Cluster(): def __init__(self) : self.n = 0 self.L = [] self.Teff = [] self.BmV = [] self.V = [] def __iter__(self): return self def __repr__(self): tt = 'Cluster()' return tt def read(self): try: amusedir = os.environ['AMUSE_DIR'] dir = amusedir+'/examples/textbook/' except: print('Environment variable AMUSE_DIR not set') dir = './' isofile = open(dir+'M67Data.dat') lines = isofile.readlines() E_BminV = 0.04 for line in lines: self.V.append(float(line.split()[0])) self.BmV.append(float(line.split()[1])) self.L.append(10**logLuminosity(self.V[-1]-E_BminV)) self.Teff.append(10**logTeff(self.BmV[-1]-E_BminV)) self.n = self.n +1 def plot(self): pyplot.xlim(max(self.Teff), min(self.Teff)) pyplot.scatter(self.Teff, self.L) pyplot.xlabel("Teff") pyplot.ylabel("L") pyplot.show() if __name__=="__main__": cls = Cluster() cls.read() cls.plot()
1,589
22.043478
64
py
amuse
amuse-main/examples/textbook/orbital_elements_to_cartesian.py
from amuse.lab import * from math import pi, sin, cos, sqrt, atan2 import numpy #Solve Kepler equation by iterating: M = E - e sin E #Lit.: Sterne, T.E., 1960, An introduction to Celestial Mechanics, p. 13-14 def eccentric_anomaly(mean_anomaly, e) : ecc_anomaly = mean_anomaly + 2*pi*(e * sin(mean_anomaly) + 0.5*e*e*sin(2*mean_anomaly)) m = ecc_anomaly - e*sin(ecc_anomaly) de = (mean_anomaly-m) / (1 - e*cos(ecc_anomaly)) ecc_anomaly += de; while de >= 0.001 : m = ecc_anomaly - e*sin(ecc_anomaly) de = (mean_anomaly-m) / (1 - e*cos(ecc_anomaly)) ecc_anomaly += de return ecc_anomaly def orbital_elements_to_pos_and_vel(time, a, ecc, inc, omra, omega, tp, P, Mbh, mstar): mu = constants.G*(Mbh+mstar) MA = 2.*pi*(time-tp)/P while (MA<0) and (MA>2.*pi): if MA<0: time = time+P else: time = time-P MA = 2.*pi*(time-tp)/P EA = eccentric_anomaly(MA,ecc) # eccentric anomaly # true anomaly in the correct quadrant ta = 2.*atan2(sqrt(1.+ecc)*sin(EA/2.),sqrt(1.-ecc)*cos(EA/2.)) radius = a * (1. - ecc*cos(EA)) # radius from EA and ecc r = [] | units.AU # Cartesian position r.append(radius*(cos(omra)*cos(omega+ta) - sin(omra)*sin(omega+ta)*cos(inc))) r.append(radius*(sin(omra)*cos(omega+ta) + cos(omra)*sin(omega+ta)*cos(inc))) r.append(radius*(sin(inc)*sin(omega+ta))) h = (mu*a*(1. - ecc*ecc)).sqrt() pp = a*(1-ecc*ecc) v = [] | units.kms # Cartesian velocity v.append(r.x*h*ecc/radius/pp*sin(ta) - h/radius * ( cos(omra)*sin(omega+ta) +sin(omra)*cos(omega+ta)*cos(inc))) v.append(r.y*h*ecc/radius/pp*sin(ta) - h/radius * ( sin(omra)*sin(omega+ta) -cos(omra)*cos(omega+ta)*cos(inc))) v.append(r.z*h*ecc/radius/pp*sin(ta) + h/radius*sin(inc)*cos(omega+ta)) return r, v def main(T, a, e, i, o, O, t, P, M, m): T = T |units.yr a = a |units.AU t = t | units.yr P = P | units.yr M = M |units.MSun m = m |units.MSun i *= pi/180. o *= pi/180. O *= pi/180. r, v = orbital_elements_to_pos_and_vel(T, a, e, i, o, O, t, P, M, m) print("r=", r.in_(units.AU), "v=", v.in_(units.kms)) def new_option_parser(): from optparse import OptionParser result = OptionParser() # data for S2 from 2009ApJ...692.1075G result.add_option("-T", dest="T",type="float",default=0) result.add_option("-a", dest="a",type="float",default=1042.5) result.add_option("-e", dest="e",type="float",default=0.88) result.add_option("-i", dest="i",type="float",default=135.25) result.add_option("-o", dest="o",type="float",default=225.39) result.add_option("-O", dest="O",type="float",default=63.56) result.add_option("-t", dest="t",type="float",default=2002.32) result.add_option("-P", dest="P",type="float",default=15.8) result.add_option("-M", dest="M",type="float",default=4.45e+6) result.add_option("-m", dest="m",type="float",default=19.5) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
3,103
37.8
115
py
amuse
amuse-main/examples/textbook/molecular_cloud_collapse_with_sinks.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from cooling_class import SimplifiedThermalModel, SimplifiedThermalModelEvolver from hydrodynamics_class import Hydro def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec): conv = nbody_system.nbody_to_si(Mcloud,Rcloud) gas=molecular_cloud(targetN=N,convert_nbody=conv, base_grid=body_centered_grid_unit_cube).result gas.name = "gas" rho_cloud = Mcloud/Rcloud**3 tff = 0.5427/numpy.sqrt(constants.G*rho_cloud) print("Freefall timescale=", tff.in_(units.Myr)) stars = Particles(0) hydro = Hydro(Fi, gas, stars) rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3) print(rho_cloud) dt = 0.02 | units.Myr tend= 10.0 | units.Myr dt_diag = 0.1 | units.Myr t_diag = 0 | units.Myr i=0 E0 = 0.0 time = 0.0 | units.Myr while time < tend: time += dt print("Evolve to time=", time.in_(units.Myr)) Mtot = 0|units.MSun if len(hydro.star_particles) > 0: print("Mass conservation: Slocal:", time.in_(units.Myr), \ hydro.gas_particles.mass.sum().in_(units.MSun), \ hydro.star_particles.mass.sum().in_(units.MSun), \ "sum=", (hydro.gas_particles.mass.sum() \ + hydro.star_particles.mass.sum()).in_(units.MSun)) print("Mass conservation: Shydro:", time.in_(units.Myr), \ hydro.code.gas_particles.mass.sum().in_(units.MSun), \ hydro.code.dm_particles.mass.sum().in_(units.MSun), \ "sum=", \ (hydro.code.gas_particles.mass.sum() \ + hydro.code.dm_particles.mass.sum()).in_(units.MSun), \ "S=", hydro.star_particles.mass.sum().in_(units.MSun)) Mtot = hydro.gas_particles.mass.sum() \ + hydro.star_particles.mass.sum() else: print("Mass conservation: local:", time.in_(units.Myr), \ hydro.gas_particles.mass.sum().in_(units.MSun)) print("Mass conservation: hydro:", time.in_(units.Myr), \ hydro.code.gas_particles.mass.sum().in_(units.MSun)) Mtot = hydro.gas_particles.mass.sum() if Mtot < Mcloud-(1.e-5|units.MSun): print("Mass is not conserved:", Mtot.in_(units.MSun), \ Mcloud.in_(units.MSun)) exit(-1) hydro.evolve_model(time) E = hydro.gas_particles.kinetic_energy() \ + hydro.gas_particles.potential_energy() \ + hydro.gas_particles.thermal_energy() E_th = hydro.gas_particles.thermal_energy() if i==0: E0 = E Eerr = (E-E0)/E0 print('energy=', E, 'energy_error=', Eerr, 'e_th=', E_th) print("maximal_density:",gas.rho.max().in_(units.MSun/units.parsec**3)) hydro.print_diagnostics() if time>t_diag: t_diag += dt_diag hydro.write_set_to_file(i) i=i+1 hydro.stop() return gas if __name__ in ("__main__","__plot__"): numpy.random.seed(3141) parts = run_molecular_cloud(10000, Mcloud=1000. | units.MSun, Rcloud=3.0 | units.parsec)
3,457
35.020833
79
py
amuse
amuse-main/examples/textbook/three_body_bridge.py
import numpy from amuse.lab import * from amuse.couple import bridge def new_system_of_sun_and_earth(): stars = Particles(3) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) moon = stars[2] moon.mass = units.kg(7.3477e22 ) moon.radius = units.km(1737.10) moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity return stars def main(): filename = "SunAndEarthAndMoon.hdf" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] moon = ss[2] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) ###BOOKLISTSTART### star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) moon_gravity = ph4(converter) moon_gravity.particles.add_particle(moon) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss) write_set_to_file(ss, filename, 'hdf5') gravity = bridge.Bridge() gravity.add_system(star_gravity, (planet_gravity,moon_gravity)) gravity.add_system(planet_gravity, (star_gravity,moon_gravity)) gravity.add_system(moon_gravity, (star_gravity,planet_gravity)) ###BOOKLISTSTOP### Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.timestep = 1|units.day time = zero dt = 3|units.day t_end = 1 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() channel_from_moon_to_framework.copy() write_set_to_file(ss, filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
2,739
30.860465
82
py
amuse
amuse-main/examples/textbook/hydro_wind_disk_interaction.py
from amuse.lab import * from amuse.community.gadget2.interface import Gadget2 as Gadget2 from amuse.units import units, constants, nbody_system from amuse.ext.sink import new_sink_particles from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.datamodel import Particles import numpy import time as timing class MinimalWorkingExample(object): def __init__(self, total_N=16000, #total number of disc particles tend=250. | units.yr, #End time of the simulation Mstar=1. | units.MSun, #Mass of the accreting star dt = 1. | units.yr, #timestep temp = 25. | units.K, #temperature of the ISM v_ism = 3.0 | units.kms, #Velocity of the ISM with respect to the star n_core = 4, #Number of cores used by the community codes mu = 2.3, #mean molecular weight theta = 0., #angle of the disc with respect to the flow, 0 means disc rotation axis is parallel with flow direction n_dens = 5e6 | (units.cm)**(-3.), #Number density of the ism dirname = './'): self.disc_N = total_N self.tend = tend self.Mstar = Mstar self.dt = dt self.mu = mu * constants.proton_mass self.T = temp self.cs = ((temp*constants.kB)/self.mu).sqrt() # print "cs=", self.cs.in_(units.kms) self.v_ism = v_ism self.ism_n_dens = n_dens #number density of the ism self.ism_dens = self.mu*self.ism_n_dens #mass density of the ism self.converter = nbody_system.nbody_to_si(self.Mstar, 1. | units.AU) self.disc_angle = numpy.radians(theta) self.n_core = n_core self.dirname = dirname self.discfraction = 0.01 self.disc_Rmin = self.converter.to_generic(10.| units.AU).value_in(nbody_system.length) self.disc_Rmax = self.converter.to_generic(100.| units.AU).value_in(nbody_system.length) self.filename = "DiskWind.h5" print('Files will be saved in ', self.dirname) def initialize_star(self): self.star=Particles(1) self.star.mass=self.Mstar self.star.radius= 1. | units.AU self.star.x=0.|units.AU self.star.y=0.|units.AU self.star.z=0.|units.AU self.star.vx=0.|units.kms self.star.vy=0.|units.kms self.star.vz=0.|units.kms def initialize_data(self): self.cylinder_radius = 500. | units.AU self.cylinder_length = 2.*self.cylinder_radius self.cylinder_vol = self.cylinder_length*numpy.pi*self.cylinder_radius**2. self.sph_particle_dens = self.ism_dens/(0.01*self.Mstar/self.disc_N) self.initialize_star() self.initialize_ism() def initialize_ism(self): #specific internal energy of the ism, i.e. internal energy per unit mass #In case of an isothermal EOS, Gadget requires the sound-speed squared as input parameter instead of the thermal energy per unit mass self.ism_u = self.cs**2. self.ism_slice_length = self.v_ism*self.dt self.ism_slice_vol = self.ism_slice_length*numpy.pi*self.cylinder_radius**2.0 self.ism_slice_mass = self.ism_dens*self.ism_slice_vol self.ism_mass = self.ism_dens*self.cylinder_vol #The x-coordinate of the inflow self.offset = self.cylinder_radius self.ism_slice_N = int(round(self.sph_particle_dens*self.ism_slice_vol)) self.total_N = self.ism_slice_N*(self.cylinder_length/self.ism_slice_length) def make_slice(self): new_slice = Particles(self.ism_slice_N) rho = numpy.sqrt(numpy.random.uniform(0,1,self.ism_slice_N))*self.cylinder_radius.value_in(units.AU) phi = numpy.random.uniform(0,2.0*numpy.pi, self.ism_slice_N) new_slice.x = numpy.random.uniform(self.ism_slice_length.value_in(units.AU), 0, self.ism_slice_N) - self.offset.value_in(units.AU) | units.AU new_slice.y = rho*numpy.sin(phi) | units.AU new_slice.z = rho*numpy.cos(phi) | units.AU new_slice.vx = 1000*self.v_ism new_slice.vy = 0.0 | units.kms new_slice.vz = 0.0 | units.kms new_slice.mass = self.ism_slice_mass/self.ism_slice_N new_slice.u = self.ism_u return new_slice def create_disc(self): #The following line makes sure masses for ISM and disc particles are equal: self.discfraction = (self.disc_N*(self.ism_slice_mass/self.ism_slice_N))/self.Mstar T_disc = self.T cs_disc = ((T_disc*constants.kB)/self.mu).sqrt() densitypower = 1.5 g2=2-densitypower k_out=((1+self.discfraction)/self.disc_Rmax**3)**0.5 sigma_out=g2*self.discfraction/(2*numpy.pi*self.disc_Rmax**densitypower*(self.disc_Rmax**g2-self.disc_Rmin**g2)) q_out = self.converter.to_generic(cs_disc).value_in(nbody_system.length/nbody_system.time)/(numpy.pi*sigma_out/k_out) print("Number of disk particles:", self.disc_N) proto=ProtoPlanetaryDisk(self.disc_N, convert_nbody=self.converter, discfraction=self.discfraction, densitypower=1.5, thermalpower=0, Rmin=self.disc_Rmin, Rmax=self.disc_Rmax, q_out=q_out) disc=proto.result print("The mass of a disc particle = ", disc.mass[0].value_in(units.kg)) #Rotate 90 degrees with respect to the z-axis and then theta degrees with respect to the y-axis temp_x = disc[:].x temp_y = disc[:].y temp_z = disc[:].z temp_vx = disc[:].vx temp_vy = disc[:].vy temp_vz = disc[:].vz disc.x = temp_z*numpy.cos(self.disc_angle) - temp_y*numpy.sin(self.disc_angle) disc.y = temp_z*numpy.sin(self.disc_angle) + temp_y*numpy.cos(self.disc_angle) disc.z = -temp_x disc.vx = temp_vz*numpy.cos(self.disc_angle) - temp_vy*numpy.sin(self.disc_angle) disc.vy = temp_vz*numpy.sin(self.disc_angle) + temp_vy*numpy.cos(self.disc_angle) disc.vz = -temp_vx return disc def evolve_model(self): self.initialize_data() self.ism_code = Gadget2(self.converter, number_of_workers=self.n_core)#, debugger='gdb') self.ism_code.parameters.time_max = 1024*self.dt self.ism_code.parameters.n_smooth = 64 self.ism_code.parameters.n_smooth_tol = 2./64. self.ism_code.parameters.artificial_viscosity_alpha = 0.1 self.ism_code.parameters.epsilon_squared = (1. | units.AU)**2. self.all_particles = Particles() write_set_to_file(self.star, self.filename, "hdf5", append_to_file=False) write_set_to_file(self.all_particles, self.filename, "hdf5", append_to_file=False) self.initial_disc_particles = self.create_disc() self.all_particles.add_particles(self.initial_disc_particles) self.ism_code.gas_particles.add_particles(self.initial_disc_particles) #You can only add a sink after adding gas particles #starinsph refers to the corresponding particle set/id in the community code starinsph = self.ism_code.dm_particles.add_particles(self.star) #Use the build-in sink particle routine from amuse.ext.sink. Sink_radius needs to be defined manually otherwise the particle radius in gadget is taken, #which does not corresponding to the particle radius in the framework (since 'particles' in gadget do not have a radius, it is set to 0.01 | generic_unit_system.length #and corresponds to the gas gravitational smoothing epsilon. sink = new_sink_particles(starinsph, sink_radius= self.star.radius) self.channel_from_ismcode_to_framework = self.ism_code.gas_particles.new_channel_to(self.all_particles) time = 0. | units.yr while time <= (self.tend+self.dt/2.): print("Adding new slice of ISM...") newslice=self.make_slice() self.ism_code.gas_particles.add_particles(newslice) self.all_particles.add_particles(newslice) start = timing.time() print("=======================================================") print("Evolving to time = ", time.value_in(units.yr), " of ", self.tend.value_in(units.yr)," years...") self.ism_code.evolve_model(time) print("This took ", (timing.time() - start), " s") out_of_bounds = self.ism_code.gas_particles.select_array(lambda x,y,z:(x > self.cylinder_radius)|((z**2+y**2).sqrt() >= self.cylinder_radius), ["x","y","z"]) if len(out_of_bounds)>0: print("Removing ", len(out_of_bounds), " particles from the code because they were out of bounds") self.ism_code.gas_particles.remove_particles(out_of_bounds) self.ism_code.gas_particles.synchronize_to(self.all_particles) sink.accrete(self.ism_code.gas_particles) write_set_to_file(self.star, self.filename, "hdf5") write_set_to_file(self.all_particles, self.filename, "hdf5") time += self.dt print("=======================================================") self.ism_code.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="total_N", type="int", default = 1000, help="Total number of disc particles") result.add_option("-t", dest="t_end", type="float", default = 100, unit = units.yr, help="end time [%unit]") result.add_option("-d", dest="dt_diag", type="float", default = 1, unit = units.yr, help="diagnostic timestep [%unit]") result.add_option("-m", dest="mass", type="float", default = 1.0, unit = units.MSun, help="mass of the star [%unit]") result.add_option("--temp", dest="temp", type="float", default = 25., unit = units.K, help="Temperature of the ISM [%unit]") result.add_option("-v", dest="v_ism", type="float", default = 3., unit = units.kms, help="Velocity of the ISM [%unit]") result.add_option("--mu", dest="m_ism", type="float", default = 2.3, help="Mean molecular weight of ISM [%unit]") result.add_option("-i", dest="inclination", type="float", default = 0.0, help="inclination of the disc with the y-axis") result.add_option("--ndens", dest="n_dens", type="int", default = 5e6 | (units.cm)**(-3.), unit = (units.cm)**(-3.), help="Number density of the ISM") result.add_option("--dir", dest="directory", type="string", default = '/home/thomas/Documents/simulations/disc', help="The directory where to save the plots and data") result.add_option("-c", dest="n_cores", type="int", default = 4, help="Number of cores used by community codes") return result if __name__ in ("__main__","__plot__"): o, arguments = new_option_parser().parse_args() code = MinimalWorkingExample( total_N=o.total_N, tend=o.t_end, Mstar=o.mass, dt = o.dt_diag, temp = o.temp, v_ism = o.v_ism, mu = o.m_ism, n_dens = o.n_dens, dirname = o.directory, n_core = o.n_cores, theta = o.inclination) code.evolve_model()
12,985
40.225397
175
py
amuse
amuse-main/examples/textbook/plot_projected_density_distributions_all.py
import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from amuse.plot import sph_particles_plot, native_plot from prepare_figure import figure_frame from distinct_colours import get_distinct def create_molecular_cloud(N, Mcloud, Rcloud, t_end): converter = nbody_system.nbody_to_si(Mcloud,Rcloud) parts = new_plummer_gas_model(N, convert_nbody=converter) sph=Fi(converter) sph.gas_particles.add_particle(parts) sph.evolve_model(t_end) ch = sph.gas_particles.new_channel_to(parts) ch.copy() sph.stop() return parts def convert_star_to_hydro_model(M, t_end): star = Particle(mass=M) stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) print("Evolving", star.mass, "star with", stellar_evolution.__class__.__name__, "up to", t_end.in_(units.Myr)) stellar_evolution.evolve_model(t_end) print("Creating SPH particles from the (1D) stellar evolution model") sph_particles = convert_stellar_model_to_SPH( se_star, 10000 ).gas_particles stellar_evolution.stop() return sph_particles def stellar_model(N, M, t=0.0|units.Myr): star = Particle(mass=M) stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) print("Evolving", star.mass, "star with", stellar_evolution.__class__.__name__, "to t=", t.in_(units.Myr)) stellar_evolution.evolve_model(t) print("Stellar type:", stellar_evolution.particles.stellar_type) print("Creating SPH particles from the (1D) stellar evolution model") sph_particles = convert_stellar_model_to_SPH(se_star, N).gas_particles stellar_evolution.stop() return sph_particles def plot_ZAMS_stellar_model(N, M): sph_particles = stellar_model(N, M) figure = pyplot.figure(figsize=(12, 12)) plot = figure.add_subplot(1,1,1) pyplot.rcParams.update({'font.size': 30}) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) ax.get_yaxis().get_major_formatter().set_useOffset(False) ax.minorticks_on() # switch on the minor ticks lim = 2 sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-lim, lim, -lim, lim)|units.RSun) ax.set_facecolor('white') pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") #native_plot.savefig("stellar_2MSunZAMS_projected") pyplot.savefig("stellar_2MSunZAMS_projected") def plot_stellar_model(N, M, t): sph_particles = stellar_model(N, M, t) x_label = "x [R$_\odot$]" y_label = "y [R$_\odot$]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-5, 5, -5, 5)|units.RSun) # sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-2, 2, -2, 2)|units.RSun) ax.set_facecolor('white') pyplot.xlabel(x_label) pyplot.ylabel(y_label) native_plot.savefig("stellar_2MSun_projected") #pyplot.savefig("stellar_2MSun_projected") def plummer_model(N, M, R): converter = nbody_system.nbody_to_si(M, R) parts = new_plummer_gas_model(N, convert_nbody=converter) sph=Fi(converter) sph.gas_particles.add_particle(parts) sph.evolve_model(1|units.day) ch = sph.gas_particles.new_channel_to(parts) ch.copy() sph.stop() return parts def GMC_model(N, M, R): converter = nbody_system.nbody_to_si(M, R) gmc=molecular_cloud(targetN=N, convert_nbody=converter) parts= gmc.result sph=Fi(converter) sph.gas_particles.add_particle(parts) sph.evolve_model(1|units.day) ch = sph.gas_particles.new_channel_to(parts) ch.copy() sph.stop() return parts def plot_plummer_model(N, M, R): sph_particles = plummer_model(N, M, R) x_label = "x [pc]" y_label = "y [pc]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-50, 50, -50, 50)|units.parsec) ax.set_facecolor('white') pyplot.xlabel(x_label) pyplot.ylabel(y_label) native_plot.savefig("plummer_projected") def plot_GMC_model(N, M, R): sph_particles = GMC_model(N, M, R) x_label = "x [pc]" y_label = "y [pc]" figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12) lim = 20 sph_particles_plot(sph_particles, min_size = 500, max_size = 500, alpha=0.01, view=(-lim, lim, -lim, lim)|units.parsec) ax.set_facecolor('white') #native_plot.savefig("molecular_cloud_projected") pyplot.savefig("molecular_cloud_projected") if __name__ in ("__main__","__plot__"): N = 10000 M = 10000. | units.MSun R = 10. | units.parsec # plot_plummer_model(N, M, R) # plot_GMC_model(N, M, R) M = 2 | units.MSun plot_ZAMS_stellar_model(N, M) # plot_stellar_model(N, M, t=1.3|units.Gyr)
5,060
34.145833
119
py
amuse
amuse-main/examples/textbook/hydro_disk_with_bump.py
""" Simulate the radiative and hydrodynamial evolution of a disk with a bump around a single star """ from time import time, localtime from amuse.lab import * from amuse.ext.molecular_cloud import ism_cube from amuse.community.simplex.interface import SimpleXInterface, SimpleX, \ SimpleXSplitSet from amuse.ext.protodisk import ProtoPlanetaryDisk set_printing_strategy("custom", preferred_units = [units.MSun, units.AU, units.Myr], precision = 12, prefix = "", separator = " [", suffix = "]") def mu(X = None, Y = 0.25, Z = 0.02, x_ion = 0.1): """ Compute the mean molecular weight in kg (the average weight of particles in a gas) X, Y, and Z are the mass fractions of Hydrogen, of Helium, and of metals, respectively. x_ion is the ionisation fraction (0 < x_ion < 1), 1 means fully ionised. """ if X is None: X = 1.0 - Y - Z elif abs(X + Y + Z - 1.0) > 1e-6: raise Exception("Error in calculating mu: mass " + "fractions do not sum to 1.0") return constants.proton_mass / (X*(1.0+x_ion) + Y*(1.0+2.0*x_ion)/4.0 + Z*x_ion/2.0) class RadHydro: def __init__(self, rad, hydro, star, disk): self.time = 0|units.day self.star = star self.disk = disk disk.r2 = disk.x**2 + disk.y**2 disk = disk.sorted_by_attributes("r2") Rmax = disk.r2.max().sqrt() print("MaxR=", Rmax.in_(units.AU)) self.hydro = hydro(nbody_system.nbody_to_si(self.disk.mass.sum(), Rmax), number_of_workers=4) self.hydro.parameters.epsilon_squared = (10|units.AU)**2 self.hydro.gas_particles.add_particles(self.disk) self.hydro.gas_particles.new_channel_to(self.disk) self.hydro.dm_particles.add_particles(self.star) self.hydro.dm_particles.new_channel_to(self.star) self.hydro_to_star = self.hydro.dm_particles.new_channel_to(self.star) self.hydro_to_disk = self.hydro.gas_particles.new_channel_to(self.disk) self.star_to_hydro = self.star.new_channel_to(self.hydro.dm_particles) self.disk_to_hydro = self.disk.new_channel_to(self.hydro.gas_particles) self.hydro.evolve_model(1|units.s) self.hydro_to_star.copy() self.hydro_to_disk.copy() self.rad = rad() for si in self.star: if si.mass>=5|units.MSun: self.rad.src_particles.add_particle(si) self.rad.gas_particles.add_particles(self.disk) self.rad.parameters.box_size=2.01*Rmax self.rad.parameters.timestep=1|units.day self.rad.set_source_Teff(star.temperature) self.rad_to_disk = self.rad.gas_particles.new_channel_to(self.disk, attributes=["xion", "u"]) self.star_to_rad = self.star.new_channel_to(self.rad.src_particles, attributes=["x", "y", "z"]) self.disk_to_rad = self.disk.new_channel_to(self.rad.gas_particles, attributes=["x", "y", "z"]) self.rad.stop() self.index = 0 def write_file(self): self.index += 1 filename = "hydro_disk_with_bump_i{0:04}.amuse".format(self.index) write_set_to_file(self.star, filename, "amuse", append_to_file=False) write_set_to_file(self.disk, filename, "amuse") def evolve_model(self, model_time): dt = model_time - self.time self.old_time = self.time self.time += dt/2. #self.disk_to_rad.copy() #self.star_to_rad.copy() #self.rad.evolve_model(self.time) #self.rad_to_disk.copy() self.time += dt/2. self.disk_to_hydro.copy() self.star_to_hydro.copy() self.hydro.evolve_model(self.time) self.hydro_to_disk.copy() self.hydro_to_star.copy() print("RT done at time:", self.time.in_(units.day)) def print_diagnostics(self): umin = self.disk.u.min() umean = self.disk.u.mean() umax = self.disk.u.max() Tmin = mu() / constants.kB * umax Tmean = mu() / constants.kB * umean Tmax = mu() / constants.kB * umin print("Time=", self.time.in_(units.day)) print("Ionization:", self.disk.xion.min(), self.disk.xion.mean(), \ self.disk.xion.max()) print("Intenal energy:", umin, umean, umax) print("Temperature:", Tmin, Tmean, Tmax) print("Density:", self.disk.density.min().in_(units.amu/units.cm**3), \ self.disk.density.mean().in_(units.amu/units.cm**3), \ self.disk.density.max().in_(units.amu/units.cm**3)) print("scaleheight:", abs(self.disk.z.value_in(units.AU)).mean()) def stop(self): self.hydro.stop() ###BOOKLISTSTART1### def new_disk_with_bump(Mstar = 10|units.MSun, Ndisk=100, Mdisk=1.0|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=5.0|units.AU, abump=10|units.AU): converter=nbody_system.nbody_to_si(Mstar, Rmin) disk = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1, Rmax=Rmax/Rmin, q_out=1.0, discfraction=Mdisk/Mstar).result com = disk.center_of_mass() # determine bump's local velocity inner_particles = disk.select(lambda r: (com-r).length() < abump,["position"]) M_inner = Mstar + inner_particles.mass.sum() v_circ = (constants.G*M_inner*(2./abump - 1./abump)) \ .sqrt().value_in(units.kms) # initialize bump Nbump = int(Ndisk*Mbump/Mdisk) bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump bump.velocity += [0, v_circ, 0] | units.kms disk.add_particles(bump) disk.move_to_center() return disk ###BOOKLISTSTOP1### def evolve_star(Mstar, tstar): stars = Particles(1) stars = Particles(2) stars[0].mass = Mstar stars[1].mass = 0.1*Mstar stellar = SeBa() stellar.particles.add_particle(stars) stellar.evolve_model(tstar) stars.mass = stellar.particles.mass stars.position = (0, 0, 0) |units.AU stars.velocity = (0, 0, 0) |units.kms stars.luminosity = stellar.particles.luminosity/(20. | units.eV) stars.temperature = stellar.particles.temperature stars.flux = stars.luminosity stars.rho = 1.0|(units.g/units.cm**3) stars.xion = 0.0 #ionization_fraction stars.u = (9. |units.kms)**2 #internal_energy print(stars) if len(stars)>1: stars[1].x = 50|units.AU vc = 1.0*(constants.G*stars.mass.sum()/(100.|units.AU)).sqrt() stars[1].vy += vc stellar.stop() return stars def hydro_disk_with_bump(Mstar = 10|units.MSun, Ndisk=100, Mdisk=1.0|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun, Rbump=5.0|units.AU, abump=10|units.AU, t_end=10|units.yr, n_steps=10): star = evolve_star(Mstar, t_end) disk = new_disk_with_bump(star[0].mass, Ndisk, Mdisk, Rmin, Rmax, Mbump, Rbump, abump) radhydro = RadHydro(SimpleXSplitSet, Gadget2, star, disk) radhydro.write_file() dt = t_end/float(n_steps) print("dt=", dt.in_(units.day)) time = 0 | units.day while time<t_end: time += dt radhydro.evolve_model(time) radhydro.print_diagnostics() radhydro.write_file() radhydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ndisk", type="int",default = 10000, help="number of stars [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 2000.|units.yr, help="radiation time [%default]") result.add_option("-n", dest="n_steps", type="int",default = 100, help="number of steps [%default]") result.add_option("--Mstar", unit=units.MSun, dest="Mstar", type="float", default = 10|units.MSun, help="Mass of the central star [%default]") result.add_option("--Mdisk", unit=units.MSun, dest="Mdisk", type="float", default = 1|units.MSun, help="Mass of the disk [%default]") result.add_option("-r", unit=units.AU, dest="Rmin", type="float", default = 10 |units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, dest="Rmax", type="float", default = 100 | units.AU, help="outer disk radius [%default]") result.add_option("--Mbump", unit=units.MSun, dest="Mbump", type="float", default = 0.5 | units.MSun, help="bump mass [%default]") result.add_option("--Rbump", unit=units.AU, dest="Rbump", type="float", default = 5 | units.AU, help="bump radius [%default]") result.add_option("-a", unit=units.AU, dest="abump", type="float", default = 50 | units.AU, help="distance of bump from star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() hydro_disk_with_bump(**o.__dict__)
10,086
38.402344
80
py
amuse
amuse-main/examples/textbook/plot_core_temperature_density.py
import math from amuse.lab import * from matplotlib import pyplot from distinct_colours import get_distinct Second_Asymptotic_Giant_Branch = 6 | units.stellar_type HeWhiteDwarf = 10 | units.stellar_type def stellar_remnant(stellar): remnant = True if stellar.particles[0].stellar_type < HeWhiteDwarf \ or stellar.particles[0].stellar_type > 11|units.stellar_type: remnant = False return remnant colors = get_distinct(11) def get_color_from_stellar_type(stype): st = stype.value_in(units.stellar_type) if st > 10: st = 10 return colors[st] def stellar_core_temperature_and_density(M, z=0.02, t_max=10|units.Myr): rho_core = [] T_core = [] color = [] check = 0 ncheck = 100 ###BOOKLISTSTART1### stellar = MESA() stellar.parameters.metallicity = z star = stellar.particles.add_particle(Particle(mass=M)) while not stellar_remnant(stellar) and star.age < t_max: stellar.evolve_model() nzones = star.get_number_of_zones() rhoc = star.get_density_profile(nzones)[0] Tc = star.get_temperature_profile(nzones)[0] ###BOOKLISTSTOP1### rho_core.append(rhoc.number) T_core.append(Tc.number) color.append(get_color_from_stellar_type(star.stellar_type)) check += 1 if check == ncheck: check = 0 try: x = open('STOP') stop = True except: stop = False if stop: break ###BOOKLISTSTART2### print(star.age.in_(units.Myr), rhoc, Tc, star.stellar_type) stellar.stop() ###BOOKLISTSTOP2### return rho_core, T_core, color if __name__ in ('__main__'): Mlist = [1, 10, 100] | units.MSun tmax = [1.2137e4, 22.6, 3.08064994] | units.Myr z = 0.02 for i in range(len(Mlist)): M = Mlist[i] rhoc, Tc, color = stellar_core_temperature_and_density(M, z, tmax[i]) size = 4*(math.log10(M.value_in(units.MSun))+1) print('size =', size) pyplot.scatter(rhoc, Tc, c=color, s=size) fontsize = 12 pyplot.text(20., 1.5e7, '$1\,M_\odot$', fontsize=fontsize) pyplot.text(1.e2, 7.0e7, '$10\,M_\odot$', fontsize=fontsize) pyplot.text(4.e4, 1.6e9, '$100\,M_\odot$', fontsize=fontsize) pyplot.xlabel('core density [g/cm$^3$]') pyplot.ylabel('core temperature [K]') pyplot.xlim(1., 1.e7) pyplot.ylim(1.e7, 1.e10) pyplot.xscale('log') pyplot.yscale('log') save_file = 'plot_core_temperature_density.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') #pyplot.show()
2,649
26.894737
77
py
amuse
amuse-main/examples/textbook/gravity_stellar_minimal.py
from amuse.lab import * from amuse.units.optparse import OptionParser def main(N, t_end, W0, Rvir, Mmin, Mmax, z): ###BOOKLISTSTART1### masses = new_salpeter_mass_distribution(N, Mmin, Mmax) Mtot_init = masses.sum() converter = nbody_system.nbody_to_si(Mtot_init, Rvir) bodies = new_king_model(N, W0, convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) stellar = SSE() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) bodies.radius = stellar.particles.radius gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) channel_from_stellar_to_framework \ = stellar.particles.new_channel_to(bodies) channel_from_stellar_to_gravity \ = stellar.particles.new_channel_to(gravity.particles) channel_from_gravity_to_framework \ = gravity.particles.new_channel_to(bodies) ###BOOKLISTSTOP1### filename = "bodies.hdf5" ###BOOKLISTSTART2### Etot_init = gravity.kinetic_energy + gravity.potential_energy dE_gr = 0 | Etot_init.unit time = 0.0 | t_end.unit dt = stellar.particles.time_step.amin() while time < t_end: dt = min(dt, t_end-time) stellar.evolve_model(time + dt/2) channel_from_stellar_to_gravity.copy() Etot_gr = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time + dt) dE_gr += (gravity.kinetic_energy + gravity.potential_energy - Etot_gr) stellar.evolve_model(time + dt) channel_from_stellar_to_gravity.copy() channel_from_gravity_to_framework.copy() time += dt write_set_to_file(bodies, filename) ###BOOKLISTSTOP2### Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_init-Etot Mtot = bodies.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtot_init, ")", end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE/E=", (Etot_init-Etot)/Etot, end=' ') print("(dE[gr]/E=", dE_gr/Etot, ",", end=' ') print("dE[se]/E=", (Etot_init-Etot-dE_gr)/Etot, ")") Etot_init -= dE gravity.stop() stellar.stop() def new_option_parser(): result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [100]") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float",default = 100 | units.MSun, help="maximal stellar mass [100] MSun") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float",default = 0.1|units.MSun, help="minimal stellar mass [0.1] MSun") result.add_option("-R", unit=units.parsec, dest="Rvir", type="float",default = 1.0|units.parsec, help="cluser virial radius [1] in parsec") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 1.0|units.Myr, help="end time of the simulation [1] Myr") result.add_option("-W", dest="W0", type="float", default = 7.0, help="structure parameter for King model [7]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,607
35.444444
78
py
amuse
amuse-main/examples/textbook/supernova_grid.py
import numpy from amuse.lab import * #from amuse import plot from amuse.ext import cloud from matplotlib import pyplot from amuse import datamodel from amuse.ext.sph_to_grid import convert_SPH_to_grid from amuse.community.capreole.interface import Capreole from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits def plot_grid(grid, time= 0.0|units.day): pyplot.rcParams.update({'font.size': 30}) figure = pyplot.figure(figsize=(12, 12)) halfway = len(grid.rho[...,0,0])/2 rho = grid.rho[:,:,halfway].value_in(units.g/units.cm**3) print("Extrema density:", halfway, rho.min(), rho.max()) max_dens = rho.max() # max_dens = 32 plot = figure.add_subplot(1,1,1) # cax = plot.imshow(rho, interpolation='nearest', origin = 'lower', extent=[-5, 5, -5, 5], cmap="hot") cax = plot.imshow(rho, interpolation='bicubic', origin = 'lower', extent=[-5, 5, -5, 5], cmap="hot") cbar = figure.colorbar(cax, ticks=[1.e-8, 0.5*max_dens, max_dens], orientation='vertical', fraction=0.045) rmin = 0.0 rmid = "%.1f" % (0.5*max_dens) rmax = "%.1f" % (max_dens) # cbar.ax.set_yticklabels(['Low', ' ', 'High']) # horizontal colorbar cbar.ax.set_yticklabels([rmin, ' ', rmax]) # horizontal colorbar cbar.set_label('mid-plane density [$g/cm^3$]', rotation=270) pyplot.xlabel("x [R$_\odot$]") pyplot.ylabel("y [R$_\odot$]") t = int(time.value_in(units.s)) filename = "supernova_grid_T"+str(t)+".png" figure.savefig(filename) # pyplot.show() def setup_sph_code(sph_code, N, L, rho, u): converter = ConvertBetweenGenericAndSiUnits(L, rho, constants.G) sph_code = sph_code(converter, mode = 'periodic')#, redirection = 'none') sph_code.parameters.periodic_box_size = 10.0 | units.parsec plummer = new_plummer_gas_model(N, convert_nbody=converter) plummer = plummer.select(lambda r: r.length()<0.5*L,["position"]) N = len(plummer) print("N=", len(plummer)) plummer.mass = (rho * L**3) / N gas = Particles(N) gas.mass = 0.001*(rho * L**3) / N numpy.random.seed(12345) gas.x = L * numpy.random.uniform(0.0, 1.0, N) gas.y = L * numpy.random.uniform(0.0, 1.0, N) gas.z = L * numpy.random.uniform(0.0, 1.0, N) gas.vx = numpy.zeros(N) | units.cm / units.s gas.vy = numpy.zeros(N) | units.cm / units.s gas.vz = numpy.zeros(N) | units.cm / units.s gas.u = u if isinstance(sph_code, Fi): sph_code.parameters.self_gravity_flag = False sph_code.parameters.timestep = 0.1 | generic_unit_system.time gas.h_smooth = L / N**(1/3.0) gas.position -= 0.5 * L sph_code.gas_particles.add_particles(gas) sph_code.gas_particles.add_particles(plummer) sph_code.commit_particles() return sph_code def main(stellar_mass, stellar_radius, core_mass, core_radius, t_end, dt, resolution): grid_size = 10 * stellar_radius hydro = initialize_grid_code(resolution, grid_size) grid = initialize_grid(stellar_mass, stellar_radius, core_mass, core_radius, resolution, grid_size) cth = grid.new_channel_to(hydro.grid) cth.copy() hydro.initialize_grid() run_grid_code(hydro, grid, t_end, dt) def initialize_grid_code(resolution, grid_size): converter = nbody_system.nbody_to_si(1|units.MSun, 1|units.RSun) instance = Athena(converter, number_of_workers=4) instance.initialize_code() instance.parameters.gamma = 5/3.0 instance.parameters.courant_number=0.3 instance.parameters.nx = resolution instance.parameters.ny = resolution instance.parameters.nz = resolution instance.parameters.length_x = grid_size instance.parameters.length_y = grid_size instance.parameters.length_z = grid_size instance.x_boundary_conditions = ("outflow", "outflow") instance.y_boundary_conditions = ("outflow", "outflow") instance.z_boundary_conditions = ("outflow", "outflow") instance.commit_parameters() return instance def initialize_grid(stellar_mass, stellar_radius, core_mass, core_radius, resolution, grid_size): n = resolution r = grid_size.value_in(units.RSun) grid = datamodel.new_regular_grid((n,n,n), [r, r, r] | units.RSun) momentum = units.kg / (units.s * units.m**2) grid_size = units.RSun energy_density = units.erg / grid_size**3 supernova_energy = 1.e+51 | units.erg stellar_energy_density = 0.01*supernova_energy/stellar_radius**3 supernova_energy_density = supernova_energy/core_radius**3 stellar_density = stellar_mass/stellar_radius**3 grid.rho = 1.e-10 * stellar_density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 1 | energy_density datamodel.Grid.add_global_vector_attribute("position", ["x","y","z"]) cloud.fill_grid_with_spherical_cloud( grid, center = [5.0, 5.0, 5.0] | units.RSun, radius = stellar_radius, rho = stellar_density, rhovx = 0.0 | momentum, rhovy = 0.0 | momentum, rhovz = 0.0 | momentum, energy = stellar_energy_density ) cloud.fill_grid_with_spherical_cloud( grid, center = [5.0, 5.0, 5.0] | units.RSun, radius = core_radius, rho = core_mass/core_radius**3, rhovx = 0.0 | momentum, rhovy = 0.0 | momentum, rhovz = 0.0 | momentum, energy = supernova_energy_density #subgridsize = 16, ) return grid def run_grid_code(hydro, grid, t_end, dt): ctg = hydro.grid.new_channel_to(grid) ctg.copy() plot_grid(grid) while hydro.model_time<t_end: print("Time=", hydro.model_time.in_(units.s)) hydro.evolve_model(hydro.model_time + dt) ctg.copy() plot_grid(grid, hydro.model_time) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.s, dest="t_end", type="float", default = 300.0|units.s, help="end time of the simulation [%default]") result.add_option("-d", unit=units.s, dest="dt", type="float", default = 50.0|units.s, help="diagnostic time step [%default]") result.add_option("-M", unit=units.MSun, dest="stellar_mass", type="float", default = 3|units.MSun, help="Mass of the star [%default]") result.add_option("-R", unit=units.RSun, dest="stellar_radius", type="float", default = 1|units.RSun, help="Radius of the star [%default]") result.add_option("-m", unit=units.MSun, dest="core_mass", type="float", default = 1.4|units.MSun, help="Mass of the stellar core [%default]") result.add_option("-n", dest="resolution", type="int", default = 256, help="Resolution of the grid [%default]") result.add_option("-r", unit=units.RSun, dest="core_radius", type="float", default = 0.1|units.RSun, help="Radius of the stellar core [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
7,421
37.65625
110
py
amuse
amuse-main/examples/textbook/plot_RLOF_triples.py
from matplotlib import pyplot from amuse.lab import * from prepare_figure import * from distinct_colours import get_distinct import numpy set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.AU, units.Myr], precision = 4, prefix = "", separator = " [", suffix = "]") def maximum_stellar_radius(): M = (10**numpy.arange(-0.2, 2, 0.05)) | units.MSun R = [] | units.AU for mi in M: stellar = SeBa() s = Particle() s.mass = mi stellar.particles.add_particle(s) rmax = 0|units.AU while stellar.particles[0].stellar_type<9|units.stellar_type: stellar.evolve_model() rmax = max(rmax, stellar.particles[0].radius) print("Time=", mi, stellar.particles[0].mass, \ stellar.model_time, stellar.particles[0].radius) R.append(rmax) return M, R names = [r"$\tau$ CMa", "V* CQ Dra", r"$\xi$ Tau", "V* V1334 Cyg", "V* DL Vir", "V* d Ser", "HD 97131", "KIC002856960"] Mprim = [50.0, 6.3, 5.5, 4.4, 3.68, 2.5, 1.5, 0.76] | units.MSun Rprim = [0.95, 2.64, 0.42, 3.99, 2.34, 0.62, 0.26, 0.12]| units.AU colors = get_distinct(4) figure = pyplot.figure(figsize=(16, 12)) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) M, Rmax = maximum_stellar_radius() x_label = "m [$M_\odot$]" y_label = "$r [AU]$" pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.semilogx() pyplot.semilogy() pyplot.xlim(0.6, 100.0) pyplot.ylim(0.07, 20.0) pyplot.scatter(Mprim.value_in(units.MSun), Rprim.value_in(units.AU), c=colors[0], lw=0, s=300) pyplot.plot(M.value_in(units.MSun), Rmax.value_in(units.AU), c=colors[1], lw=4) for i in range(len(names)): pyplot.text(1.1*Mprim[i].value_in(units.MSun), 0.9*Rprim[i].value_in(units.AU), names[i], fontsize=20) save_file = 'fig_RLOF_triples_R.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
2,082
32.596774
75
py
amuse
amuse-main/examples/textbook/earthorbitvariation.py
from amuse.lab import * from amuse.ext.solarsystem import solar_system_in_time from prepare_figure import single_frame, figure_frame, \ set_tickmarks, get_distinct def integrate_solar_system(particles, end_time): convert_nbody = nbody_system.nbody_to_si(particles.mass.sum(), particles[1].position.length()) gravity = Huayno(convert_nbody) gravity.particles.add_particles(particles) SunEarth = Particles() SunEarth.add_particle(particles[0]) SunEarth.add_particle(particles[3]) channel_from_to_SunEarth = gravity.particles.new_channel_to(SunEarth) from matplotlib import pyplot, rc x_label = "$a-a_0$ [AU]" y_label = "eccentricty" figure = single_frame(x_label, y_label, xsize=14, ysize=10) from amuse.plot import scatter from matplotlib import pyplot, rc kep = Kepler(convert_nbody) kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() a0 = a color = get_distinct(1) scatter((a-a0).in_(units.AU), e, c=color[0], lw=0) pyplot.text((a-a0).value_in(units.AU)-0.0003, e, "{0:.0f}".format(0.001*gravity.model_time.value_in(units.yr))+"kyr") dt = 100 | units.yr t_diag = 10000 |units.yr while gravity.model_time < end_time: kep.initialize_from_particles(SunEarth) a, e = kep.get_elements() scatter((a-a0).in_(units.AU), e, c=color[0], lw=0, s=80) time = gravity.model_time if time > t_diag: t_diag += 10000 |units.yr fmt = "{0:.0f}".format(0.001*time.value_in(units.yr))+" kyr" if time < 100|units.yr: pyplot.text(-0.0006, e, fmt) elif time < 15000|units.yr: pyplot.text(0.0003, e, fmt) elif time < 25000|units.yr: pyplot.text(0.0017, e, fmt) elif time < 35000|units.yr: pyplot.text(0.0031, e, fmt) elif time < 45000|units.yr: pyplot.text(0.0028, e, fmt) elif time < 55000|units.yr: pyplot.text(0.0021, e, fmt) elif time < 65000|units.yr: pyplot.text(0.0017, e+0.002, fmt) elif time < 75000|units.yr: pyplot.text(0.0014, e-0.002, fmt) else: pass gravity.evolve_model(gravity.model_time + dt) channel_from_to_SunEarth.copy() gravity.stop() pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.xlim(-0.001, 0.004) file = 'EarthOrbitVariation.png' pyplot.savefig(file) print('\nSaved figure in file', file,'\n') pyplot.show() return if __name__ in ('__main__','__plot__'): particles = solar_system_in_time(time_JD=2474649.5|units.day) integrate_solar_system(particles, 84000 | units.yr)
2,857
31.850575
80
py
amuse
amuse-main/examples/textbook/plot_stellar_massloss_response.py
""" Visualization for simple N-body integration. Reads particle set from file (nbody.hdf5) and prints subsequent frames. """ import sys import numpy from matplotlib import pyplot from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct #filenames = ["Zeta_M1MSun_dmdt.out", "Zeta_M2MSun_dmdt.out"] filenames = ["Zeta_M1MSun_dmdt.data"] ls = ["-", "-", "-", "-.", "--"] lw = [6, 4, 4, 2, 2] c = ["b", "k", "g", "b", "r", ] dmdt = [-10000, -100, -1, -0.01, -0.0001] zz = 1 # index for the value of zeta zt = 2# index for the time zm = 8 # index for the core mass zd = 12 # index for the value of dmdt def process_file(filename, mdot): t = [] z = [] tms = 0 for line in filename: if "mpi" not in line and "Zeta" in line: l = line.split() if float(l[zd])==mdot: #print l t.append(float(l[zt])) z.append(float(l[zz])) if "Main Sequence" in line: tms = t[-1] return t, z, tms def main(): x_label = "$log_{10}[(t_{end}-t)/t_{MS}]$" y_label = "$\zeta$" figure = single_frame(x_label, y_label, logx=False, logy=False, xsize=14, ysize=10) color = get_distinct(12) pyplot.text(-2.2, 0.8, "giant branch") pyplot.text(-0.1, 0.8, "main sequence") pyplot.xlim(0.5, -4.) pyplot.ylim(-0.6, 1.2) fii = 0 ti=0 for dmi in dmdt: for fi in filenames: f = open(fi) for line in f: t, z, tms = process_file(f, dmi) #print t, z, tms for i in range(len(t)): if z[i]<0: ti = i break for i in range(len(t)): t[i] = numpy.log10((t[-1]-t[i])/tms) # pyplot.scatter(t, z) pyplot.plot(t[ti:], z[ti:], c=color[fii], ls=ls[fii], lw=lw[fii]) f.close() fii += 1 pyplot.show() #pyplot.savefig("fig_stellar_massloss_response") if __name__ in ('__main__', '__plot__'): main()
2,143
27.972973
87
py
amuse
amuse-main/examples/textbook/core_temperature_density.py
from amuse.lab import * Second_Asymptotic_Giant_Branch = 6 | units.stellar_type HeWhiteDwarf = 10 | units.stellar_type def stellar_remnant(stellar): remnant = True if stellar.particles[0].stellar_type<HeWhiteDwarf or stellar.particles[0].stellar_type>11|units.stellar_type: remnant = False return remnant def stellar_core_temperature_and_density(M, z): stellar = MESA() stellar.parameters.metallicity = z star = stellar.particles.add_particle(Particle(mass=M)) while not stellar_remnant(stellar): stellar.evolve_model() T_core = star.get_temperature_profile(star.get_number_of_zones())[0] density_core = star.get_density_profile(star.get_number_of_zones())[0] T_surface = star.get_temperature_profile(star.get_number_of_zones())[-1] density_surface = star.get_density_profile(star.get_number_of_zones())[-1] print(star.age, T_surface, density_surface, T_core, density_core) stellar.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.0 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() stellar_core_temperature_and_density(**o.__dict__)
1,554
36.02381
113
py
amuse
amuse-main/examples/textbook/plot_M67withBSS_tracks.py
""" Minimal routine for running a stellar evolution code. """ from amuse.lab import * from matplotlib import pyplot import plot_M67Data from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct TBSS = [6170, 6820, 6675, 7050, 6650] LBSS = [12.259, 11.078, 12.127, 11.226, 12.892] def single_star_evolution(M, z, model_time): stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=M)) stellar.commit_particles() initial_luminosity = stellar.particles.luminosity dt = 1 | units.Myr time = 0 | units.Myr L = [] | units.LSun T = [] | units.K while stellar.particles[0].age<model_time: time += dt stellar.evolve_model(time) L.append(stellar.particles[0].luminosity) T.append(stellar.particles[0].temperature) final_luminosity = stellar.particles.luminosity print("L(t=0)=", initial_luminosity, \ ", L (t=", stellar.particles.age, ")=", \ final_luminosity, stellar.particles.radius) stellar.stop() return L, T def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.7 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-t", unit = units.Myr, dest="model_time", type="float", default = 4000.0|units.Myr, help="end time of the simulation [4.7] %unit") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() x_label = "T [$K$]" y_label = "L [$L_\odot$]" figure = single_frame(x_label, y_label, logx=False, logy=True, xsize=14, ysize=10) color = get_distinct(6) L, T = single_star_evolution(M=1.4|units.MSun, z=0.04, model_time=4|units.Gyr) pyplot.plot(T.value_in(units.K),L.value_in(units.LSun), c=color[0]) L, T = single_star_evolution(**o.__dict__) pyplot.plot(T.value_in(units.K),L.value_in(units.LSun), c=color[4]) m67 = plot_M67Data.Cluster() m67.read() pyplot.scatter(m67.Teff, m67.L, c=color[1], lw=0, s=100) pyplot.scatter(TBSS, LBSS, c=color[3], lw=0, s=250) pyplot.scatter(TBSS[3], LBSS[3], c=color[2], lw=0, s=250) pyplot.xlim(9000, 4000) pyplot.ylim(1, 50) save_file = 'fig_M67withBSS_tracks.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show()
2,775
32.853659
72
py
amuse
amuse-main/examples/textbook/sun_venus_earth.py
###BOOKLISTSTART1### from amuse.lab import Particles, units def sun_venus_and_earth(): particles = Particles(3) sun = particles[0] sun.mass = 1.0 | units.MSun sun.radius = 1.0 | units.RSun sun.position = (855251, -804836, -3186) |units.km sun.velocity = (7.893, 11.894, 0.20642) | (units.m/units.s) venus = particles[1] venus.mass = 0.0025642 | units.MJupiter venus.radius = 3026.0 | units.km venus.position = (-0.3767, 0.60159, 0.03930) | units.AU venus.velocity = (-29.7725, -18.849, 0.795) | units.kms earth = particles[2] earth.mass = 1.0 | units.MEarth earth.radius = 1.0 | units.REarth earth.position = (-0.98561, 0.0762, -7.847e-5) | units.AU earth.velocity = (-2.927, -29.803, -0.0005327) | units.kms particles.move_to_center() return particles ###BOOKLISTSTOP1### ###BOOKLISTSTART2### def integrate_solar_system(particles, end_time): from amuse.lab import Huayno, nbody_system convert_nbody = nbody_system.nbody_to_si(particles.mass.sum(), particles[1].position.length()) gravity = Huayno(convert_nbody) gravity.particles.add_particles(particles) venus = gravity.particles[1] earth = gravity.particles[2] x_earth = [] | units.AU y_earth = [] | units.AU x_venus = [] | units.AU y_venus = [] | units.AU while gravity.model_time < end_time: gravity.evolve_model(gravity.model_time + (1 | units.day)) x_earth.append(earth.x) y_earth.append(earth.y) x_venus.append(venus.x) y_venus.append(venus.y) gravity.stop() return x_earth, y_earth, x_venus, y_venus ###BOOKLISTSTOP2### ###BOOKLISTSTART3### def plot_track(xe,ye,xv,yv, output_filename): from matplotlib import pyplot figure = pyplot.figure(figsize=(10, 10)) pyplot.rcParams.update({'font.size': 30}) plot = figure.add_subplot(1,1,1) ax = pyplot.gca() ax.minorticks_on() ax.locator_params(nbins=3) x_label = 'x [au]' y_label = 'y [au]' pyplot.xlabel(x_label) pyplot.ylabel(y_label) plot.scatter([0.0], [0.0], color='y', lw=8) plot.plot(xe.value_in(units.AU), ye.value_in(units.AU), color = 'b') plot.plot(xv.value_in(units.AU), yv.value_in(units.AU), color = 'r') plot.set_xlim(-1.3, 1.3) plot.set_ylim(-1.3, 1.3) save_file = 'sun_venus_earth.png' pyplot.savefig(save_file) print('\nSaved figure in file', save_file,'\n') pyplot.show() ###BOOKLISTSTOP3### def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-o", dest="output_filename", default ="SunVenusEarth", help="output filename [%default]") return result if __name__ in ('__main__','__plot__'): o, arguments = new_option_parser().parse_args() particles = sun_venus_and_earth() xe,ye, xv,yv = integrate_solar_system(particles, 2 | units.yr) plot_track(xe, ye, xv, yv, o.output_filename)
3,063
30.587629
76
py
amuse
amuse-main/examples/textbook/plot_Nbody_precision.py
from amuse.lab import * import numpy from distinct_colours import get_distinct from matplotlib import pyplot def energy_error_of_integrated_Nbody_system(code, particles, end_time, precision): gravity = code(number_of_workers=4) gravity.parameters.timestep_parameter = precision #gravity.parameters.timestep = precision | nbody_system.time gravity.particles.add_particles(particles) channel_from_to_framework = gravity.particles.new_channel_to(particles) E0 = gravity.particles.potential_energy(G=nbody_system.G) E0 += gravity.particles.kinetic_energy() gravity.evolve_model(end_time) channel_from_to_framework.copy() Et = gravity.particles.potential_energy(G=nbody_system.G) \ + gravity.particles.kinetic_energy() gravity.stop() de = (Et-E0)/E0 return de def get_dE(code, precision, t_end): dE = [] for pri in precision: dEi = energy_error_of_integrated_Nbody_system(code, particles, t_end, pri) dE.append(abs(dEi)) print("integrated with precision=", pri, "dE/E=", dEi) return dE if __name__ in ('__main__','__plot__'): numpy.random.seed(31415) particles = new_plummer_model(1000) precision = 10.**numpy.linspace(0., -3., 10) t_end = 1.0| nbody_system.time cols = get_distinct(2) print('ph4') code = ph4 dE = get_dE(code, precision, t_end) pyplot.scatter(precision, dE, c=cols[0], lw=0, s=50, marker='o') print('BHTree') code = BHTree dE = get_dE(code, precision, t_end) pyplot.scatter(precision, dE, c=cols[1], lw=0, s=50, marker='^') t0 = 0.8 t1 = 0.02 ep = 4.e-5 eb = 0.07 pyplot.plot([t0, t1], [ep, ep*(t1/t0)**4], c=cols[0], lw=2) pyplot.plot([t0, t1], [eb, eb*(t1/t0)**2], c=cols[1], lw=2) pyplot.xlabel('time step parameter') pyplot.xlim(1.e-4, 3.) pyplot.xscale('log') pyplot.ylabel('$|E(t)-E(0)|/|E(0)|$') pyplot.ylim(1.e-15, 10.) pyplot.yscale('log') save_file = 'precision_N100t1.png' pyplot.savefig(save_file) print("\nOutput saved in", save_file) pyplot.show()
2,236
28.434211
75
py
amuse
amuse-main/examples/textbook/gravity_class.py
import os.path import math import numpy from amuse.lab import * from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.ext.evrard_test import uniform_unit_sphere import time from initialize_sstars import * from calculate_orbital_parameters import calculate_orbital_parameters from amuse.community.mercury.interface import Mercury from amuse.community.mikkola.interface import Mikkola from amuse.units.optparse import OptionParser from amuse.community.adaptb.interface import Adaptb class Gravity: def __init__(self, gravity_code, particles): self.converter=nbody_system.nbody_to_si(1|units.MSun,1|units.AU) self.code = gravity_code(self.converter) self.code.initialize_code() self.get_gravity_at_point = self.code.get_gravity_at_point self.get_potential_at_point = self.code.get_potential_at_point if hasattr(self.code.parameters, "bs_tolerance"): self.code.parameters.bs_tolerance = 1.0e-10 self.code.parameters.word_length = 512 if hasattr(self.code.parameters, "lightspeed"): self.code.parameters.lightspeed = 0 | units.kms for pi in particles: self.code.particles.add_particles(pi) if isinstance(self.code, Mercury): self.code.commit_particles() self.channel_to_framework = [] self.channel_from_framework = [] for pi in particles: self.channel_to_framework.append(self.code.particles.new_channel_to(pi)) self.channel_from_framework.append(pi.new_channel_to(self.code.particles)) @property def model_time(self): return self.code.model_time @property def stop(self): return self.code.stop @property def particles(self): return self.code.particles def evolve_model(self, model_time): for gi in self.channel_from_framework: gi.copy() #gi.copy_attributes("mass") self.code.evolve_model(model_time) for gi in self.channel_to_framework: gi.copy() def print_diagnostics(model_time, particles, converter): bh = particles[0] stars = particles[1] for si in stars: a, e, m0, m1 = calculate_orbital_parameters(bh[0], si, converter) print("Orbital elements for star ", si.name, model_time.in_(units.yr), a.in_(units.AU), e, bh[0].mass.in_(units.MSun), si.mass.in_(units.MSun)) def main(t_end=1687|units.yr, n_steps=1, filename=None): black_hole, stars = initialize_sstars(2012|units.yr, S_name, S_a_arcsec, S_ecc, S_inc, S_omra, S_Omega, S_tperi, S_Period) gravity = Gravity(Mercury, [black_hole, stars]) # gravity = Gravity(Mikkola, [black_hole, stars]) print_diagnostics(gravity.model_time, [black_hole, stars], gravity.converter) if filename: write_set_to_file(gravity.particles, filename, "hdf5") dt = t_end/float(n_steps) while gravity.model_time < t_end: gravity.evolve_model(gravity.model_time+dt) if filename: write_set_to_file(gravity.particles, filename, 'hdf5') print_diagnostics(gravity.model_time, [black_hole, stars], gravity.converter) gravity.stop() def new_option_parser(): result = OptionParser() result.add_option("-n", dest="n_steps", type="int", default = 1, help="number of diagnostics time steps [10]") result.add_option("-f", dest="filename", default = None, help="write output filename") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 0.000001|units.Myr, help="end time of the simulation [0.0000001] %unit") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,827
37.666667
151
py
amuse
amuse-main/examples/textbook/prepare_figure.py
from matplotlib import pyplot #import seaborn # These are the "Tableau 20" colors as RGB. tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # colors almost_black = '#262626' blue='#3D52A1' light_blue='#88CCEE' cyan='#44AA99' green='#117733' red='#AE1C3E' sand='#999933' yellow='#DDCC77' pink='#CC6677' crimson='#882255' violet='#AA4499' brown='#661100' steal='#6699CC' rose='#AA4466' sky_blue='#4477AA' # -*- coding: iso-8859-1 -*- """ Colour-blind proof distinct colours module, based on work by Paul Tol Pieter van der Meer, 2011 SRON - Netherlands Institute for Space Research """ # colour table in HTML hex format hexcols = ['#332288', '#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77', '#CC6677', '#882255', '#AA4499', '#661100', '#6699CC', '#AA4466', '#4477AA'] greysafecols = ['#809BC8', '#FF6666', '#FFCC66', '#64C204'] xarr = [[12], [12, 6], [12, 6, 5], [12, 6, 5, 3], [0, 1, 3, 5, 6], [0, 1, 3, 5, 6, 8], [0, 1, 2, 3, 5, 6, 8], [0, 1, 2, 3, 4, 5, 6, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 9, 6, 7, 8], [0, 10, 1, 2, 3, 4, 5, 9, 6, 7, 8], [0, 10, 1, 2, 3, 4, 5, 9, 6, 11, 7, 8]] # get specified nr of distinct colours in HTML hex format. # in: nr - number of colours [1..12] # returns: list of distinct colours in HTML hex def get_distinct(nr): # check if nr is in correct range if nr < 1 or nr > 12: print("wrong nr of distinct colours!") return # get list of indices lst = xarr[nr-1] # generate colour list by stepping through indices and looking them # up in the colour table i_col = 0 col = [0] * nr for idx in lst: col[i_col] = hexcols[idx] i_col+=1 return col # display usage information and produce example plot. if __name__ == '__main__': import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt print(__doc__) print("usage examples: ") print("print distinct_colours.get_distinct(2)") print((get_distinct(2))) print("print distinct_colours.greysafecols") print(greysafecols) print("\ngenerating example plot: distinct_colours_example.png") plt.close() t = np.arange(0.0, 2.0, 0.01) n = 12 cols = get_distinct(n) d = 2./n for i in range(n): s = np.sin(i*d*np.pi*t) plt.plot(t, s, linewidth=2.0, c=cols[i]) plt.xlabel('time (s)') plt.ylabel('voltage (mV)') plt.title('Distinct colours example') plt.grid(True) plt.savefig("distinct_colours_example.pdf") def figure_frame(x_label, y_label, xsize=12, ysize=10): figure = pyplot.figure(figsize=(xsize, ysize)) plot = figure.add_subplot(1,1,1) ax = pyplot.gca() ax.minorticks_on() # switch on the minor ticks ax.locator_params(nbins=3) pyplot.xlabel(x_label) pyplot.ylabel(y_label) return figure, ax from cycler import cycler def single_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=10, ymin=-1, ymax=-1): pyplot.rcParams.update({'font.size': 20}) #pyplot.rcParams['axes.color_cycle'] = [blue, green, red, sand, light_blue, # pink, crimson, violet, brown, # steal, rose, yellow, cyan ] pyplot.rcParams['axes.prop_cycle'] \ = (cycler('color', [blue, green, red, sand, light_blue, pink, crimson, violet, brown, steal, rose, yellow, cyan ])) figure = pyplot.figure(figsize=(xsize, ysize)) ax = pyplot.gca() ax.get_yaxis().get_major_formatter().set_useOffset(False) pyplot.xlabel(x_label) pyplot.ylabel(y_label) if ymax>0: pyplot.ylim(ymin, ymax) set_tickmarks(ax) ax.xaxis._autolabelpos = True ax.yaxis._autolabelpos = True if logx is True: ax.set_xscale('log') ax.get_xaxis().set_tick_params(pad=7) if logy is True: ax.set_yscale('log') ax.get_yaxis().set_tick_params(pad=7) return figure def quad_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12): f, ((ax1, ax2), (ax3, ax4)) = pyplot.subplots(2, 2, sharex='col', sharey='row', figsize=(8,8)) set_tickmarks(ax1) ax1.locator_params(nbins=3) set_tickmarks(ax2) ax2.locator_params(nbins=3) set_tickmarks(ax3) ax3.locator_params(nbins=3) set_tickmarks(ax4) ax4.locator_params(nbins=3) ax1.xaxis.set_label_position("top") ax2.xaxis.set_label_position("top") ax1.set_xlabel(x_label) ax2.set_xlabel(x_label) ax2.yaxis.set_label_position("right") ax4.yaxis.set_label_position("right") ax2.set_ylabel(y_label) ax4.set_ylabel(y_label) return f, ax1, ax2, ax3, ax4 def _quad_frame(x_label, y_label, logx=False, logy=False, xsize=12, ysize=12): pyplot.rcParams.update({'font.size': 25}) #pyplot.rcParams['axes.color_cycle'] = [blue, green, red, sand, light_blue, # pink, crimson, violet, brown, # steal, rose, yellow, cyan ] pyplot.rcParams['axes.prop_cycle'] \ = (cycler('color', [blue, green, red, sand, light_blue, pink, crimson, violet, brown, steal, rose, yellow, cyan ])) f, ((ax1, ax2), (ax3, ax4)) = pyplot.subplots(2, 2, sharex='col', sharey='row', figsize=(12,12)) set_tickmarks(ax1) set_tickmarks(ax2) set_tickmarks(ax3) set_tickmarks(ax4) ax1.xaxis.set_label_position("top") ax2.xaxis.set_label_position("top") ax1.set_xlabel(x_label) ax2.set_xlabel(x_label) ax2.yaxis.set_label_position("right") ax4.yaxis.set_label_position("right") ax2.set_ylabel(y_label) ax4.set_ylabel(y_label) return f, ax1, ax2, ax3, ax4 def set_tickmarks(ax): ax.minorticks_on() return ax.tick_params('both', length=15, width=2, which='major') ax.tick_params('both', length=6, width=1, which='minor') ax.locator_params(nbins=3) ax.tick_params(axis='x', which='major', pad=20) ax.tick_params(axis='y', which='major', pad=20) ax.margins(0.25, tight=True)
6,734
29.613636
80
py