markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
μ–΄λ–€ ν•¨μˆ˜μΈκ°€? help λ₯Ό μ΄μš©ν•˜μ—¬ ν™•μΈν•˜λ©΄ λ‹€μŒκ³Ό κ°™λ‹€.
help(g) g
ref_materials/excs/Lab-07.ipynb
liganega/Gongsu-DataSci
gpl-3.0
즉, 인자λ₯Ό ν•˜λ‚˜ λ°›λŠ” ν•¨μˆ˜μ΄λ©° f_expλ₯Ό μ΄μš©ν•΄ μ •μ™Έλ˜μ—ˆμŒμ„ μ•Œ 수 μžˆλ‹€. μ‹€μ œλ‘œ gλŠ” μ•„λž˜μ™€ 같이 μ •μ˜λ˜μ–΄ μžˆλ‹€. gλ₯Ό μ •μ˜ν•˜κΈ° μœ„ν•΄ fun_2_fun(f) ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ μ‚¬μš©λœ 인자 f λŒ€μ‹ μ— exp2 ν•¨μˆ˜λ₯Ό μ‚½μž…ν•˜μ˜€κΈ° λ•Œλ¬Έμ— gκ°€ μ•„λž˜μ™€ 같이 μ •μ˜λœ ν•¨μˆ˜μž„μ„ μ•Œ 수 μžˆλ‹€. g(x) = fun_2_fun(exp2) = f_exp(x) # f_exp λ₯Ό μ •μ˜ν•  λ•Œ exp2 κ°€ μ‚¬μš©λ¨μ— μ€‘μ˜ = exp2(x) ** x = (x**2) ** x = x ** (2*x) μ—°μŠ΅ 6 κ²¬λ³Έλ‹΅μ•ˆ 2
def fun_2_fun(f): return lambda x: f(x) ** x print(f1(2)) print(fun_2_fun(f1)(2))
ref_materials/excs/Lab-07.ipynb
liganega/Gongsu-DataSci
gpl-3.0
First we will make a default NormalFault.
grid = RasterModelGrid((6, 6), xy_spacing=10) grid.add_zeros("topographic__elevation", at="node") nf = NormalFault(grid) plt.figure() imshow_grid(grid, nf.faulted_nodes.astype(int), cmap="viridis") plt.plot(grid.x_of_node, grid.y_of_node, "c.") plt.show()
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
This fault has a strike of NE and dips to the SE. Thus the uplifted nodes (shown in yellow) are in the NW half of the domain. The default NormalFault will not uplift the boundary nodes. We change this by using the keyword argument include_boundaries. If this is specified, the elevation of the boundary nodes is calcul...
nf = NormalFault(grid, include_boundaries=True) plt.figure() imshow_grid(grid, nf.faulted_nodes.astype(int), cmap="viridis") plt.plot(grid.x_of_node, grid.y_of_node, "c.") plt.show()
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
We can add functionality to the NormalFault with other keyword arguments. We can change the fault strike and dip, as well as specify a time series of fault uplift through time.
grid = RasterModelGrid((60, 100), xy_spacing=10) z = grid.add_zeros("topographic__elevation", at="node") nf = NormalFault(grid, fault_trace={"x1": 0, "y1": 200, "y2": 30, "x2": 600}) imshow_grid(grid, nf.faulted_nodes.astype(int), cmap="viridis")
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
By reversing the order of (x1, y1) and (x2, y2) we can reverse the location of the upthrown nodes (all else equal).
grid = RasterModelGrid((60, 100), xy_spacing=10) z = grid.add_zeros("topographic__elevation", at="node") nf = NormalFault(grid, fault_trace={"y1": 30, "x1": 600, "x2": 0, "y2": 200}) imshow_grid(grid, nf.faulted_nodes.astype(int), cmap="viridis")
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
We can also specify complex time-rock uplift rate histories, but we'll explore that later in the tutorial. Next let's make a landscape evolution model with a normal fault. Here we'll use a HexModelGrid to highlight that we can use both raster and non-raster grids with this component. We will do a series of three nume...
# here are the parameters to change K = 0.0005 # stream power coefficient, bigger = streams erode more quickly U = 0.0001 # uplift rate in meters per year dt = 1000 # time step in years dx = 10 # space step in meters nr = 60 # number of model rows nc = 100 # number of model columns # instantiate the grid grid ...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
As we can see, the upper left portion of the grid has been uplifted an a stream network has developed over the whole domain. How might this change when we also uplift the boundaries nodes?
# instantiate the grid grid = HexModelGrid((nr, nc), 10, node_layout="rect") # add a topographic__elevation field with noise z = grid.add_zeros("topographic__elevation", at="node") z[grid.core_nodes] += 100.0 + np.random.randn(grid.core_nodes.size) fr = FlowAccumulator(grid) fs = FastscapeEroder(grid, K_sp=K) nf = No...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
We can see that when the boundary nodes are not included, the faulted region is impacted by the edge boundary conditions differently. Depending on your application, one or the other of these boundary condition options may suite your problem better. The last thing to explore is the use of the fault_rate_through_time pa...
time = ( np.array( [ 0.0, 7.99, 8.00, 8.99, 9.0, 17.99, 18.0, 18.99, 19.0, 27.99, 28.00, 28.99, 29.0, ] ) * 10 * dt ) rate = np.arra...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
The default value for uplift rate is 0.001 (units unspecified as it will depend on the x and t units in a model, but in this example we assume time units of years and length units of meters). This will result in a total of 300 m of fault throw over the 300,000 year model time period. This amount of uplift can also be ...
t = np.arange(0, 300 * dt, dt) rate_constant = np.interp(t, [0, 300 * dt], [0.001, 0.001]) rate_variable = np.interp(t, time, rate) cumulative_rock_uplift_constant = np.cumsum(rate_constant) * dt cumulative_rock_uplift_variable = np.cumsum(rate_variable) * dt plt.figure() plt.plot(t, cumulative_rock_uplift_constant) ...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
A technical note: Beyond the times specified, the internal workings of the NormalFault will use the final value provided in the rate array. Let's see how this changes the model results.
# instantiate the grid grid = HexModelGrid((nr, nc), 10, node_layout="rect") # add a topographic__elevation field with noise z = grid.add_zeros("topographic__elevation", at="node") z[grid.core_nodes] += 100.0 + np.random.randn(grid.core_nodes.size) fr = FlowAccumulator(grid) fs = FastscapeEroder(grid, K_sp=K) nf = No...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
As you can see the resulting topography is very different than in the case with continuous uplift. For our final example, we'll use NormalFault with a more complicated model in which we have both a soil layer and bedrock. In order to move, material must convert from bedrock to soil by weathering. First we import remai...
from landlab.components import DepthDependentDiffuser, ExponentialWeatherer # here are the parameters to change K = 0.0005 # stream power coefficient, bigger = streams erode more quickly U = 0.0001 # uplift rate in meters per year max_soil_production_rate = ( 0.001 # Maximum weathering rate for bare bedrock in ...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
Next we create the grid and run the model.
# instantiate the grid grid = HexModelGrid((nr, nc), 10, node_layout="rect") # add a topographic__elevation field with noise z = grid.add_zeros("topographic__elevation", at="node") z[grid.core_nodes] += 100.0 + np.random.randn(grid.core_nodes.size) # create a field for soil depth d = grid.add_zeros("soil__depth", at=...
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
We can also examine the soil thickness and soil production rate. Here in the soil depth, we see it is highest along the ridge crests.
# and the soil depth imshow_grid(grid, "soil__depth", cmap="viridis")
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
The soil production rate is highest where the soil depth is low, as we would expect given the exponential form.
# and the soil production rate imshow_grid(grid, "soil_production__rate", cmap="viridis")
notebooks/tutorials/normal_fault/normal_fault_component_tutorial.ipynb
landlab/landlab
mit
The data is small enough to be read into memory.
[line_no//25000] import gensim # from gensim.models.doc2vec import from collections import namedtuple SentimentDocument = namedtuple('SentimentDocument', 'words tags split sentiment') alldocs = [] # will hold all docs in original order with open('./data/new_parsed_no_spam.txt') as alldata: for line_no, line in...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Set-up Doc2Vec Training & Evaluation Models Approximating experiment of Le & Mikolov "Distributed Representations of Sentences and Documents", also with guidance from Mikolov's example go.sh: ./word2vec -train ../alldata-id.txt -output vectors.txt -cbow 0 -size 100 -window 10 -negative 5 -hs 0 -sample 1e-4 -threads 40 ...
from gensim.models import Doc2Vec import gensim.models.doc2vec from collections import OrderedDict import multiprocessing cores = multiprocessing.cpu_count() assert gensim.models.doc2vec.FAST_VERSION > -1, "this will be painfully slow otherwise" simple_models = [ # PV-DM w/concatenation - window=5 (both sides) ap...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Following the paper, we also evaluate models in pairs. These wrappers return the concatenation of the vectors from each model. (Only the singular models are trained.)
from gensim.test.test_doc2vec import ConcatenatedDoc2Vec models_by_name['dbow+dmm'] = ConcatenatedDoc2Vec([simple_models[1], simple_models[2]]) models_by_name['dbow+dmc'] = ConcatenatedDoc2Vec([simple_models[1], simple_models[0]])
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Predictive Evaluation Methods Helper methods for evaluating error rate.
import numpy as np import statsmodels.api as sm from random import sample # for timing from contextlib import contextmanager from timeit import default_timer import time @contextmanager def elapsed_timer(): start = default_timer() elapser = lambda: default_timer() - start yield lambda: elapser() end ...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Bulk Training Using explicit multiple-pass, alpha-reduction approach as sketched in gensim doc2vec blog post – with added shuffling of corpus on each pass. Note that vector training is occurring on all documents of the dataset, which includes all TRAIN/TEST/DEV docs. Evaluation of each model's sentiment-predictive powe...
from collections import defaultdict best_error = defaultdict(lambda :1.0) # to selectively-print only best errors achieved from random import shuffle import datetime alpha, min_alpha, passes = (0.025, 0.001, 20) alpha_delta = (alpha - min_alpha) / passes print("START %s" % datetime.datetime.now()) for epoch in ran...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Achieved Sentiment-Prediction Accuracy
# print best error rates achieved for rate, name in sorted((rate, name) for name, rate in best_error.items()): print("%f %s" % (rate, name))
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
In my testing, unlike the paper's report, DBOW performs best. Concatenating vectors from different models only offers a small predictive improvement. The best results I've seen are still just under 10% error rate, still a ways from the paper's 7.42%. Examining Results Are inferred vectors close to the precalculated one...
doc_id = np.random.randint(simple_models[0].docvecs.count) # pick random doc; re-run cell for more examples print('for doc %d...' % doc_id) for model in simple_models: inferred_docvec = model.infer_vector(alldocs[doc_id].words) print('%s:\n %s' % (model, model.docvecs.most_similar([inferred_docvec], topn=3)))
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
(Yes, here the stored vector from 20 epochs of training is usually one of the closest to a freshly-inferred vector for the same words. Note the defaults for inference are very abbreviated – just 3 steps starting at a high alpha – and likely need tuning for other applications.) Do close documents seem more related than ...
import random doc_id = np.random.randint(simple_models[0].docvecs.count) # pick random doc, re-run cell for more examples model = random.choice(simple_models) # and a random model sims = model.docvecs.most_similar(doc_id, topn=model.docvecs.count) # get *all* similar documents print(u'TARGET (%d): Β«%sΒ»\n' % (doc_id...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
(Somewhat, in terms of reviewer tone, movie genre, etc... the MOST cosine-similar docs usually seem more like the TARGET than the MEDIAN or LEAST.) Do the word vectors show useful similarities?
word_models = simple_models[:] import random from IPython.display import HTML # pick a random word with a suitable number of occurences while True: word = random.choice(word_models[0].index2word) if word_models[0].vocab[word].count > 10: break # or uncomment below line, to just pick a word from the rel...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Do the DBOW words look meaningless? That's because the gensim DBOW model doesn't train word vectors – they remain at their random initialized values – unless you ask with the dbow_words=1 initialization parameter. Concurrent word-training slows DBOW mode significantly, and offers little improvement (and sometimes a lit...
# assuming something like # https://word2vec.googlecode.com/svn/trunk/questions-words.txt # is in local directory # note: this takes many minutes for model in word_models: sections = model.accuracy('questions-words.txt') correct, incorrect = len(sections[-1]['correct']), len(sections[-1]['incorrect']) prin...
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Even though this is a tiny, domain-specific dataset, it shows some meager capability on the general word analogies – at least for the DM/concat and DM/mean models which actually train word vectors. (The untrained random-initialized words of the DBOW model of course fail miserably.) Slop
This cell left intentionally erroneous.
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
To mix the Google dataset (if locally available) into the word tests...
from gensim.models import Word2Vec w2v_g100b = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True) w2v_g100b.compact_name = 'w2v_g100b' word_models.append(w2v_g100b)
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
To get copious logging output from above steps...
import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) rootLogger = logging.getLogger() rootLogger.setLevel(logging.INFO)
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
To auto-reload python code while developing...
%load_ext autoreload %autoreload 2
doc2vec-IMDB.ipynb
texib/pixnet_hackathon_2015
mit
Display mode: Pandas default
beakerx.pandas_display_default() pd.read_csv('../resources/data/interest-rates.csv')
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Display mode: TableDisplay Widget
beakerx.pandas_display_table() pd.read_csv('../resources/data/interest-rates.csv')
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Recognized Formats
TableDisplay([{'y1':4, 'm3':2, 'z2':1}, {'m3':4, 'z2':2}]) TableDisplay({"x" : 1, "y" : 2})
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Programmable Table Actions
mapList4 = [ {"a":1, "b":2, "c":3}, {"a":4, "b":5, "c":6}, {"a":7, "b":8, "c":5} ] display = TableDisplay(mapList4) def dclick(row, column, tabledisplay): tabledisplay.values[row][column] = sum(map(int,tabledisplay.values[row])) display.setDoubleClickAction(dclick) def negate(row, column, tabledisplay):...
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Set index to DataFrame
df = pd.read_csv('../resources/data/interest-rates.csv') df.set_index(['m3']) df = pd.read_csv('../resources/data/interest-rates.csv') df.index = df['time'] df
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Update cell
dataToUpdate = [ {'a':1, 'b':2, 'c':3}, {'a':4, 'b':5, 'c':6}, {'a':7, 'b':8, 'c':9} ] tableToUpdate = TableDisplay(dataToUpdate) tableToUpdate tableToUpdate.values[0][0] = 99 tableToUpdate.sendModel() tableToUpdate.updateCell(2,"c",121) tableToUpdate.sendModel()
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
HTML format HTML format allows markup and styling of the cell's content. Interactive JavaScript is not supported however.
table = TableDisplay({ 'w': '$2 \\sigma$', 'x': '<em style="color:red">italic red</em>', 'y': '<b style="color:blue">bold blue</b>', 'z': 'strings without markup work fine too', }) table.setStringFormatForColum...
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Auto linking of URLs The normal string format automatically detects URLs and links them. An underline appears when the mouse hovers over such a string, and when you click it opens in a new window.
TableDisplay({'Two Sigma': 'http://twosigma.com', 'BeakerX': 'http://BeakerX.com'})
doc/python/TableAPI.ipynb
twosigma/beakerx
apache-2.0
Before we go any further let's take a look at this data by plotting it:
%matplotlib inline # plot signals import pylab as pl # abdominal signals for i in range(1,6): pl.figure(figsize=(14,3)) pl.plot(time_steps, data[:,i], 'r') pl.title('Abdominal %d' % (i)) pl.grid() pl.show() # thoracic signals for i in range(6,9): pl.figure(figsize=(14,3)) pl.plot(time_step...
doc/ipython-notebooks/ica/ecg_sep.ipynb
lisitsyn/shogun
bsd-3-clause
The peaks in the plot represent a heart beat but its pretty hard to interpret and I know I definitely can't see two distinc signals, lets see what we can do with ICA! In general for performing Source Separation we need at least as many mixed signals as sources we're hoping to separate and in this case we actually have ...
import shogun as sg # Signal Matrix X X = (np.c_[abdominal2, abdominal3, abdominal4, abdominal5, abdominal6, thoracic7,thoracic8,thoracic9]).T # Convert to features for shogun mixed_signals = sg.features((X).astype(np.float64))
doc/ipython-notebooks/ica/ecg_sep.ipynb
lisitsyn/shogun
bsd-3-clause
Next we apply the ICA algorithm to separate the sources:
# Separating with SOBI sep = sg.transformer('SOBI') sep.put('tau', 1.0*np.arange(0,120)) sep.fit(mixed_signals) signals = sep.transform(mixed_signals) S_ = signals.get('feature_matrix')
doc/ipython-notebooks/ica/ecg_sep.ipynb
lisitsyn/shogun
bsd-3-clause
And we plot the separated signals:
# Show separation results # Separated Signal i for i in range(S_.shape[0]): pl.figure(figsize=(14,3)) pl.plot(time_steps, S_[i], 'r') pl.title('Separated Signal %d' % (i+1)) pl.grid() pl.show()
doc/ipython-notebooks/ica/ecg_sep.ipynb
lisitsyn/shogun
bsd-3-clause
Before we do training, one thing that is often beneficial is to separate the dataset into training and testing. In this case, let's randomly shuffle the data, use the first 100 data points to do training, and the remaining 50 to do testing. For more sophisticated approaches, you can use e.g. cross validation to separat...
random_index = np.random.permutation(150) features = features[random_index] labels = labels[random_index] train_features = features[:100] train_labels = labels[:100] test_features = features[100:] test_labels = labels[100:] # Let's plot the first two features together with the label. # Remember, while we are plotting...
caffe2/python/tutorials/create_your_own_dataset.ipynb
Yangqing/caffe2
apache-2.0
Now, as promised, let's put things into a Caffe2 DB. In this DB, what would happen is that we will use "train_xxx" as the key, and use a TensorProtos object to store two tensors for each data point: one as the feature and one as the label. We will use Caffe2's Python DB interface to do so.
# First, let's see how one can construct a TensorProtos protocol buffer from numpy arrays. feature_and_label = caffe2_pb2.TensorProtos() feature_and_label.protos.extend([ utils.NumpyArrayToCaffe2Tensor(features[0]), utils.NumpyArrayToCaffe2Tensor(labels[0])]) print('This is what the tensor proto looks like for ...
caffe2/python/tutorials/create_your_own_dataset.ipynb
Yangqing/caffe2
apache-2.0
Now, let's create a very simple network that only consists of one single TensorProtosDBInput operator, to showcase how we load data from the DB that we created. For training, you might want to do something more complex: creating a network, train it, get the model, and run the prediction service. To this end you can loo...
net_proto = core.Net("example_reader") dbreader = net_proto.CreateDB([], "dbreader", db="iris_train.minidb", db_type="minidb") net_proto.TensorProtosDBInput([dbreader], ["X", "Y"], batch_size=16) print("The net looks like this:") print(str(net_proto.Proto())) workspace.CreateNet(net_proto) # Let's run it to get batc...
caffe2/python/tutorials/create_your_own_dataset.ipynb
Yangqing/caffe2
apache-2.0
2. Preparting the Inputs The structure as specified is 64-atom diamond silicon at zero temperature and zero pressure. Weuse the minimal Tersoff potential [Fan 2020]. Generate the xyz.in file: Create Si Unit Cell & Add Basis
a=5.434 Si_UC = bulk('Si', 'diamond', a=a) add_basis(Si_UC) Si_UC
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
Transform Si to Cubic Supercell
# Create 8 atom diamond structure Si = repeat(Si_UC, [2,2,1]) Si.set_cell([a, a, a]) Si.wrap() # Complete full supercell Si = repeat(Si, [2,2,2]) Si
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
Write xyz.in File
ase_atoms_to_gpumd(Si, M=4, cutoff=3)
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
Write basis.in File The basis.in file reads: 2 0 28 4 28 0 0 0 0 1 1 1 1 ... Here the primitive cell is chosen as the unit cell. There are only two basis atoms in the unit cell, as indicated by the number 2 in the first line. The next two lines list the indices (0 and 4) and masses (both are 28 amu) for the two bas...
create_basis(Si)
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
Write kpoints.in File The $k$ vectors are defined in the reciprocal space with respect to the unit cell chosen in the basis.in file. We use the $\Gamma-X-K-\Gamma-L$ path, with 400 $k$ points in total.
linear_path, sym_points, labels = create_kpoints(Si_UC, path='GXKGL',npoints=400)
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
The <code>run.in</code> file: The <code>run.in</code> input file is given below:<br> potential potentials/tersoff/Si_Fan_2019.txt 0 compute_phonon 5.0 0.005 # in units of A The first line with the potential keyword states that the potential to be used is specified in the file Si_Fan_2019.txt. The second line...
aw = 2 fs = 24 font = {'size' : fs} matplotlib.rc('font', **font) matplotlib.rc('axes' , linewidth=aw) def set_fig_properties(ax_list): tl = 8 tw = 2 tlm = 4 for ax in ax_list: ax.tick_params(which='major', length=tl, width=tw) ax.tick_params(which='minor', length=tlm, width=tw) ...
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
Plot Phonon Dispersion The omega2.out output file is loaded and processed to create the following figure. The previously defined kpoints are used for the $x$-axis.
nu = load_omega2() figure(figsize=(10,10)) set_fig_properties([gca()]) vlines(sym_points, ymin=0, ymax=17) plot(linear_path, nu, color='C0',lw=3) xlim([0, max(linear_path)]) gca().set_xticks(sym_points) gca().set_xticklabels([r'$\Gamma$','X', 'K', r'$\Gamma$', 'L']) ylim([0, 17]) ylabel(r'$\nu$ (THz)') show()
examples/empirical_potentials/phonon_dispersion/Phonon Dispersion.ipynb
brucefan1983/GPUMD
gpl-3.0
List of data files:
from glob import glob file_list = sorted(f for f in glob(data_dir + '*.hdf5') if '_BKG' not in f) ## Selection for POLIMI 2012-11-26 datatset labels = ['17d', '27d', '7d', '12d', '22d'] files_dict = {lab: fname for lab, fname in zip(labels, file_list)} files_dict ph_sel_map = {'all-ph': Ph_sel('all'), 'Dex': Ph_sel(De...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Burst search and selection
bs_kws = dict(L=10, m=10, F=7, ph_sel=ph_sel) d.burst_search(**bs_kws) th1 = 30 ds = d.select_bursts(select_bursts.size, th1=30) bursts = (bext.burst_data(ds, include_bg=True, include_ph_index=True) .round({'E': 6, 'S': 6, 'bg_d': 3, 'bg_a': 3, 'bg_aa': 3, 'nd': 3, 'na': 3, 'naa': 3, 'nda': 3, 'nt': 3, 'wid...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Donor Leakage fit Half-Sample Mode Fit peak usng the mode computed with the half-sample algorithm (Bickel 2005).
def hsm_mode(s): """ Half-sample mode (HSM) estimator of `s`. `s` is a sample from a continuous distribution with a single peak. Reference: Bickel, Fruehwirth (2005). arXiv:math/0505419 """ s = memoryview(np.sort(s)) i1 = 0 i2 = len(s) while i2 - i1 > 3: n = (i...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Gaussian Fit Fit the histogram with a gaussian:
E_fitter = bext.bursts_fitter(ds_do, weights=None) E_fitter.histogram(bins=np.arange(-0.2, 1, 0.03)) E_fitter.fit_histogram(model=mfit.factory_gaussian()) E_fitter.params res = E_fitter.fit_res[0] res.params.pretty_print() E_pr_do_gauss = res.best_values['center'] E_pr_do_gauss
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
KDE maximum
bandwidth = 0.03 E_range_do = (-0.1, 0.15) E_ax = np.r_[-0.2:0.401:0.0002] E_fitter.calc_kde(bandwidth=bandwidth) E_fitter.find_kde_max(E_ax, xmin=E_range_do[0], xmax=E_range_do[1]) E_pr_do_kde = E_fitter.kde_max_pos[0] E_pr_do_kde
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Leakage summary
mfit.plot_mfit(ds_do.E_fitter, plot_kde=True, plot_model=False) plt.axvline(E_pr_do_hsm, color='m', label='HSM') plt.axvline(E_pr_do_gauss, color='k', label='Gauss') plt.axvline(E_pr_do_kde, color='r', label='KDE') plt.xlim(0, 0.3) plt.legend() print('Gauss: %.2f%%\n KDE: %.2f%%\n HSM: %.2f%%' % (E_pr_do_gauss...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Burst size distribution
nt_th1 = 50 dplot(ds_fret, hist_size, which='all', add_naa=False) xlim(-0, 250) plt.axvline(nt_th1) Th_nt = np.arange(35, 120) nt_th = np.zeros(Th_nt.size) for i, th in enumerate(Th_nt): ds_nt = ds_fret.select_bursts(select_bursts.size, th1=th) nt_th[i] = (ds_nt.nd[0] + ds_nt.na[0]).mean() - th plt.figure()...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
The following string contains the list of variables to be saved. When saving, the order of the variables is preserved.
variables = ('sample n_bursts_all n_bursts_do n_bursts_fret ' 'E_kde_w E_gauss_w E_gauss_w_sig E_gauss_w_err E_gauss_w_fiterr ' 'S_kde S_gauss S_gauss_sig S_gauss_err S_gauss_fiterr ' 'E_pr_do_kde E_pr_do_hsm E_pr_do_gauss nt_mean\n')
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
This is just a trick to format the different variables:
variables_csv = variables.replace(' ', ',') fmt_float = '{%s:.6f}' fmt_int = '{%s:d}' fmt_str = '{%s}' fmt_dict = {**{'sample': fmt_str}, **{k: fmt_int for k in variables.split() if k.startswith('n_bursts')}} var_dict = {name: eval(name) for name in variables.split()} var_fmt = ', '.join([fmt_dict.get(name...
out_notebooks/usALEX-5samples-PR-raw-out-all-ph-22d.ipynb
tritemio/multispot_paper
mit
Numpy and Scipy
import numpy as np from numpy import array, cos, diag, eye, linspace, pi from numpy import poly1d, sign, sin, sqrt, where, zeros from scipy.linalg import eigh, inv, det
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Matplotlib
%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-paper') plt.rcParams['figure.dpi'] = 115 plt.rcParams['figure.figsize'] = (7.5, 2.5) plt.rcParams['axes.grid'] = True
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Miscellaneous definitions In the following ld and pmat are used to display mathematical formulas generated by the program, rounder ensures that a floating point number close to an integer will be rounded correctly when formatted as an integer, p is a shorthand to calling poly1d that is long and requires a single argume...
def ld(*items): display(Latex('$$' + ' '.join(items) + '$$')) def pmat(mat, env='bmatrix', fmt='%+f'): opener = '\\begin{'+env+'}\n ' closer = '\n\\end{'+env+'}' formatted = '\\\\\n '.join('&'.join(fmt%elt for elt in row) for row in mat) return opener+formatted+closer def rounder(mat): return mat...
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
3 DOF System Input motion We need the imposed displacement, the imposed velocity (an intermediate result) and the imposed acceleration. It is convenient to express these quantities in terms of an adimensional time coordinate $a = \omega_0 t$, \begin{align} u &= \frac{4/3\omega_0 t - \sin(4/3\omega_0 t)}{2\pi...
l0 = 4/3 # define a function to get back the time array and the 3 dependent vars def a_uA_vA_aA(t0, t1, npoints): a = linspace(t0, t1, npoints) uA = where(a<3*pi/2, (l0*a-sin(l0*a))/2/pi, 1) vA = where(a<3*pi/2, (1-cos(l0*a))/2/pi, 0) aA = where(a<3*pi/2, 16*sin(l0*a)/18/pi, 0) return a, uA, vA, aA...
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The plots
plt.plot(a/pi, uA) plt.xlabel(r'$\omega_0 t/\pi$') plt.ylabel(r'$u_A/\delta$') plt.title('Imposed support motion'); plt.plot(a/pi, vA) plt.xlabel(r'$\omega_0 t/\pi$') plt.ylabel(r'$\dot u_A/\delta\omega_0$') plt.title('Imposed support velocity'); plt.plot(a/pi, aA) plt.xlabel(r'$\omega_0 t/\pi$') plt.ylabel(r'$\ddot...
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Equation of Motion The EoM expressed in adimensional coordinates and using adimensional structural matrices is $$ m\omega_0^2\hat{\boldsymbol M} \frac{\partial^2\boldsymbol x}{\partial a^2} + \frac{EJ}{L^3}\hat{\boldsymbol K}\boldsymbol x = m \hat{\boldsymbol M} \boldsymbol e \omega_0^2 \frac{\partial^2 u_A}{\partial...
display(HTML(open('figures/trab1kin_conv.svg').read()))
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The left beam is constrained by a roller and by the right beam, the first requires that the Centre of Instantaneous Rotation (CIR) belongs to the vertical line in $A$, while the second requires that the CIR belongs to the line that connects the hinges of the right beam. The angles of rotation are $\theta_\text{left} = ...
e = array((2.0, 2.0, 2.0))
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Structural Matrices
display(HTML(open('figures/trab1_conv.svg').read()))
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Compute the 3x3 flexibility using the Principle of Virtual Displacements and the 3x3 stiffness using inversion, while the mass matrix is directly assembled with the understanding that the lumped mass on $x_1$ is $2m$. The code uses a structure m where each of the three rows contains the computational represention (as ...
l = [1, 2, 2, 1, 1, 1] h = 0.5 ; t = 3*h m = [[p(2,0),p(h,0),p(h,1),p(h,0),p(h,h),p(1,0)], [p(2,0),p(1,0),p(0,2),p(1,0),p(1,1),p(2,0)], [p(2,0),p(h,0),p(h,1),p(h,0),p(t,h),p(2,0)]] F = array([[vw(emme, chi, l) for emme in m] for chi in m]) K = inv(F) M = array(((2.0, 0.0, 0.0), (0.0, 1.0, 0.0), ...
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The eigenvalues problem We solve immediately the eigenvalue problem because when we know the shortest modal period of vibration it is possible to choose the integration time step $h$ to avoid numerical unstability issues with the linear acceleration algorithm.
wn2, Psi = eigh(K, M) wn = sqrt(wn2) li = wn Lambda2 = diag(wn2) Lambda = diag(wn) # eigenvectors are normalized β†’ M* is a unit matrix, as well as its inverse Mstar, iMstar = eye(3), eye(3) ld(r'\boldsymbol\Omega^2 = \omega_0^2\,', pmat(Lambda2), r'=\omega_0^2\,\boldsymbol\Lambda^2.') ld(r'\boldsymbol\Omega=\omega_...
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Numerical Integration The shortest period is $T_3 = 2\pi\,0.562/\omega_0 \rightarrow A_3 = 1.124 \pi$ hence to avoid unstability of the linear acceleration algorithm we shall use a non dimensional time step $h<0.55A_3\approx0.6\pi$. We can anticipate that the modal response associated with mode 2 is important ($\lambda...
nsppi = 200 a, _, _, aA = a_uA_vA_aA(0, 16*pi, nsppi*16+1) peff = (- M @ e) * aA[:,None]
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The constants that we need in the linear acceleration algorithm β€” note that we have an undamped system or, in other words, $\boldsymbol C = \boldsymbol 0$
h = pi/nsppi K_ = K + 6*M/h**2 F_ = inv(K_) dp_v = 6*M/h dp_a = 3*M
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The integration loop First we initialize the containers where to save the new results with the initial values at $a=0$, next the loop on the values of the load at times $t_i$ and $t_{i+1}$ with $i=0,\ldots,1999$.
Xl, Vl = [zeros(3)], [zeros(3)] for p0, p1 in p0_p1(peff): x0, v0 = Xl[-1], Vl[-1] a0 = iM @ (p0 -K@x0) dp = (p1-p0) + dp_a@a0 + dp_v@v0 dx = F_@dp dv = 3*dx/h - 3*v0 - a0*h/2 Xl.append(x0+dx), Vl.append(v0+dv) Xl = array(Xl) ; Vl = array(Vl)
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Plotting
for i, line in enumerate(plt.plot(a/pi, Xl), 1): line.set_label(r'$x_{%d}$'%i) plt.xlabel(r'$\omega_0 t/\pi$') plt.ylabel(r'$x_i/\delta$') plt.title('Response β€” numerical integration β€” lin.acc.') plt.legend();
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Equation of Motion Denoting with $\boldsymbol x$ the dynamic component of the displacements, with $\boldsymbol x_\text{tot} = \boldsymbol x + \boldsymbol x_\text{stat} = \boldsymbol x + \boldsymbol e \;u_\mathcal{A}$ the equation of motion is (the independent variable being $a=\omega_0t$) $$ \hat{\boldsymbol M} \ddot{\...
G = - Psi.T @ M @ e
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Substituting a particular integral $\xi_i=C_i\sin(\lambda_0 a)$ in the modal equation of motion we have $$(\lambda^2_i-\lambda^2_0)\,C_i\sin(\lambda_0 a) = \frac{\Gamma_i}{2\pi}\,\lambda_0^2\,\sin(\lambda_0 a)$$ and solving w/r to $C_i$ we have $$ C_i = \frac{\Gamma_i}{2\pi}\,\frac{\lambda_0^2}{\lambda_i^2-\lambda_0^...
C = G*l0**2/(li**2-l0**2)/2/pi
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The modal response, taking into account that we start from rest conditions, is $$ q_i = C_i\left(\sin(\lambda_0 a) - \frac{\lambda_0}{\lambda_i}\,\sin(\lambda_i a)\right)$$ $$ \dot q_i = \lambda_0 C_i \left( \cos(\lambda_0 a) - \cos(\lambda_i a) \right).$$
for n in range(3): i = n+1 ld(r'q_%d=%+10f\left(\sin\frac43a-%10f\sin%1fa\right)' % (i,C[n],l0/li[n],li[n]), r'\qquad\text{for }0 \le a \le \frac32\pi')
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Free vibration phase, $a\ge 3\pi/2 = a_1$ When the forced phase end, the system is in free vibrations and we can determine the constants of integration requiring that the displacements and velocities of the free vibration equal the displacements and velocities of the forced response at $t=t_0$. \begin{align} + (\cos\...
a1 = 3*pi/2 q_a1 = C*(sin(l0*a1)-l0*sin(li*a1)/li) v_a1 = C*l0*(cos(l0*a1)-cos(li*a1)) ABs = [] for i in range(3): b = array((q_a1[i], v_a1[i]/li[i])) A = array(((+cos(li[i]*a1), -sin(li[i]*a1)), (+sin(li[i]*a1), +cos(li[i]*a1)))) ABs.append(A@b) ABs = array(ABs)
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Analytical expressions
display(Latex(r'Modal responses for $a_1 \le a$.')) for n in range(3): i, l, A_, B_ = n+1, li[n], *ABs[n] display(Latex((r'$$q_{%d} = '+ r'%+6.3f\cos%6.3fa '+ r'%+6.3f\sin%6.3fa$$')%(i, A_, l, B_, l)))
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Stitching the two responses We must evaluate numerically the analytical responses
ac = a[:,None] q = where(ac<=a1, C*(sin(l0*ac)-l0*sin(li*ac)/li), ABs[:,0]*cos(li*ac) + ABs[:,1]*sin(li*ac))
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Plotting the Analytical Response First, we zoom around $a_1$ to verify the continuity of displacements and velocities
# #### Plot zooming around a1 low, hi = int(0.8*a1*nsppi/pi), int(1.2*a1*nsppi/pi) for i, line in enumerate(plt.plot(a[low:hi]/pi, q[low:hi]), 1): line.set_label('$q_{%d}$'%i) plt.title('Modal Responses, zoom on transition zone') plt.xlabel(r'$\omega_0 t/\pi$') plt.legend(loc='best') plt.show()
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
next, the modal responses over the interval $0 \le a \le 16\pi$
# #### Plot in 0 ≀ a ≀ 16 pi for i, line in enumerate(plt.plot(a/pi, q), 1): line.set_label('$q_{%d}$'%i) plt.title('Modal Responses') plt.xlabel(r'$\omega_0 t/\pi$') plt.legend(loc='best'); plt.xticks() plt.show();
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Nodal responses
x = q@Psi.T
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
Why x = q@Psi.T rather than x = Psi@q? Because for different reasons (mostly, ease of use with the plotting libraries) we have all the response arrays organized in the shape of (Nsteps Γ— 3). That's equivalent to say that q and x, the Pyton objects, are isomorph to $\boldsymbol q^T$ and $\boldsymbol x^T$ and because i...
for i, line in enumerate(plt.plot(a/pi, x), 1): line.set_label('$x_{%d}/\delta$'%i) plt.title('Normalized Nodal Displacements β€” analytical solution') plt.xlabel(r'$\omega_0 t / \pi$') plt.legend(loc='best') plt.show();
dati_2017/hw03/01.ipynb
boffi/boffi.github.io
mit
The mt_obj contains all the data from the edi file, e.g. impedance, tipper, frequency as well as station information (lat/long). To look at any of these parameters you can type, for example:
# To see the latitude and longitude print(mt_obj.lat, mt_obj.lon) # To see the easting, northing, and elevation print(mt_obj.east, mt_obj.north, mt_obj.elev)
examples/workshop/Workshop Exercises Core.ipynb
MTgeophysics/mtpy
gpl-3.0
There are many other parameters you can look at in the mt_obj. Just type mt_obj.[TAB] to see what is available. In the MT object are the Z and Tipper objects (mt_obj.Z; mt_obj.Tipper). These contain all information related to, respectively, the impedance tensor and the tipper.
# for example, to see the frequency values represented in the impedance tensor: print(mt_obj.Z.freq) # or to see the impedance tensor (first 4 elements) print(mt_obj.Z.z[:4]) # or the resistivity or phase (first 4 values) print(mt_obj.Z.resistivity[:4]) print(mt_obj.Z.phase[:4])
examples/workshop/Workshop Exercises Core.ipynb
MTgeophysics/mtpy
gpl-3.0
As with the MT object, you can explore the object by typing mt_obj.Z.[TAB] to see the available attributes. Plot an edi file In this example we plot MT data from an edi file.
# import required modules from mtpy.core.mt import MT import os # Define the path to your edi file and save path edi_file = "C:/mtpywin/mtpy/examples/data/edi_files_2/Synth00.edi" savepath = r"C:/tmp" # Create an MT object mt_obj = MT(edi_file) # To plot the edi file we read in in Part 1 & save to file: pt_obj = mt_...
examples/workshop/Workshop Exercises Core.ipynb
MTgeophysics/mtpy
gpl-3.0
Make some change to the data and save to a new file This example demonstrates how to resample the data onto new frequency values and write to a new edi file. In the example below, you can either choose every second frequency or resample onto five periods per decade. To do this we need to make a new Z object, and save ...
# import required modules from mtpy.core.mt import MT import os # Define the path to your edi file and save path edi_file = r"C:/mtpywin/mtpy/examples/data/edi_files_2/Synth00.edi" savepath = r"C:/tmp" # Create an MT object mt_obj = MT(edi_file) # First, define a frequency array: # Every second frequency: new_freq_l...
examples/workshop/Workshop Exercises Core.ipynb
MTgeophysics/mtpy
gpl-3.0
We will now create the multi-group library using data directly from Appendix A of the C5G7 benchmark documentation. All of the data below will be created at 294K, consistent with the benchmark. This notebook will first begin by setting the group structure and building the groupwise data for UO2. As you can see, the cr...
# Create a 7-group structure with arbitrary boundaries (the specific boundaries are unimportant) groups = openmc.mgxs.EnergyGroups(np.logspace(-5, 7, 8)) uo2_xsdata = openmc.XSdata('uo2', groups) uo2_xsdata.order = 0 # When setting the data let the object know you are setting the data for a temperature of 294K. uo2_x...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
We will now add the scattering matrix data. Note: Most users familiar with deterministic transport libraries are already familiar with the idea of entering one scattering matrix for every order (i.e. scattering order as the outer dimension). However, the shape of OpenMC's scattering matrix entry is instead [Incoming g...
# The scattering matrix is ordered with incoming groups as rows and outgoing groups as columns # (i.e., below the diagonal is up-scattering). scatter_matrix = \ [[[1.27537E-1, 4.23780E-2, 9.43740E-6, 5.51630E-9, 0.00000E-0, 0.00000E-0, 0.00000E-0], [0.00000E-0, 3.24456E-1, 1.63140E-3, 3.14270E-9, 0.00000E-0, ...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Now that the UO2 data has been created, we can move on to the remaining materials using the same process. However, we will actually skip repeating the above for now. Our simulation will instead use the c5g7.h5 file that has already been created using exactly the same logic as above, but for the remaining materials in ...
# Initialize the library mg_cross_sections_file = openmc.MGXSLibrary(groups) # Add the UO2 data to it mg_cross_sections_file.add_xsdata(uo2_xsdata) # And write to disk mg_cross_sections_file.export_to_hdf5('mgxs.h5')
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Generate 2-D C5G7 Problem Input Files To build the actual 2-D model, we will first begin by creating the materials.xml file. First we need to define materials that will be used in the problem. In other notebooks, either openmc.Nuclides or openmc.Elements were created at the equivalent stage. We can do that in multi-gro...
# For every cross section data set in the library, assign an openmc.Macroscopic object to a material materials = {} for xs in ['uo2', 'mox43', 'mox7', 'mox87', 'fiss_chamber', 'guide_tube', 'water']: materials[xs] = openmc.Material(name=xs) materials[xs].set_density('macro', 1.) materials[xs].add_macroscopi...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Now we can go ahead and produce a materials.xml file for use by OpenMC
# Instantiate a Materials collection, register all Materials, and export to XML materials_file = openmc.Materials(materials.values()) # Set the location of the cross sections file to our pre-written set materials_file.cross_sections = 'c5g7.h5' materials_file.export_to_xml()
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Our next step will be to create the geometry information needed for our assembly and to write that to the geometry.xml file. We will begin by defining the surfaces, cells, and universes needed for each of the individual fuel pins, guide tubes, and fission chambers.
# Create the surface used for each pin pin_surf = openmc.ZCylinder(x0=0, y0=0, R=0.54, name='pin_surf') # Create the cells which will be used to represent each pin type. cells = {} universes = {} for material in materials.values(): # Create the cell for the material inside the cladding cells[material.name] = o...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
The next step is to take our universes (representing the different pin types) and lay them out in a lattice to represent the assembly types
lattices = {} # Instantiate the UO2 Lattice lattices['UO2 Assembly'] = openmc.RectLattice(name='UO2 Assembly') lattices['UO2 Assembly'].dimension = [17, 17] lattices['UO2 Assembly'].lower_left = [-10.71, -10.71] lattices['UO2 Assembly'].pitch = [1.26, 1.26] u = universes['uo2'] g = universes['guide_tube'] f = universe...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Let's now create the core layout in a 3x3 lattice where each lattice position is one of the assemblies we just defined. After that we can create the final cell to contain the entire core.
lattices['Core'] = openmc.RectLattice(name='3x3 core lattice') lattices['Core'].dimension= [3, 3] lattices['Core'].lower_left = [-32.13, -32.13] lattices['Core'].pitch = [21.42, 21.42] r = universes['Reflector Assembly'] u = universes['UO2 Assembly'] m = universes['MOX Assembly'] lattices['Core'].universes = [[u, m, r]...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
Before we commit to the geometry, we should view it using the Python API's plotting capability
root_universe.plot(center=(0., 0., 0.), width=(3 * 21.42, 3 * 21.42), pixels=(500, 500), color_by='material')
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
OK, it looks pretty good, let's go ahead and write the file
# Create Geometry and set root Universe geometry = openmc.Geometry(root_universe) # Export to "geometry.xml" geometry.export_to_xml()
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
We can now create the tally file information. The tallies will be set up to give us the pin powers in this notebook. We will do this with a mesh filter, with one mesh cell per pin.
tallies_file = openmc.Tallies() # Instantiate a tally Mesh mesh = openmc.Mesh() mesh.type = 'regular' mesh.dimension = [17 * 2, 17 * 2] mesh.lower_left = [-32.13, -10.71] mesh.upper_right = [+10.71, +32.13] # Instantiate tally Filter mesh_filter = openmc.MeshFilter(mesh) # Instantiate the Tally tally = openmc.Tally(...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit
With the geometry and materials finished, we now just need to define simulation parameters for the settings.xml file. Note the use of the energy_mode attribute of our settings_file object. This is used to tell OpenMC that we intend to run in multi-group mode instead of the default continuous-energy mode. If we didn't s...
# OpenMC simulation parameters batches = 150 inactive = 50 particles = 5000 # Instantiate a Settings object settings_file = openmc.Settings() settings_file.batches = batches settings_file.inactive = inactive settings_file.particles = particles # Tell OpenMC this is a multi-group problem settings_file.energy_mode = 'm...
docs/source/examples/mg-mode-part-i.ipynb
bhermanmit/openmc
mit