markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
4. Create Pilot and Unit Managers | print "Initializing Pilot Manager ..."
pmgr = rp.PilotManager(session=session)
print "Initializing Unit Manager ..."
umgr = rp.UnitManager (session=session,
scheduler=rp.SCHED_DIRECT_SUBMISSION) | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
5. Submit the pilot to the Pilot and Unit Managers | pdesc = rp.ComputePilotDescription ()
pdesc.resource = "yarn.stampede" # NOTE: This is a "label", not a hostname
pdesc.runtime = 60 # minutes
pdesc.cores = 16
pdesc.cleanup = False
pdesc.project = '' #Include the Allocation here
pdesc.queue = 'development' #You can select a different queue if you want.
# subm... | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
6. Submit Compute Units
First create the description of the compute units which define the task to be executed | NUMBER_JOBS = 16
cudesc_list = []
for i in range(NUMBER_JOBS):
cudesc = rp.ComputeUnitDescription()
cudesc.environment = {'CU_NO': i}
cudesc.executable = "/bin/echo"
cudesc.arguments = ['I am CU number $CU_NO']
cudesc.cores = 1
cudesc_list.append(cudesc) | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
Submit the created Compute Units to the Unit Manager. |
print "Submit Compute Units to Unit Manager ..."
cu_set = umgr.submit_units (cudesc_list)
print "Waiting for CUs to complete ..."
umgr.wait_units()
print "All CUs completed successfully!" | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
Printing the output of a Compute Unit | for unit in cu_set:
print "* CU %s, state %s, exit code: %s, stdout: %s" \
% (unit.uid, unit.state, unit.exit_code, unit.stdout) | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
7. Always clean up the session | session.close ()
del session | 02_pilot/Radical_Pilot_YARN_Stampede.ipynb | radical-cybertools/supercomputing2015-tutorial | apache-2.0 |
Configure Solow Model
In this notebook, you can set the parameters of the Solow model.
This notebook is part of three notebooks which can be used to work with the Black Rhino Solow model. These notebooks are:
1. Configure_Solow notebook
2. Run_Solow notebook,
3. Analyse_Solow notebook.
The current notebook is highligh... | parameter_values = (('num_sweeps', '30'),
('num_simulations', '1'),
('num_banks', '1'),
('num_firms', '1'),
('num_households', '1'),
('bank_directory', 'agents/banks/'),
('firm_directory', 'agents/fir... | examples/solow/Configure_Solow.ipynb | cogeorg/black_rhino | gpl-3.0 |
Next, parameter attributes for type, name and value are added to the XML elements. | for idx, p in enumerate(parameters):
p.set('type', 'static')
p.set('name', parameter_values[idx][0])
p.set('value', parameter_values[idx][1])
xml_params = ET.tostring(environment, encoding="unicode")
myfile = open("environments/solow_parameters.xml", "w")
myfile.write(xml_params)
myfile.close() | examples/solow/Configure_Solow.ipynb | cogeorg/black_rhino | gpl-3.0 |
Our feed forward neural network will look very similar to our softmax classifier. However, now we have multiple layers and non-linear activations over logits!
For this network, we will have 3 layers. 2 hidden layers and 1 output layer. The output layer is a softmax classifier that we implemented in the previous example... | # Hyperparameters (these are similar to the ones used in the previous example)
learning_rate = 0.5
training_epochs = 5
batch_size = 100
# Additional hyperparameters for our Neural Nets - Layer sizes
layer_1_size = 256
layer_2_size = 128 | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Step 1: Create placeholders to hold the images. | # Create placeholders
x = tf.placeholder(tf.float32, shape=(None, 784))
y = tf.placeholder(tf.float32, shape=(None, 10)) | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Step 2: Create variables to hold the weight matrices and the bias vectors for all the layers
Note that the weights are now initialized with small random numbers. From Karpathy:
"A reasonable-sounding idea then might be to set all the initial weights to zero, which we expect to be the “best guess” in expectation. This... | # Model parameters that have to be learned
# Note that the weights & biases are now initialized to small random numbers
# Also note that the number of columns for should be the size of the first layer!
W_h1 = tf.Variable(0.01 * tf.random_normal([784, layer_1_size]))
b_h1 = tf.Variable(tf.random_normal([layer_1_size]))... | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Step 3: Lets build the flow of data. Each unit in each layer computes the logits (Linear function = W * X + b). Next, it applies an activation function over each of the weighted sum and passes them on as inputs to the next layer.
Step 4: Compute the loss function as the cross entropy between the predicted distributio... | # Get the weighted sum for the first layer
preact_h1 = tf.matmul(x, W_h1) + b_h1
# Compute the activations which forms the output of this layer
out_h1 = tf.sigmoid(preact_h1)
# out_h1 = tf.nn.relu(preact_h1)
# Get the weighted sum for the second layer
# Note that the input is now the output from the previous layer
pre... | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Step 5: Lets create an optimizer to minimize the cross entropy loss | # Create an optimizer with the learning rate
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
# optimizer = tf.train.AdamOptimizer(learning_rate)
# Use the optimizer to minimize the loss
train_step = optimizer.minimize(cross_entropy_loss) | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Step 6: Lets compute the accuracy | # First create the correct prediction by taking the maximum value from the prediction class
# and checking it with the actual class. The result is a boolean column vector
correct_predictions = tf.equal(tf.argmax(logits_o, 1), tf.argmax(y, 1))
# Calculate the accuracy over all the images
# Cast the boolean vector into f... | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
Now lets run our graph as usual | # Initializing global variables
init = tf.global_variables_initializer()
# Create a saver to save our model
saver = tf.train.Saver()
# Create a session to run the graph
with tf.Session() as sess:
# Run initialization
sess.run(init)
# For the set number of epochs
for epoch in range(training_epochs):
... | notebooks/Feed Forward Neural Network.ipynb | abhay1/tf_rundown | mit |
2 - Zero initialization
There are two types of parameters to initialize in a neural network:
- the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$
- the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$
Exercise: Implement the following function to initialize all parameters to z... | # GRADED FUNCTION: initialize_parameters_zeros
def initialize_parameters_zeros(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | deeplearning.ai/coursera-improving-neural-networks/week1/assignment1/Initialization.ipynb | ud3sh/coursework | unlicense |
The model is predicting 0 for every example.
In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is n... | # GRADED FUNCTION: initialize_parameters_random
def initialize_parameters_random(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | deeplearning.ai/coursera-improving-neural-networks/week1/assignment1/Initialization.ipynb | ud3sh/coursework | unlicense |
Observations:
- The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\log(a^{[3]}) = \log(0)$, the loss go... | # GRADED FUNCTION: initialize_parameters_he
def initialize_parameters_he(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- ... | deeplearning.ai/coursera-improving-neural-networks/week1/assignment1/Initialization.ipynb | ud3sh/coursework | unlicense |
You have now built a function to describe your model. To train and test this model, there are four steps in Keras:
1. Create the model by calling the function above
2. Compile the model by calling model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])
3. Train the model on train data by calling model.fi... | ### START CODE HERE ### (1 line)
happyModel = HappyModel(X_train[0,:,:,:].shape)
### END CODE HERE ### | deeplearning.ai/C4.CNN/week2_DeepModelCaseStudy/hw/KerasTutorial/Keras+-+Tutorial+-+Happy+House+v1.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
Exercise: Implement step 3, i.e. train the model. Choose the number of epochs and the batch size. | ### START CODE HERE ### (1 line)
happyModel.fit(x = X_train, y = Y_train, epochs = 10, batch_size = 20)
### END CODE HERE ### | deeplearning.ai/C4.CNN/week2_DeepModelCaseStudy/hw/KerasTutorial/Keras+-+Tutorial+-+Happy+House+v1.ipynb | jinzishuai/learn2deeplearn | gpl-3.0 |
We need about 16.4 seconds of data, after we scale the system to (36+29=) $65\, M_{\odot}$. In terms of $M$ as we know it, that's about... | 16.4 / ((36.+29.) * m_sun) | GW150914/HybridizeNR.ipynb | moble/MatchedFiltering | mit |
Now read the NR waveform and offset so that the "relaxed" measurement time is $0$. | nr = GWFrames.ReadFromNRAR(data_dir + 'rhOverM_Asymptotic_GeometricUnits_CoM.h5/Extrapolated_N4.dir')
nr.SetT(nr.T()-metadata.relaxed_measurement_time);
approximant = 'TaylorT4' # 'TaylorT1'|'TaylorT4'|'TaylorT5'
delta = (m1 - m2) / (m1 + m2) # Normalized BH mass difference (M1-M2)/(M1+M2)
chi1_i = chi1 # Initial d... | GW150914/HybridizeNR.ipynb | moble/MatchedFiltering | mit |
NOTE: You must have python-twitter installed on the machine to run this script. You can install it by running the below cell (change the cell type in the toolbar above to Code instead of Raw NBConvert). You may need to use "! sudo pip install tweepy". | ! sudo pip install tweepy | .ipynb_checkpoints/getTweetsByID-checkpoint.ipynb | renecnielsen/twitter-diy | mit |
Setup Twitter Access | # Twitter OAuth Credentials
consumer_key = ""
consumer_secret = ""
access_token = ""
access_secret = "" | .ipynb_checkpoints/getTweetsByID-checkpoint.ipynb | renecnielsen/twitter-diy | mit |
Analysis of the fanfiction readers and writers
To begin, we will examine the userbase of fanfiction.net. Who are they? Where are they from? How active are they? To do so, we will take a random sample of ~10,000 users from the site and break down some of their characteristics. | # opens raw data
with open ('../data/clean_data/df_profile', 'rb') as fp:
df = pickle.load(fp)
# creates subset of data of active users
df_active = df.loc[df.status != 'inactive', ].copy()
# sets current year
cyear = datetime.datetime.now().year
# sets stop word list for text parsing
stop_word_list = stopwor... | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
Account status and volume
Let's begin by examining the types of profiles that make up the userbase: readers, authors, or inactive users. Inactive users are accounts that are no longer existing. | # examines status of users
status = df['status'].value_counts()
# plots chart
(status/np.sum(status)).plot.bar()
plt.xticks(rotation=0)
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
About ~20% of users on the site are authors! That's much higher than expected. The number of inactive profiles is also notably negligible, meaning that once a profile has been created, it is very unlikely to be ever deleted or pulled off the site.
What about how fast people are joining the site? | # examines when stories first created
entry = [int(row[2]) for row in df_active['join'] if row != 'NA']
entry = pd.Series(entry).value_counts().sort_index()
# plots chart
(entry/np.sum(entry)).plot()
plt.xlim([np.min(entry.index.values), cyear-1])
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
Fanfiction has been on an upward trend every since its establishment.
Note that sharp increase in 2011! In a later chapter, we will examine what could have caused that surge...
Countries
The site fanfiction.net allows tracking of location for users. Let's examine where these users are from. | # examines distribution of top 10 countries
country = df['country'].value_counts()
# plots chart
(country[1:10]/np.sum(country)).plot.bar()
plt.xticks(rotation=90)
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
We looked at the top 10 countries. Over ~30% are from United States!
Profile descriptions
Users have the option of including a profile description. This is typically to allow users to introduce themselves to the community. Let's see what percentage of the active userbase has written something. | # counts number with written profiles
hasprofile = [row != '' for row in df_active['profile']]
profiletype = pd.Series(hasprofile).value_counts()
# plots chart
profiletype.plot.pie(autopct='%.f', figsize=(5,5))
plt.ylabel('')
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
It would appear about one-fourth of the users have written something in their profile! For those who have, let's see how many words they have written. | # examines word count of profiles
profile_wc = [len(row.split()) for row in df_active['profile']]
# plots chart
pd.Series(profile_wc).plot.hist(normed=True, bins=np.arange(1, 500, 1))
plt.show()
# IMPORTANT NOTE: 'request' package has error in which it cannot find end p tag </p>, thus
# leading to description duplic... | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
The right tail is much longer than depicted, with ~3% of profiles exceeding our 500 word cut off. However, it would appear the majority of profiles fall well under 100-200 words.
What do these users typically say? Let's see what are the top 10 words commonly used. | # extracts mostly used common words
profile_wf = [set(row.lower().translate(str.maketrans('', '', string.punctuation)).split())
for row in df_active.loc[hasprofile, 'profile']]
profile_wf = [item for sublist in profile_wf for item in sublist]
profile_wf = pd.Series(profile_wf).value_counts()
# prints ta... | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
Above are the words most likely to be used at least once in a profile description. And of course, this is excluding stop words, such as "the", "is", or "are".
From here, we can guess that most profiles mention the user's likes (or dislikes) and something related to reading and/or writing. Very standard words you'd expe... | name_count = (profile_wf['name'])/sum(hasprofile)
gender_count = (profile_wf['gender']+profile_wf['sex'])/sum(hasprofile)
age_count = (profile_wf['age']+profile_wf['old'])/sum(hasprofile) | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
The word "name" also made the list. We estimate that ~21% of profiles that have something written will include that word. This prompts the question of what other information we might parse out. We looked into "gender"/"sex" found those words existed in ~6% of profiles. As for "age"/"old", ~20%.
Gender
Now this is where... | # finds gender breakdown
profile_text = [list(set(row.lower().translate(str.maketrans('', '', string.punctuation)).split()))
for row in df_active.loc[hasprofile, 'profile']]
female = ['female' in row and 'male' not in row for row in profile_text]
male = ['male' in row and 'female' not in row for row in p... | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
It should be noted that third-gender and non-binary words were also tested but yielded too little observations for analysis. As such, everything we talk about below is only in reference to the female and male genders.
Assuming a user is either "female" or "male", we estimate a rough 3:1 ratio, favoring female.
This may... | # sets gender words
female = ['female', 'girl', 'woman', 'daughter', 'mother', 'sister']
male = ['male', 'boy', 'man', 'son', 'father', 'brother']
other = ['agender', 'queer', 'nonbinary', 'transgender', 'trans', 'bigender', 'intergender']
# finds gender ratio
gender_index = [n+'-'+m for m,n in zip(female, male)]
gend... | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
Here we have a much more mixed picture.
The problem with the pairs "girl"/"boy" and "woman"/"man" is that they may refer to third parties (eg. "I once met a girl who...). However, when those two columns are added together, there does not seem to be any evidence of any gender disparity. The final three pairs are even mo... | # examines distribution of favorited
df_active[['fa', 'fs']].plot.hist(normed=True, bins=np.arange(1, 50, 1), alpha = 0.65)
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
The right tail is much longer than is depicted above -- in the thousands. However, we cut it off at 50 to better show the distribution.
For the most part, the distributions between the number of favorited authors and the number of favorited stories are similar, with heavy right skew. The number of authors is slightly m... | # examines distribution of stories written
df_active['st'].plot.hist(normed=True, bins=np.arange(1, np.max(df_active['st']), 1))
plt.show() | jupyter_notebooks/profile_analysis.ipynb | lily-tian/fanfictionstatistics | mit |
Introduction: Position switching
Let's start with an illustrative example, that shows how exposure calculation is done for a pointed observation (position switch). Usually, the backend provides the measured (spectral) intensities, $P$, in an uncalibrated fashion, e.g., in units of counts. Therefore one needs to derive ... | dual_pol = True
restfreq = 23.7e9 # Hz
opacity = 0.07 # assume reasonably good weather
Tsys_zenith = 60. | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Atmospheric temperature is approximately given by ambient temperature at ground. | T_amb = 290. # K
T_atm = T_amb - 17. | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Calculate telescope sensitivity (aka Kelvins per Jansky). | Gamma = 1.12 # K/Jy
eta_MB = 0.79 # main beam efficiency
Gamma_MB = Gamma / eta_MB | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
The conversion between antenna temperatures and main-beam brightness temperatures is given by | Ta_to_Tb = 1. / eta_MB | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Define spectrometer properties | nchan = 2 ** 16 # 64 k
bandwidth = 5e8 # 500 MHz
spec_reso = bandwidth / nchan * 1.16 # true spectral resolution 16% worse than channel width
print('spec_reso = {:.1f} kHz'.format(spec_reso * 1.e-3)) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
If a certain velocity resolution is desired, we first have to infer the desired spectral resolution. | desired_vel_resolution = 1. # km/s
desired_freq_resolution = dv_to_df(restfreq, desired_vel_resolution)
print('desired_freq_resolution = {:.1f} kHz'.format(desired_freq_resolution * 1.e-3)) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
This means, we can bin the original spectrum by a factor of | smooth_nbin = int(desired_freq_resolution / spec_reso + 0.5) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
which will further decrease the noise. | print('smooth_nbin', smooth_nbin) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Case 1: Calculate the noise after a certain integration time. The result will depend on the elevation of the source (because different airmasses modify $T_\mathrm{sys}$). | exposure = 60. # seconds
elevations = np.array([10, 20, 30, 40, 50, 60, 90])
AM = 1. / np.sin(np.radians(elevations))
gain_correction = gaincurve(elevations, 0.954, 3.19E-3, -5.42E-5) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Note, Tsys is higher for low elevation (more air mass). | Tsys_corr = Tsys_zenith + T_atm * (np.exp(opacity * AM) - np.exp(opacity * 1))
print('Tsys_corr', Tsys_corr)
# Tsys_corr = Tsys_zenith + opacity * T_atm * (AM - 1) # approximate formula, for small opacity * AM
# print(Tsys_corr) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Calculate raw $T_\mathrm{A}$ noise: | Ta_rms = Tsys_corr / np.sqrt(spec_reso * smooth_nbin * exposure) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
For dual polarization observations, we can divide by $\sqrt{2}$. | if dual_pol:
Ta_rms /= np.sqrt(2.) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
We also have to account for the position switch (division by noisy reference spectrum). | Ta_rms *= np.sqrt(2.) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Finally, we convert to main-beam brightness temperature, $\Delta T_\mathrm{B}$, and flux-density, $\Delta S$, noise: | Tb_rms = Ta_to_Tb * Ta_rms / gain_correction
S_rms = Tb_rms / Gamma_MB | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
The astronomical signal is furthermore attenuated by the atmosphere. There are two ways to handle this. (a) If the signal strength is known (or can be expected to have a certain value), just apply the attenuation factor and compare to the noise levels. (b) calculate an effective noise level, by increasing Tb and flux-d... | atm_atten = np.exp(-opacity * AM)
print('{0:>8s} {1:>8s} {2:>10s} {3:>10s} {4:>10s} {5:>10s} {6:>10s} {7:>10s} {8:>10s}'.format(
'Elev', 'Airmass', 'Tsys', 'Ta RMS', 'Tb RMS', 'S RMS', 'AtmAtten', 'Tb_eff RMS', 'S_eff RMS'
))
print('{0:>8s} {1:>8s} {2:>10s} {3:>10s} {4:>10s} {5:>10s} {6:>10s} {7:>10s} {8:>10s}... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Case 2: Calculate, how long we have to integrate, to reach a certain (effective) noise level.
Start with a given noise level | Tb_eff_rms_desired = 0.01 # 10 mK
Ta_eff_rms_desired = Tb_eff_rms_desired * gain_correction / Ta_to_Tb | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Again, divide by two for dual polarization | exposure = (Tsys_corr / Ta_eff_rms_desired) ** 2 / (spec_reso * smooth_nbin)
if dual_pol:
exposure /= 2. | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
and account for PSW (division by noisy reference spectrum) | exposure *= 2.
print('Exposure time needed to reach an effective MB brightness temperature noise level of {:.1f} mK'.format(
Tb_eff_rms_desired * 1.e3))
print('{0:>8s} {1:>10s}'.format('Elev [d]', 'Time [min]'))
for idx in range(len(elevations)):
print('{0:>8.2f} {1:>10.1f}'.format(
elevations[idx], (e... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
On-the-fly mapping
For OTF mapping, it is not straight-forward to calculate the effective noise in the map after gridding. Therefore, we simulate the process, use cygrid to produce a map, and will measure the noise accordingly.
Map setup
In Effelsberg, we do so-called zig-zag scanning. For position switching, one obser... | map_width, map_height = 100., 100. # arcsec
beamsize_fwhm = 38. # arcsec; at the frequency given in our example | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
The spacing between the scans should not be larger than half the beamwidth, a third is even better. | num_scan_lines = int(3 * map_height / beamsize_fwhm + 0.5)
print('num_scan_lines', num_scan_lines) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Likewise, the scan velocity must not be too high. This is determined by the sampling rate and the beam size (one wants at least three independent samples, per beam, otherwise the resulting map will have some smearing along the scan lines).
Let's calculate the maximal scan speed | sampling_interval = 1. # s (== 4 x 250 ms at Effelsberg)
max_speed = beamsize_fwhm / 3 / sampling_interval
print('max_speed = {:.2f} arcsec per s'.format(max_speed)) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
With this, we can calculate the minimal duration of one scan line | min_duration = map_width / max_speed
print('min_duration = {:.1f} s'.format(min_duration)) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
However, each telescope will have a duty cycle between two scan lines, which is defined by the time the telescope needs for re-positioning. At Effelsberg, this is about 15 s, which means that the duration per scanline should at least be one or two minutes, otherwise the observing efficiency would become really poor.
Ch... | scanline_duration = 90. # seconds
samples_per_scanline = int(scanline_duration / sampling_interval + 0.5)
print('samples_per_scanline', samples_per_scanline) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
We now have to choose the time spent on the reference position. Furthermore, it is possible to do the reference scan only after every $n$ scanlines (to save time).
Let's do a relatively long refpos integration, but only after every 2 scanlines (avoids some duty cycles). | refpos_duration = 90. # seconds
refpos_interval = 2 | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Such a map would need the following total observing time. | duty_cycle = 15. # s
total_on_time = (scanline_duration + duty_cycle) * num_scan_lines
total_ref_time = (refpos_duration + duty_cycle) * (num_scan_lines // refpos_interval)
total_time = total_on_time + total_ref_time
print('Total time necessary for map: {:.1f} min'.format(total_time / 60.))
| notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Now, we create the raw data. Note, the absolute value of the RMS in counts (for the P quantities) is not important, but the RMS ratio between On and Ref spectra is (the absolute number is unimportant, because it gets calibrated away in the (On-Ref/Ref) equation).
Compared to the On scan, a Ref position is integrated ov... | num_maps = 128 | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Here, a dummy $T_\mathrm{sys}$ value is used. Later, the map (and thus the RMS) can simply be scaled to match the true $T_\mathrm{sys}$. | dummy_tsys = 1. | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
We will now create spectral noise (in arbitrary units). This must be much smaller than $T_\mathrm{sys}$ to avoid numerical problems. It is also important, that each of the raw-data spectra has an offset (the $T_\mathrm{sys}$ level in counts, if you will). If one would neglect this, one had a division by very small numb... | on_noise = dummy_tsys / np.sqrt(spec_reso * smooth_nbin * sampling_interval)
ref_noise = dummy_tsys / np.sqrt(spec_reso * smooth_nbin * refpos_duration)
print('on_noise = {:.2e}, ref_noise = {:.2e}'.format(on_noise, ref_noise))
reduced_specs = np.empty((num_scan_lines, samples_per_scanline, num_maps))
xcoords, ycoord... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
We can test this, by just plotting the "raw" data for one channel. | tmp_map = reduced_specs[..., 0]
cabs = np.max(np.abs(tmp_map))
fig = pl.figure(figsize=(10, 5))
ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
_ = ax.scatter(
xcoords, ycoords, c=tmp_map,
cmap='bwr', edgecolor='none',
vmin=-cabs, vmax=cabs,
) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Now do the real gridding. First, prepare a WCS header | target_header = setup_header((0, 0), (map_width / 3600., map_height / 3600.), beamsize_fwhm / 3600.) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
We already define a WCS object for later use in our plots: | target_wcs = WCS(target_header)
# print(target_header) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Setup the gridder and define kernel sizes (half the beamsize is always a good choice). | gridder = cygrid.WcsGrid(target_header, naxis3=num_maps)
kernelsize_fwhm = beamsize_fwhm / 2
kernelsize_fwhm /= 3600. # need to convert to degree
kernelsize_sigma = kernelsize_fwhm / np.sqrt(8 * np.log(2))
support_radius = 4. * kernelsize_sigma
healpix_reso = kernelsize_sigma / 2.
gridder.set_kernel(
'gauss1d'... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
The gridder needs the coordinates as flat arrays. The data to be gridded must be a 2D array (first dimension has to match the number of coordinate samples, second dimension is the number of channels/maps in the desired data cube). | gridder.grid(xcoords.flatten() / 3600, ycoords.flatten() / 3600, reduced_specs.reshape((-1, num_maps)))
cygrid_cube = gridder.get_datacube() | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Again, as a sanity check, we plot one of the channel maps. | tmp_map = cygrid_cube[0]
cabs = np.max(np.abs(tmp_map))
fig = pl.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection=target_wcs.celestial)
ax.imshow(tmp_map, cmap='bwr', interpolation='nearest', origin='lower', vmin=-cabs, vmax=cabs)
lon, lat = ax.coords
lon.set_axislabel('R.A. [deg]')
lat.set_axislabel('Dec... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Last but not least, we can measure the noise. There are two possibilities to do this.
First, we can calculate the RMS over the full data cube. | rms_cube = np.std(cygrid_cube, ddof=1) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Second, we can calculate the RMS per plane (and the average over all planes) | rms_plane = np.mean(np.std(cygrid_cube, ddof=1, axis=(1, 2)))
print('rms_cube', rms_cube, 'rms_plane', rms_plane) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
The ultimate questions is, what is the noise level in such a map, if we account for real $T_\mathrm{sys}$ and atmospheric effects, etc. | elevations = np.array([10, 20, 30, 40, 50, 60, 90])
AM = 1. / np.sin(np.radians(elevations))
gain_correction = gaincurve(elevations, 0.954, 3.19E-3, -5.42E-5)
Tsys_corr = Tsys_zenith + T_atm * (np.exp(opacity * AM) - np.exp(opacity * 1))
print('Tsys_corr', Tsys_corr) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
$T_\mathrm{A}$ noise is now the measured noise from the gridded maps multiplied with the $T_\mathrm{sys}$ | Ta_rms = rms_cube * Tsys_corr
if dual_pol:
Ta_rms /= np.sqrt(2.) | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Note, we don't need to account for the position switch again (division by noisy reference spectrum was already performed in the reduced-spectra array creation)! | Tb_rms = Ta_to_Tb * Ta_rms / gain_correction
S_rms = Tb_rms / Gamma_MB
atm_atten = np.exp(-opacity * AM)
print('-' * 95)
print('RMS per map')
print('-' * 95)
print('{0:>8s} {1:>8s} {2:>10s} {3:>10s} {4:>10s} {5:>10s} {6:>10s} {7:>10s} {8:>10s}'.format(
'Elev', 'Airmass', 'Tsys', 'Ta RMS', 'Tb RMS', 'S RMS', 'AtmA... | notebooks/B01_OTF-map_exposure_calculator.ipynb | bwinkel/cygrid | gpl-3.0 |
Network Architecture
The encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers. The decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide rec... | learning_rate = 0.001
# Input and target placeholders
inputs_ = tf.placeholder(tf.float32, shape=(None, 28, 28, 1), name="inputs")
targets_ = tf.placeholder(tf.float32, shape=(None, 28, 28, 1), name="targets")
### Encoder
conv1 = tf.layers.conv2d(inputs_, 16, (3,3), padding='same', activation=tf.nn.relu)#parameters in... | autoencoder/Convolutional_Autoencoder.ipynb | geilerloui/deep-learning | mit |
Define a helper function for synthesize and plot the sound field from the given driving signals. | def sound_field(d, selection, secondary_source, array, grid, tapering=True):
if tapering:
tapering_window = sfs.tapering.tukey(selection, alpha=0.3)
else:
tapering_window = sfs.tapering.none(selection)
p = sfs.fd.synthesize(d, tapering_window, array, secondary_source, grid=grid)
sfs.plot... | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Circular loudspeaker arrays
In the following we show different sound field synthesis methods applied to a circular loudspeaker array. | radius = 1.5 # in m
array = sfs.array.circular(number_of_secondary_sources, radius) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Wave Field Synthesis (WFS)
Plane wave | d, selection, secondary_source = sfs.fd.wfs.plane_25d(omega, array.x, array.n, n=npw)
sound_field(d, selection, secondary_source, array, grid) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Point source | d, selection, secondary_source = sfs.fd.wfs.point_25d(omega, array.x, array.n, xs)
sound_field(d, selection, secondary_source, array, grid) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Near-Field Compensated Higher Order Ambisonics (NFC-HOA)
Plane wave | d, selection, secondary_source = sfs.fd.nfchoa.plane_25d(omega, array.x, radius, n=npw)
sound_field(d, selection, secondary_source, array, grid, tapering=False) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Point source | d, selection, secondary_source = sfs.fd.nfchoa.point_25d(omega, array.x, radius, xs)
sound_field(d, selection, secondary_source, array, grid, tapering=False) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Linear loudspeaker array
In the following we show different sound field synthesis methods applied to a linear loudspeaker array. | spacing = 0.07 # in m
array = sfs.array.linear(number_of_secondary_sources, spacing,
center=[0, -0.5, 0], orientation=[0, 1, 0]) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Wave Field Synthesis (WFS)
Plane wave | d, selection, secondary_source = sfs.fd.wfs.plane_25d(omega, array.x, array.n, npw)
sound_field(d, selection, secondary_source, array, grid) | doc/examples/sound-field-synthesis.ipynb | sfstoolbox/sfs-python | mit |
Cylindrical coordinates
The ISO standard 80000-2 recommends the use of $(ρ, φ, z)$, where $ρ$ is the radial coordinate, $\varphi$ the azimuth, and $z$ the height.
For the conversion between cylindrical and Cartesian coordinates, it is convenient to assume that the reference plane of the former is the Cartesian $xy$-pla... | # Cylinder
phi, z = np.mgrid[0:2*np.pi:31j, -2:2*np.pi:31j]
x = 2*np.cos(phi)
y = 2*np.sin(phi)
cylinder = pv.StructuredGrid(x, y, z)
# Vertical plane
rho, z = np.mgrid[0:3:31j, -2:2*np.pi:31j]
x = rho*np.cos(np.pi/4)
y = rho*np.sin(np.pi/4)
vert_plane = pv.StructuredGrid(x, y, z)
# Horizontal plane
rho, phi = np.mgr... | notebooks/vector_calculus-pyvista.ipynb | nicoguaro/AdvancedMath | mit |
Spherical coordinates
The use of $(r, θ, φ)$ to denote radial distance, inclination (or elevation), and azimuth, respectively, is common practice in physics, and is specified by ISO standard 80000-2.
The spherical coordinates of a point can be obtained from its Cartesian coordinate system $(x, y, z)$
\begin{align}
r&=\... | theta, phi = np.mgrid[0:np.pi:21j, 0:np.pi:21j]
# Sphere
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
sphere = pv.StructuredGrid(x, y, z)
sphere2 = pv.StructuredGrid(-x, -y, z)
# Cone
x = theta/3 * np.cos(phi)
y = theta/3 * np.sin(phi)
z = theta/3
cone = pv.StructuredGrid(x, y, z)
... | notebooks/vector_calculus-pyvista.ipynb | nicoguaro/AdvancedMath | mit |
Ellipsoidal coordinates | v, theta = np.mgrid[0:np.pi/2:21j, 0:np.pi:21j]
a = 3
b = 2
c = 1
# Ellipsoid
lam = 3
x = np.sqrt(a**2 + lam) * np.cos(v) * np.cos(theta)
y = np.sqrt(b**2 + lam)* np.cos(v) * np.sin(theta)
z = np.sqrt(c**2 + lam) * np.sin(v)
ellipsoid = pv.StructuredGrid(x, y, z)
ellipsoid2 = pv.StructuredGrid(x, y, -z)
ellipsoid3 ... | notebooks/vector_calculus-pyvista.ipynb | nicoguaro/AdvancedMath | mit |
References
Wikipedia contributors. "Cylindrical coordinate system." Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 12 Dec. 2016. Web. 9 Feb. 2017.
Wikipedia contributors. "Spherical coordinate system." Wikipedia, The Free Encyclopedia. Wikipedia, The Free Encyclopedia, 29 Jan. 2017. Web. 9 Feb.... | from IPython.core.display import HTML
def css_styling():
styles = open('./styles/custom_barba.css', 'r').read()
return HTML(styles)
css_styling() | notebooks/vector_calculus-pyvista.ipynb | nicoguaro/AdvancedMath | mit |
Preprocessing data | input_filename = "iris.data.txt"
att = pd.read_csv(input_filename, sep=',', header=None)
H = att.iloc[:,0:-1] # Get content to be trained
H = np.c_[np.ones(len(H)), H]
y = np.where(att.iloc[:,-1]=="Iris-setosa", 1.0, 0.0)
label = list(["Iris-virginica/versicolor","Iris-setosa"]) | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Compute norma:
$\left| \left| \nabla l(w^{(t)}) \right| \right| = \sqrt{\displaystyle \sum_{i=1}^{m} \left( w_{i}^{(t)} \right)^{2} }$
I implement Logistic Regression based on Multiple Linear Regression implementation. | def compute_norma(vector):
norma = np.sqrt( np.sum( vector ** 2 ) )
return norma | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Compute sigmoid
$\sigma (x) = \displaystyle \frac{1}{1 + e^{-x}}$ | def sigmoid(x):
sig = 1 / ( 1 + exp( - x ) )
return sig | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Compute step gradient to train Multiple Linear Regression
$\frac{\partial l(w)}{\partial w_{j} } = \displaystyle \sum{ \left( y - \frac{1}{1+e^{-\theta^{t}x}} \right) x }$ | def step_gradient(H, w_current, y, learning_rate):
diff = y - sigmoid( np.dot( H, w_current ) )
partial = np.sum( ( diff * ( H.transpose() ) ).transpose(), axis = 0 )
norma = compute_norma(partial)
w = w_current + ( learning_rate * partial )
return [w, norma] | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Compute complete gradient ascending: | def gradient_ascendent(H, y, learning_rate, epsilon):
w = np.zeros((H.shape[1])) #has the same size of output
num_iterations = 0
gradient = 1
while(gradient > epsilon):
[w, gradient] = step_gradient(H, w, y, learning_rate)
num_iterations += 1
return [w, num_iterations, gradient... | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Running the logistic regression: | learning_rate = 0.0053
epsilon = 0.001
[w, num_iterations, norm_gradient] = gradient_ascendent(H, y, learning_rate, epsilon)
print("Norma: {0}\nw: {1}\nnum_iterations: {2}\n\n".format(norm_gradient, w, num_iterations)) | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Computing the coefficients with Scikit-learn | # C value is used as regularization factor
# This is a inverse function, a high C value turn off regularization
reg = LogisticRegression(C=1e15)
reg.fit(H[:,1:], y)
print("\nCoef with scikit-learn: {0}".format(reg.coef_))
print("\nIntercept with scikit-learn: {0}".format(reg.intercept_)) | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Predict function | #Return the flower name and probability
def predict(w, x, label):
pred = sigmoid( np.dot( w, x.transpose() ) )
class_name = np.where( np.round(pred), label[1], label[0] ) #Flower name
pred = np.where( pred<0.5, 1-pred, pred ) # Flower probability
return [ class_name, np.around( pred*100, 3 ) ]
# ... | Tarefas/Programando-Regressão-Logística-do-Zero/Task 04.ipynb | italoPontes/Machine-learning | lgpl-3.0 |
Algorithm for processing Chunks
Make a partition given the extent
Produce a tuple (minx ,maxx,miny,maxy) for each element on the partition
Calculate the semivariogram for each chunk and save it in a dataframe
Plot Everything
Do the same with a mMatern Kernel | minx,maxx,miny,maxy = getExtent(new_data)
maxy
## Let's build the partition
N = 30
xp,dx = np.linspace(minx,maxx,N,retstep=True)
yp,dy = np.linspace(miny,maxy,N,retstep=True)
xx,yy = np.meshgrid(xp,yp)
coordinates_list = [ (xx[i][j],yy[i][j]) for i in range(N) for j in range(N)]
from functools import partial
tupl... | notebooks/.ipynb_checkpoints/global_variogram-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
Initial set-up
Load experiments used for original dataset calibration:
- Steady-state activation [Shibata1989]
- Steady-state inactivation [Firek1995]
- Inactivation time constant [Nygren1998]
- Recovery time constant [Nygren1998] | from experiments.ito_shibata import shibata_act
from experiments.ito_firek import firek_inact
from experiments.ito_nygren import nygren_inact_kin, nygren_rec
modelfile = 'models/nygren_ito.mmt' | docs/examples/human-atrial/nygren_ito_original.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Plot steady-state and time constant functions of original model | from ionchannelABC.visualization import plot_variables
sns.set_context('talk')
V = np.arange(-100, 40, 0.01)
nyg_par_map = {'ri': 'ito.r_inf',
'si': 'ito.s_inf',
'rt': 'ito.tau_r',
'st': 'ito.tau_s'}
f, ax = plot_variables(V, nyg_par_map, modelfile, figshape=(2,2)) | docs/examples/human-atrial/nygren_ito_original.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Combine model and experiments to produce:
- observations dataframe
- model function to run experiments and return traces
- summary statistics function to accept traces | observations, model, summary_statistics = setup(modelfile,
shibata_act,
firek_inact,
nygren_inact_kin,
nygren_rec)
assert len(... | docs/examples/human-atrial/nygren_ito_original.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.