markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Run Detection and MatchingWe're using `sep`, via the DES Y6 settings from `esheldon/sxdes`, here for simplicity. Eventually, one should use the stack itself.
import sep from sxdes import run_sep import esutil.numpy_util from ssi_tools.matching import do_balrogesque_matching sep.set_extract_pixstack(1_000_000) def _run_sep_and_add_radec(ti, img, err=None, minerr=None): if err is None: err = np.sqrt(img.variance.array.copy()) img = img.image.array.copy()...
_____no_output_____
BSD-3-Clause
examples/cosmoDC2_galaxy_hexgrid_matching_example.ipynb
LSSTDESC/ssi-tools
Financial SimulationsMeasure different investment strategies Helper FunctionsRun me before running any of the lower cells.
import pandas as pd import matplotlib.pyplot as plt import numpy as np import random findata = pd.read_csv("https://raw.githubusercontent.com/sameerkulkarni/financial_simulations/master/returns.csv", sep=",") # Add data of monthly rate of change in adj close. findata['Scale'] = findata['Adj Close'].pct_change() +1 # Ad...
_____no_output_____
MIT
base_functions.ipynb
sameerkulkarni/financial_simulations
One shot investment strategiesThe strategies below mimic the one time investments. e.g. If you have a pot of money that you need to invest into the market for "num_years".
num_years = 25 #@param {type:"slider", min:1, max:60, step:1.0} start_points=[random.randint(0,(92-num_years)*12) for i in range(NUM_SAMPLES)] yearly_returns = [calculate_returns(start_points[i],num_years) for i in range(len(start_points))] ref_returns=np.median(yearly_returns) pretty_plot_fn(yearly_returns, ref_return...
_____no_output_____
MIT
base_functions.ipynb
sameerkulkarni/financial_simulations
Systematic monthly investmentsThese simulations simulate a typical method of saving. One would start with an initial investment amount ("intial_amount"), and would then invest some moreamount on a monthly basis ("monthly_amount").These simulations also account for inflations during the months question, and thus try to...
# Number of years one has before retirement. num_years = 20 #@param {type:"slider", min:1, max:60, step:1.0} # The amount of money that one has at present that you would like to invest. initial_amount=100 #@param {type:"slider", min:10, max:200, step:1.0} # If the amount of money is large it would be advisable to split...
_____no_output_____
MIT
base_functions.ipynb
sameerkulkarni/financial_simulations
COVID-19 ish simulationsGiven the current financial situation, the current markets are a-typical. Thus the simlations below show returns around past recessions.
# Bear Markets finder (more than 20% drop from the previous high) # https://www.investopedia.com/terms/b/bearmarket.asp # Top 11 Bear market dates = http://www.nbcnews.com/id/37740147/ns/business-stocks_and_economy/t/historic-bear-markets/#.XoCWDzdKh24 bear_market_dates=['1929-09-01', '1946-05-01', '1961-12-01', '1...
_____no_output_____
MIT
base_functions.ipynb
sameerkulkarni/financial_simulations
`ApJdataFrames` Malo et al. 2014---`Title`: BANYAN. III. Radial velocity, Rotation and X-ray emission of low-mass star candidates in nearby young kinematic groups `Authors`: Malo L., Artigau E., Doyon R., Lafreniere D., Albert L., Gagne J.Data is from this paper: http://iopscience.iop.org/article/10.1088/0004-637X/72...
import warnings warnings.filterwarnings("ignore") from astropy.io import ascii import pandas as pd
_____no_output_____
MIT
notebooks/Malo2014.ipynb
BrownDwarf/ApJdataFrames
Table 1 - Target Information for Ophiuchus Sources
#! mkdir ../data/Malo2014 #! wget http://iopscience.iop.org/0004-637X/788/1/81/suppdata/apj494919t7_mrt.txt ! head ../data/Malo2014/apj494919t7_mrt.txt from astropy.table import Table, Column t1 = Table.read("../data/Malo2014/apj494919t7_mrt.txt", format='ascii') sns.distplot(t1['Jmag'].data.data) t1
_____no_output_____
MIT
notebooks/Malo2014.ipynb
BrownDwarf/ApJdataFrames
Основные виды нейросетей (CNN и RNN)**Разработчик: Алексей Умнов** Этот семинар будет состоять из двух частей: сначала мы позанимаемся реализацией сверточных и рекуррентных сетей, а потом поисследуем проблему затухающих и взрывающихся градиентов. Сверточные сетиВернемся в очередной раз к датасету MNIST. Для начала за...
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import random from IPython.display import clear_output import torch import torch.nn as nn import torch.nn.functional as F random.seed(42) np.random.seed(42) torch.manual_seed(42) if torch.cuda.is_available(): torch.cuda.manual_seed_all(42) from...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
**Задание 1:** Реализуйте сверточную сеть, которая состоит из двух последовательных применений свертки, relu и max-пулинга, а потом полносвязного слоя. Подберите параметры так, чтобы на выходе последнего слоя размерность тензора была 4 x 4 x 16. В коде ниже используется обертка nn.Sequential, ознакомьтесь с ее интерфей...
class ConvNet(nn.Module): def __init__(self): super().__init__() self.features = nn.Sequential( # <your code here> ) self.classifier = nn.Linear(4 * 4 * 16, 10) def forward(self, x): # <your code here> return F.log_softmax(ou...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Посчитаем количество обучаемых параметров сети (полносвязные сети с прошлого семинара имеют 30-40 тысяч параметров).
def count_parameters(model): model_parameters = filter(lambda p: p.requires_grad, model.parameters()) return sum([np.prod(p.size()) for p in model_parameters]) model = ConvNet() print("Total number of trainable parameters:", count_parameters(model)) %%time opt = torch.optim.RMSprop(model.parameters(), lr=0.00...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Мы с легкостью получили качество классификаци лучше, чем было раньше с помощью полносвязных сетей. На самом деле для более честного сравнения нужно поисследовать обе архитектуры и подождать побольше итераций до сходимости, но в силу ограниченности вычислительных ресурсов мы это сделать не можем. Результаты из которых "...
# На Windows придется скачать архив по ссылке (~3Mb) и распаковать самостоятельно ! wget -nc https://download.pytorch.org/tutorial/data.zip ! unzip -n ./data.zip from io import open import glob def findFiles(path): return glob.glob(path) print(findFiles('data/names/*.txt')) import unicodedata import string all_lett...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Определим несколько удобных функций для конвертации букв и слов в тензоры.**Задание 2**: напишите последнюю функцию для конвертации слова в тензор.
# Find letter index from all_letters, e.g. "a" = 0 def letterToIndex(letter): return all_letters.find(letter) # Just for demonstration, turn a letter into a <1 x n_letters> Tensor def letterToTensor(letter): tensor = torch.zeros(1, n_letters) tensor[0][letterToIndex(letter)] = 1 return tensor # Turn a...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
**Задание 3:** Реализуйте однослойную рекуррентную сеть.
class RNNCell(nn.Module): def __init__(self, input_size, hidden_size): super(RNNCell, self).__init__() self.hidden_size = hidden_size # <your code here> # <end> def forward(self, input, hidden): # <your code here> # <end> return hidden def i...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Предсказание будем осуществлять при помощи линейного класссификатора поверх скрытых состояний сети.
classifier = nn.Sequential(nn.Linear(n_hidden, n_categories), nn.LogSoftmax(dim=1))
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Проверим, что все корректно работает: выходы классификаторы должны быть лог-вероятностями.
input = letterToTensor('A') hidden = torch.zeros(1, n_hidden) output = classifier(rnncell(input, hidden)) print(output) print(torch.exp(output).sum()) input = lineToTensor('Albert') hidden = torch.zeros(1, n_hidden) output = classifier(rnncell(input[0], hidden)) print(output) print(torch.exp(output).sum())
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Для простоты в этот раз будем оптимизировать не по мини-батчам, а по отдельным примерам. Ниже несколько полезных функций для этого.
import random def randomChoice(l): return l[random.randint(0, len(l) - 1)] def randomTrainingExample(): category = randomChoice(all_categories) line = randomChoice(category_lines[category]) category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long) line_tensor = lineToTenso...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
**Задание 4:** Реализуйте вычисление ответа в функции train. Если все сделано правильно, то точность на обучающей выборке должна быть не менее 70%.
from tqdm import trange def train(category, category_tensor, line_tensor, optimizer): hidden = rnncell.initHidden() rnncell.zero_grad() classifier.zero_grad() # <your code here> # use rnncell and classifier # <end> loss = F.nll_loss(output, category_tensor) loss.backward() optimi...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Затухающие и взрывающиеся градиентыЭксперименты будем проводить опять на датасете MNIST, но будем работать с полносвязными сетями. В этом разделе мы не будем пытаться подобрать более удачную архитектуру, нам интересно только посмотреть на особенности обучения глубоких сетей.
from util import load_mnist X_train, y_train, X_val, y_val, X_test, y_test = load_mnist(flatten=True)
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Для экспериментов нам понадобится реализовать сеть, в которой можно легко менять количество слоев. Также эта сеть должна сохранять градиенты на всех слоях, чтобы потом мы могли посмотреть на их величины.**Задание 5:** допишите недостающую часть кода ниже.
class DeepDenseNet(nn.Module): def __init__(self, n_layers, hidden_size, activation): super().__init__() self.activation = activation l0 = nn.Linear(X_train.shape[1], hidden_size) self.weights = [l0.weight] self.layers = [l0] # <your code here> ...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Модифицируем наши функции обучения, чтобы они также рисовали графики изменения градиентов.
import scipy.sparse.linalg def train_epoch_grad(model, optimizer, batchsize=32): loss_log, acc_log = [], [] grads = [[] for l in model.weights] model.train() for x_batch, y_batch in iterate_minibatches(X_train, y_train, batchsize=batchsize, shuffle=True): # data preparation data = torch...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
**Задание 6:*** Обучите сети глубины 10 и больше с сигмоидой в качестве активации. Исследуйте, как глубина влияет на качество обучения и поведение градиентов на далеких от выхода слоях.* Теперь замените активацию на ReLU и посмотрите, что получится.
# ...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Теперь попробуем добавить в сеть skip-connections (по примеру ResNet) вместо замены сигмоиды на relu и посмотрим, что получится. Запихнуть все слои в nn.Sequential и просто их применить теперь не получится - вместо этого мы их применим вручную. Но положить их в отдельный модуль nn.Sequential все равно нужно, иначе torc...
class DeepDenseResNet(nn.Module): def __init__(self, n_layers, hidden_size, activation): super().__init__() self.activation = activation l0 = nn.Linear(X_train.shape[1], hidden_size) self.weights = [l0.weight] self.layers = [l0] for i in range(1, n_l...
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Убедимся, что такая сеть отлично учится даже на большом числе слоев.
model = DeepDenseResNet(n_layers=20, hidden_size=10, activation=nn.Sigmoid) opt = torch.optim.RMSprop(model.parameters(), lr=0.001) train_grad(model, opt, 10)
_____no_output_____
Apache-2.0
2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb
aosokin/DL_CSHSE_spring2018
Comandamenti Il Comitato Supremo per la Dottrina del Coding ha emanato importanti comandamenti che seguirai scrupolosamente.Se accetti le loro sagge parole, diventerai un vero Jedi Python. **ATTENZIONE**: se non segui i Comandamenti, finirai nel _Debugging Hell_ ! I COMANDAMENTO**Scriverai codice Python**Chi non scr...
i = 7 for i in range(3): # peccato, perdi la variabile i print(i) print(i) # stampa 2 e non 7 !! def f(i): for i in range(3): # altro peccato, perdi il parametro i print(i) print(i) # stampa 2, e non il 7 che gli abbiamo passato ! f(7) for i in range(2): for i in ...
0 1 2 3 4 4 0 1 2 3 4 4
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
III COMANDAMENTO**Noi riassegnerai mai parametri di funzione**Non farai mai nessuna di queste assegnazioni, pena la perdita del parametro passato quando viene chiamata la funzione:
def peccato(intero): intero = 666 # peccato, hai perso il 5 passato dall'esterno ! print(intero) # stampa 666 x = 5 peccato(x)
666
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Lo stesso discorso si applica per tutti gli altri tipi:
def male(stringa): stringa = "666" def disgrazia(lista): lista = [666] def delirio(dizionario): dizionario = {"evil":666}
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Per il solo caso di parametri compositi come liste o dizionari, puoi scrivere come sotto SE E SOLO SE le specifiche della funzione ti richiedono di MODIFICARE gli elementi interni del parametro (come per esempio ordinare una lista o cambiare il campo di un dizionario)
# MODIFICA lista in qualche modo def consentito(lista): lista[2] = 9 # OK, lo richiede il testo della funzione fuori = [8,5,7] consentito(fuori) print(fuori) # MODIFICA dizionario in qualche modo def daccordo(dizionario): dizionario["mio campo"] = 5 # OK, lo richiede il testo # MODIFI...
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Se invece il testo di una funzione ti chiede di RITORNARE un NUOVO oggetto, non cadrai nella tentazione di modificare l'input:
# RITORNA una NUOVA lista ordinata def dolore(lista): lista.sort() # MALE, stai modificando la lista di input invece di crearne una nuova! return lista # RITORNA una NUOVA lista def crisi(lista): lista[0] = 5 # MALE, come sopra return lista # RITORNA un NUOVO dizionario def tormen...
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
IV COMANDAMENTO**Non riassegnerai mai valori a chiamate a funzioni o metodi**```pythonmia_funzione() = 666 SBAGLIATO mia_funzione() = 'evil' SBAGLIATOmia_funzione() = [666] SBAGLIATO``````pythonx = 5 OKy = my_fun() OKz = [] OKz[0] = 7 ...
list("ciao")
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Quando consenti alle Forze del Male di prendere il sopravvento, potresti essere tentato di usare tipi e funzioni di sistema (per es. `list`) come una variabile per i tuoi miserabili propositi personali:```pythonlist = ['la', 'mia', 'lista', 'raccapricciante']``` Python ti permette di farlo, ma **noi no**, poichè le con...
class MiaClasse: def mio_metodo(self): self = {'mio_campo':666}
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Dato che `self` è una specie di dizionario, potresti essere tentato di scrivere come sopra, ma al mondo esterno questo non porterà alcun effetto. Per esempio, supponiamo che qualcuno da fuori faccia una chiamata come questa:
mc = MiaClasse() mc.mio_metodo()
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Dopo la chiamata `mc` non punterà a `{'mio_campo':666}`
mc
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
e non avrà `mio_campo`: ```pythonmc.mio_campo---------------------------------------------------------------------------AttributeError Traceback (most recent call last) in ()----> 1 mc.mio_campoAttributeError: 'MiaClasse' object has no attribute 'mio_campo'``` Per lo stesso ragionamento, non ...
class MiaClasse: def mio_metodo(self): self = ['evil'] self = 666
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
IX COMANDAMENTO**Testerai il codice!**Il codice non testato per definizione _non funziona_. Per idee su come testare, guarda [Gestione degli errori e testing](errors-and-testing/errors-and-testing-sol.ipynb) X COMANDAMENTO**Non aggiungerai o toglierai mai elementi da una sequenza che iteri con un** `for` **!**Abbando...
lista = ['a','b','c','d','e'] for el in lista: lista.remove(el) # PESSIMA IDEA
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Guarda bene il codice. Credi che abbiamo rimosso tutto, eh?
lista
_____no_output_____
CC-BY-4.0
commandments.ipynb
DavidLeoni/softpython-
Lab Three---For this lab we're going to be making and using a bunch of functions. Our Goals are:- Searching our Documentation- Using built in functions- Making our own functions- Combining functions- Structuring solutions
# For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them. # I want you to find a built in function to SWAP CASE on a string. Print it. # For example the string "HeY thERe HowS iT GoING" turns into "hEy THerE hOWs It gOing" sampl...
1.4142135623730951
MIT
JupyterNotebooks/Labs/Lab 3 Solution.ipynb
owenbres01/CMPT-120L-910-20F
Reconstruct phantom dataThis exercise shows how to handle data from the Siemens mMR. It shows how to get from listmode data to sinograms, get a randoms estimate, and reconstruct using normalisation, randoms and attenuation.(Scatter is not yet available from in SIRF).It is recommended you complete the first part of `ML...
#%% make sure figures appears inline and animations works %matplotlib notebook import os import sys import matplotlib.pyplot as plt from sirf.Utilities import show_2D_array, examples_data_path from sirf.STIR import * data_path = examples_data_path('PET') + '/mMR' #data_path='/home/sirfuser/data/NEMA' print('Finding fi...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Creating sinograms from listmode dataModern PET scanners can store data in listmode format. This is essentially a long list of all events detected by the scanner. We are interested here in the *prompts* (the coincidence events) and the *delayed events* (which form an estimate of the *accidental coincidences* in the pr...
template_acq_data = AcquisitionData('Siemens_mMR', span=11, max_ring_diff=15, view_mash_factor=2) template_acq_data.write('template.hs') # create listmode-to-sinograms converter object lm2sino = ListmodeToSinograms() # set input, output and template files lm2sino.set_input(list_file) lm2sino.set_output_prefix(sino_fil...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Check the prompts sinogramsThe 3D PET data returned by `as_array` are organised by 2D sinogram. The exact order of the sinogramsis complicated for 3D PET, but they by *segment* (roughly: average ring difference). The firstsegment corresponds to "segment 0", i.e. detector pairs which are (roughly) in the same detector ...
# get access to the sinograms acq_data = lm2sino.get_output() # copy the acquisition data into a Python array acq_array = acq_data.as_array()[0,:,:,:] # print the data sizes. print('acquisition data dimensions: %dx%dx%d' % acq_array.shape) # use a slice number for display that is appropriate for the NEMA phantom z = 7...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Estimate the *randoms* backgroundSiemens stores *delayed coincidences*. These form a very noisy estimate of thebackground due to accidental coincidences in the data. However, that estimate is too noisyto be used in iterative image reconstruction.SIRF uses an algorithm from STIR that gives a much less noisy estimate. T...
help(lm2sino) # Get the randoms estimate # This will take a while randoms = lm2sino.estimate_randoms()
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Plot the randoms-estimateA (2D) sinogram of the randoms has diagonal lines. This is related to thedetector efficiencies, but we cannot get into that here.
randoms_array=randoms.as_array()[0,:,:,:] show_2D_array('randoms', randoms_array[z,:,:])
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Reconstruct the dataWe will reconstruct the data with increasingly accurate models for the acquisition as illustration.For simplicity, we will use OSEM and use only a few sub-iterations for speed.
# First just select an acquisition model that implements the geometric # forward projection by a ray tracing matrix multiplication acq_model = AcquisitionModelUsingRayTracingMatrix() acq_model.set_num_tangential_LORs(10); # define objective function to be maximized as # Poisson logarithmic likelihood (with linear model...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Add detector sensitivity modellingEach crystal pair will have different detection efficiency. We need to take that into accountin our acquisition model. The scanner provides a *normalisation file* to do this (the terminologyoriginates from the days that we were "normalising" by dividing by the detected counts by the ...
# create it from the supplied file asm_norm = AcquisitionSensitivityModel(norm_file) # add it to the acquisition model acq_model.set_acquisition_sensitivity(asm_norm) # update the objective function obj_fun.set_acquisition_model(acq_model) recon.set_objective_function(obj_fun) # reconstruct image = initial_image recon....
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Add attenuation modeling
# read attenuation image attn_image = ImageData(attn_file) z = 71 attn_image.show(z) attn_acq_model = AcquisitionModelUsingRayTracingMatrix() asm_attn = AcquisitionSensitivityModel(attn_image, attn_acq_model) # converting attenuation into attenuation factors (see previous exercise) asm_attn.set_up(acq_data) attn_factor...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
We now have two acquisition_sensitivity_models: for detection sensitivity and forcount loss due to attenuation. We combine them by "chaning" them together (which willmodel the multiplication of both sensitivities).
# chain attenuation and normalisation asm = AcquisitionSensitivityModel(asm_norm, asm_attn) # update the acquisition model etc acq_model.set_acquisition_sensitivity(asm) obj_fun.set_acquisition_model(acq_model) recon.set_objective_function(obj_fun) # reconstruct image = initial_image recon.set_up(image) recon.set_curre...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Add a background term for modelling the randoms
acq_model.set_background_term(randoms) obj_fun.set_acquisition_model(acq_model) recon.set_objective_function(obj_fun) image = initial_image recon.set_up(image) recon.set_current_estimate(image) recon.process() # show reconstructed image image_array = recon.get_current_estimate().as_array() show_2D_array('Reconstructed ...
_____no_output_____
Apache-2.0
notebooks/PET/reconstruct_measured_data.ipynb
KrisThielemans/SIRF-Exercises
Initialization
# %load init.ipy %reload_ext autoreload %autoreload 2 import os, sys import numpy as np import scipy as sp import scipy.integrate import matplotlib.pyplot as plt import matplotlib as mpl CWD = os.path.abspath(os.path.curdir) print("CWD: '{}'".format(CWD)) ODIR = os.path.join(CWD, "output", "") if not os.path.exists...
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Parameters
MASS = 1e7 * MSOL FEDD = 0.1 PATH_OUTPUT = os.path.join(ODIR, 'shakura-sunyaev', '') if not os.path.exists(PATH_OUTPUT): os.makedirs(PATH_OUTPUT) thin = bhem.disks.Thin(MASS, fedd=FEDD)
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Derived
mdot = bhem.basics.eddington_accretion(MASS) rsch = bhem.basics.radius_schwarzschild(MASS) # rads = np.logspace(np.log10(6), 4, 200) * rsch rads = thin.rads freqs = np.logspace(10, 18, 120)
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Disk Primitives Profiles
# temp = bhem.basics.temperature_profile(MASS, mdot, rads) mu = 1.2 pres_over_dens = (K_BLTZ * thin.temp / (mu * MPRT)) + (4*SIGMA_SB*thin.temp**4 / (3*SPLC) ) hh = np.sqrt(pres_over_dens * 2 * (thin.rads**3) / (NWTG * thin.mass)) fig, ax = plt.subplots(figsize=[6, 4]) ax.set(xscale='log', yscale='log') ax.plot(thin.r...
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Blackbody Spectrum
# erg/s/Hz/cm^2/steradian # bb_spec_rad = bhem.basics.blackbody_spectral_radiance(MASS, mdot, rads[:, np.newaxis], freqs[np.newaxis, :]) rr = rads[np.newaxis, :] ff = freqs[:, np.newaxis] bb_spec_rad = thin._blackbody_spectral_radiance(rr, ff) xx, yy = np.meshgrid(rr, ff) norm = mpl.colors.LogNorm(vmin=1e-10, vmax=np....
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Varying Eddington Ratios : Spectra and Efficiencies
_MASS = 1e9 * MSOL fig, axes = plt.subplots(figsize=[12, 5], ncols=2) plt.subplots_adjust(wspace=0.55, left=0.08, right=0.92, top=0.96) for ax in axes: ax.set(xscale='log', yscale='log') ax.grid(True, which='major', axis='both', c='0.5', alpha=0.5) ax = axes[0] ax.set(xlabel='Frequency [Hz]', # xlim=[1e5, 1...
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
Disk Truncation
_MASS = 1e6 * MSOL _FEDD = 1e-1 VAR_LABEL = "$\log(R_\mathrm{max}/R_s)$" BAND = "v" NRAD = 100 fig, axes = plt.subplots(figsize=[12, 5], ncols=2) plt.subplots_adjust(wspace=0.55, left=0.08, right=0.92, top=0.96) for ax in axes: ax.set(xscale='log', yscale='log') ax.grid(True, which='major', axis='both', c='0....
_____no_output_____
MIT
notebooks/shakura-sunyaev.ipynb
lzkelley/bhem
$m \ddot{x} + c \dot{x} + k x + sin(x) = u$ $\vec{x} = \begin{bmatrix}x \\\dot{x}\end{bmatrix}$ $\vec{u} = \begin{bmatrix} u\end{bmatrix}$ $\vec{y} = \vec{g}(\vec{x}) = \begin{bmatrix} x\end{bmatrix}$ $\ddot{x} = (-c \dot{x} - kx + u)/m$ $\dot{\vec{x}} = \vec{f}(\vec{x}) = \begin{bmatrix}\dot{x} \\(-c \dot{x} - kx - si...
m = ca.SX.sym('m') c = ca.SX.sym('c') k = ca.SX.sym('k') p = ca.vertcat(m, c, k) u = ca.SX.sym('u') xv = ca.SX.sym('x', 2) x = xv[0] xd = xv[1] y = x xv_dot = ca.vertcat(xd, (-c*xd - k*x - ca.sin(x) + u + 3)/m) xv_dot f_rhs = ca.Function('rhs', [xv, u, p], [xv_dot], ['x', 'u', 'p'], ['x_dot'], {'jit': True}) f_rhs f...
_____no_output_____
BSD-3-Clause
lectures/4-Casadi-MSD MODIFY.ipynb
winstonlevin/aae497-f19
Linear Time Invariant Systems (LTI) * Transfer Functions: $G(s) = s/(s+1)$* State-space: $\dot{x} = Ax + Bu$, $y = Cx + Du$* Impulse response function: $g(t)$ * $\dot{x} = a_1 x + a_2 x + b u$, $y = c x + du$ Linear? (Yes) Because A = A1 + A2* $\dot{x} = a_1 x + 3 + b u$, $y = c x + du$ Linear? (No, not a linear sys...
f_rhs([0, 0], [-3], [1, 2, 3])
_____no_output_____
BSD-3-Clause
lectures/4-Casadi-MSD MODIFY.ipynb
winstonlevin/aae497-f19
$\dot{x} = Ax + Bu$, $y = Cx + Du + 3$ (non-linear -> violates zero in zero out law) Trimming an aircraft means, finding where the rhs = 0, or $f(t, x) = 0$, in order to do this we want to minimize$dot(f(t, x), f(t, x))$.
def trim_function(xv_dot): # return xv_dot[0] + xv_dot[1] # BAD, will drive to -inf return xv_dot[0]**2 + xv_dot[1]**2
_____no_output_____
BSD-3-Clause
lectures/4-Casadi-MSD MODIFY.ipynb
winstonlevin/aae497-f19
This design problems find the state at which a given input will drive the sytem to.* x is the design vector* f is the objective function* p is a list of constant parameters* S is the solver itself
nlp = {'x':xv, 'f':trim_function(xv_dot), 'p': ca.vertcat(p, u)} S = ca.nlpsol('S', 'ipopt', nlp) print(S) S(x0=(0, 0), p=(1, 2, 3, 0)) nlp = {'x':u, 'f':trim_function(xv_dot), 'p': ca.vertcat(p, xv)} S2 = ca.nlpsol('S', 'ipopt', nlp) print(S2) res = S2(x0=(0), p=(1, 2, 3, 0, 0)) #print('we need a trim input of {:f}'.f...
This is Ipopt version 3.12.3, running with linear solver mumps. NOTE: Other linear solvers might be more efficient (see Ipopt documentation). Number of nonzeros in equality constraint Jacobian...: 0 Number of nonzeros in inequality constraint Jacobian.: 0 Number of nonzeros in Lagrangian Hessian............
BSD-3-Clause
lectures/4-Casadi-MSD MODIFY.ipynb
winstonlevin/aae497-f19
TensorFlow Graphs
import tensorflow as tf n1 = tf.constant(1) n2 = tf.constant(2) n3 = n1 + n2 with tf.Session() as sess: result = sess.run(n3) print(result) print(tf.get_default_graph()) g = tf.Graph() print(g) graph_one = tf.get_default_graph() print(graph_one) graph_two = tf.Graph() print(graph_two) with graph_two.as_default(): ...
False
MIT
Section 1/1.3_TensorFlow_Graphs.ipynb
manpreet-kau-r/Hands-on-Machine-Learning-with-TensorFlow
Read supplementary material csvs from https://www.ncbi.nlm.nih.gov/pubmed/29425488
human_tfs = pd.read_csv("http://humantfs.ccbr.utoronto.ca/download/v_1.01/DatabaseExtract_v_1.01.csv", index_col=0) print(human_tfs.shape) human_tfs.head() human_tfs.to_csv("Lambert_Jolma_Campitelli_etal_2018_human_transcription_factors.csv", index=False) true_tfs = human_tfs.loc[human_tfs['Is TF?'] == "Yes"] print(t...
_____no_output_____
MIT
notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb
czbiohub/kh-analysis
regex made with: https://regex101.com/r/7IzJgx/1
pattern = "(?P<protein_id>ENSP\d+\.\d+) (?P<seqtype>\w+) (?P<location>chromosome:GRCh38:[\dXY]+:\d+:\d+:\d+) gene:(?P<gene_id>ENSG\d+\.\d+) transcript:(?P<transcript_id>ENST\d+\.\d+) gene_biotype:(?P<gene_biotype>\w+) transcript_biotype:(?P<transcript_biotype>\w+) gene_symbol:(?P<gene_symbol>\w+) description:(?P<descri...
_____no_output_____
MIT
notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb
czbiohub/kh-analysis
Updated regex to work with all fasta entries of TFs: https://regex101.com/r/7IzJgx/2
lines = [] PATTERN = r"(?P<protein_id>ENSP\d+\.\d+) (?P<seqtype>\w+) (?P<location>chromosome:GRCh38:[\dXY]+:\d+:\d+:-?\d+) gene:(?P<gene_id>ENSG\d+\.\d+) transcript:(?P<transcript_id>ENST\d+\.\d+) gene_biotype:(?P<gene_biotype>\w+) transcript_biotype:(?P<transcript_biotype>\w+) gene_symbol:(?P<gene_symbol>[\w\.\-]+) d...
Ensembl ID,HGNC symbol,DBD,Is TF?,Final Comments ENSG00000214189,ZNF788,C2H2 ZF,Yes,Virtually nothing is known for this protein except that it has a decent cassette of znfC2H2 domains ENSG00000228623,ZNF883,C2H2 ZF,Yes,None DUX1_HUMAN,DUX1,Homeodomain,Yes,Not included in Ensembl. Binds GATCTGAGTCTAATTGAGAATTACTGTAC in ...
MIT
notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb
czbiohub/kh-analysis
Are these TFs in the fasta file? `DUX1` and `DUX3` are likely not
! zcat Homo_sapiens.GRCh38.pep.all.fa.gz | grep ZNF788 for i, (ensembl_id, gene_symbol) in true_tfs_not_in_ensembl97[['Ensembl ID', 'HGNC symbol']].iterrows(): print(f"Grep for {ensembl_id}") ! zcat Homo_sapiens.GRCh38.pep.all.fa.gz | grep $ensembl_id print(f"Grep for {gene_symbol}") ! zcat Homo_s...
Grep for ENSG00000214189 Grep for ZNF788 Grep for ENSG00000228623 Grep for ZNF883 >ENSP00000490059.1 pep chromosome:GRCh38:9:112997120:113050043:-1 gene:ENSG00000285447.1 transcript:ENST00000619044.1 gene_biotype:protein_coding transcript_biotype:protein_coding gene_symbol:ZNF883 description:zinc finger protein 883 [So...
MIT
notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb
czbiohub/kh-analysis
Batch Normalization from scratchWhen you train a linear model, you update the weightsin order to optimize some objective.And for the linear model, the distribution of the inputs stays the same throughout training.So all we have to worry about is how to map from these well-behaved inputs to some appropriate outputs.But...
from __future__ import print_function import mxnet as mx import numpy as np from mxnet import nd, autograd mx.random.seed(1) ctx = mx.gpu()
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
The MNIST dataset
batch_size = 64 num_inputs = 784 num_outputs = 10 def transform(data, label): return nd.transpose(data.astype(np.float32), (2,0,1))/255, label.astype(np.float32) train_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train=True, transform=transform), batch_size, shuff...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Batch Normalization layerThe layer, unlike Dropout, is usually used **before** the activation layer (according to the authors' original paper), instead of after activation layer.The basic idea is doing the normalization then applying a linear scale and shift to the mini-batch:For input mini-batch $B = \{x_{1, ..., m}\...
def pure_batch_norm(X, gamma, beta, eps = 1e-5): if len(X.shape) not in (2, 4): raise ValueError('only supports dense or 2dconv') # dense if len(X.shape) == 2: # mini-batch mean mean = nd.mean(X, axis=0) # mini-batch variance variance = nd.mean((X - mean) ** 2, axis=...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Let's do some sanity checks. We expect each **column** of the input matrix to be normalized.
A = nd.array([1,7,5,4,6,10], ctx=ctx).reshape((3,2)) A pure_batch_norm(A, gamma = nd.array([1,1], ctx=ctx), beta=nd.array([0,0], ctx=ctx)) ga = nd.array([1,1], ctx=ctx) be = nd.array([0,0], ctx=ctx) B = nd.array([1,6,5,7,4,3,2,5,6,3,2,4,5,3,2,5,6], ctx=ctx).reshape((2,2,2,2)) B pure_batch_norm(B, ga, be)
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Our tests seem to support that we've done everything correctly.Note that for batch normalization, implementing **backward** pass is a little bit tricky. Fortunately, you won't have to worry about that here, because the MXNet's `autograd` package can handle differentiation for us automatically. Besides that, in the test...
def batch_norm(X, gamma, beta, momentum = 0.9, eps = 1e-5, scope_name = '', is_training = True, debug = False): """compute the batch norm """ global _BN_MOVING_MEANS, _BN_MOVING_VARS ###############...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Parameters and gradients
####################### # Set the scale for weight initialization and choose # the number of hidden units in the fully-connected layer ####################### weight_scale = .01 num_fc = 128 W1 = nd.random_normal(shape=(20, 1, 3,3), scale=weight_scale, ctx=ctx) b1 = nd.random_normal(shape=20, scale=weight_scale,...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Activation functions
def relu(X): return nd.maximum(X, 0)
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Softmax output
def softmax(y_linear): exp = nd.exp(y_linear-nd.max(y_linear)) partition = nd.nansum(exp, axis=0, exclude=True).reshape((-1,1)) return exp / partition
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
The *softmax* cross-entropy loss function
def softmax_cross_entropy(yhat_linear, y): return - nd.nansum(y * nd.log_softmax(yhat_linear), axis=0, exclude=True)
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Define the modelWe insert the BN layer right after each linear layer.
def net(X, is_training = True, debug=False): ######################## # Define the computation of the first convolutional layer ######################## h1_conv = nd.Convolution(data=X, weight=W1, bias=b1, kernel=(3,3), num_filter=20) h1_normed = batch_norm(h1_conv, gamma1, beta1, scope_name='bn1',...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Test runCan data be passed into the `net()`?
for data, _ in train_data: data = data.as_in_context(ctx) break output = net(data, is_training=True, debug=True)
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Optimizer
def SGD(params, lr): for param in params: param[:] = param - lr * param.grad
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Evaluation metric
def evaluate_accuracy(data_iterator, net): numerator = 0. denominator = 0. for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(ctx) label = label.as_in_context(ctx) label_one_hot = nd.one_hot(label, 10) output = net(data, is_training=False) # attention...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Execute the training loopNote: you may want to use a gpu to run the code below. (And remember to set the `ctx = mx.gpu()` accordingly in the very beginning of this article.)
epochs = 1 moving_loss = 0. learning_rate = .001 for e in range(epochs): for i, (data, label) in enumerate(train_data): data = data.as_in_context(ctx) label = label.as_in_context(ctx) label_one_hot = nd.one_hot(label, num_outputs) with autograd.record(): # we are in trai...
_____no_output_____
Apache-2.0
chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb
sgeos/mxnet_the_straight_dope
Collection of Helpful Functions for [Class](https://sites.wustl.edu/jeffheaton/t81-558/)This is a collection of helpful functions that I will introduce during this course.
import base64 import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import requests from sklearn import preprocessing # Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue) def encode_text_dummy(df, name): dummies = pd.get_dummies(df[name]) for x i...
_____no_output_____
Apache-2.0
jeffs_helpful.ipynb
guyvani/t81_558_deep_learning
Rudder equations
%load_ext autoreload %autoreload 2 %matplotlib inline import sympy as sp from sympy.plotting import plot as plot from sympy.plotting import plot3d as plot3d import pandas as pd import numpy as np import matplotlib.pyplot as plt sp.init_printing() from IPython.core.display import HTML,Latex import seaman_symbol as ss fr...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Coordinate system![coordinate_system](coordinateSystem.png) Symbols
#HTML(ss.create_html_table(symbols=equations.total_sway_hull_equation_SI.free_symbols))
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Rudder equationThe rudder forces consist of mainly two parts, one that isdepending on the ship axial speed and one that is depending on the thrust.The stalling effect is represented by a third degree term with a stall coefficient s.The total expression for the rudder force is thus written as:
rudder_equation_no_stall
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
If we also consider stall
rudder_equation
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Effective rudder angle
effective_rudder_angle_equation delta_e_expanded
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Speed dependent part
Latex(sp.latex(rudder_u_equation))
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Thrust dependent partThis part is assumed to be proportional to the propeller thrust
rudder_T_equation sp.latex(rudder_total_sway_equation) rudder_total_sway_equation_SI
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Rudder resistanceThe rudder resistance is taken to be proportional to the rudder side force (without stall) and therudder angle, thus:
rudder_drag_equation sp.latex(rudder_drag_equation_expanded) rudder_drag_equation_expanded_SI
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Rudder yawing moment
rudder_yaw_equation rudder_yaw_equation_expanded_SI
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Rudder roll moment
rudder_roll_equation rudder_roll_equation_expanded_SI = ss.expand_bis(rudder_roll_equation_expanded) rudder_roll_equation_expanded_SI
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Lambda functions
from rudder_lambda_functions import *
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting effective rudder angle equation
df = pd.DataFrame() V = 5.0 beta = np.deg2rad(np.linspace(-10,10,20)) df['u_w'] = V*np.cos(beta) df['v_w'] = -V*np.sin(beta) df['delta'] = np.deg2rad(5) df['r_w'] = 0.0 df['L'] = 50.0 df['k_r'] = 0.5 df['k_v'] = -1.0 df['g'] = 9.81 df['xx_rud'] = -1 df['l_cg'] = 0 result = df.copy() result['delta_e'] = effective_rudd...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting the total sway rudder equation
df = pd.DataFrame() df['delta'] = np.linspace(-0.3,0.3,10) df['T_prop'] = 1.0 df['n_prop'] = 1.0 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['L'] = 1.0 df['k_r'] = 1.0 df['k_v'] = 1.0 df['g'] = 9.81 df['disp'] = 23.0 df['s'] = 0 df['Y_Tdelta'] = 1.0 df['Y_uudelta'] = 1.0 df['xx_rud'] = -1 df['l_...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting with coefficients from a real seaman ship model
import generate_input ship_file_path='test_ship.ship' shipdict = seaman.ShipDict.load(ship_file_path) df = pd.DataFrame() df['delta'] = np.deg2rad(np.linspace(-35,35,20)) df['T_prop'] = 10*10**6 df['n_prop'] = 1 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['g'] = 9.81 df_input = generate_input.a...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting the total rudder drag equation
df = pd.DataFrame() df['delta'] = np.linspace(-0.3,0.3,20) df['T'] = 1.0 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['L'] = 1.0 df['k_r'] = 1.0 df['k_v'] = 1.0 df['g'] = 9.81 df['disp'] = 23.0 df['s'] = 0 df['Y_Tdelta'] = 1.0 df['Y_uudelta'] = 1.0 df['X_Yrdelta'] = -1.0 df['xx_rud'] = -1 df['l_c...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Real seaman has a maximum effective rudder angle 0.61 rad for the rudder drag, which is why seaman gives different result for really large drift angles or yaw rates:
df = pd.DataFrame() df['delta'] = np.deg2rad(np.linspace(-45,45,50)) df['T'] = 10*10**6 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['g'] = 9.81 result_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_drag_function, s...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting the rudder yawing moment equation
df = pd.DataFrame() df['delta'] = np.deg2rad(np.linspace(-35,35,20)) df['T'] = 10*10**6 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['g'] = 9.81 result_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_yawing_moment_function, ...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Plotting the rudder roll moment equation
df = pd.DataFrame() df['delta'] = np.deg2rad(np.linspace(-35,35,20)) df['T'] = 10*10**6 df['u_w'] = 5.0 df['v_w'] = 0.0 df['r_w'] = 0.0 df['rho'] = 1025 df['g'] = 9.81 result_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_roll_moment_function, ...
_____no_output_____
MIT
docs/seaman/04.1_seaman_rudder_equation.ipynb
martinlarsalbert/wPCC
Combining Pulse TemplatesSo far we have seen how to define simple pulses using the `TablePulseTemplate` ([Modelling a Simple TablePulseTemplate](00SimpleTablePulse.ipynb)), `FunctionPulseTemplate` ([Modelling Pulses Using Functions And Expressions](02FunctionPulse.ipynb)) and `PointPulseTemplate` ([The PointPulseTempl...
from qupulse.pulses import PointPT, SequencePT # create our atomic "low-level" PointPTs first_point_pt = PointPT([(0, 'v_0'), (1, 'v_1', 'linear'), ('t', 'v_0+v_1', 'jump')], channel_names={'A'}, measurements={('M'...
sequence parameters: {'t_2', 'v_1', 'v_0', 't'} sequence measurements: {'M'}
MIT
doc/source/examples/03xComposedPulses.ipynb
lankes-fzj/qupulse
It is important to note that all of the pulse templates used to create a `SequencePT` (we call those *subtemplates*) are defined on the same channels, in this case the channel `A` (otherwise we would encounter an exception). The `SequencePT` will also be defined on the same channel.The `SequencePT` will further have th...
%matplotlib notebook from qupulse.pulses.plotting import plot parameters = dict(t=3, t_2=2, v_0=1, v_1=1.4) _ = plot(first_point_pt, parameters, sample_rate=100) _ = plot(second_point_pt, parameters, sample_rate=100) _ = plot(sequence_pt, parameters, sample_rate=1...
_____no_output_____
MIT
doc/source/examples/03xComposedPulses.ipynb
lankes-fzj/qupulse
RepetitionPulseTemplate: Repeating a PulseIf we simply want to repeat some pulse template a fixed number of times, we can make use of the `RepetitionPulseTemplate`. In the following, we will reuse one of our `PointPT`s, `first_point_pt` and use it to create a new pulse template that repeats it `n_rep` times, where `n_...
from qupulse.pulses import RepetitionPT repetition_pt = RepetitionPT(first_point_pt, 'n_rep') print("repetition parameters: {}".format(repetition_pt.parameter_names)) print("repetition measurements: {}".format(repetition_pt.measurement_names)) # let's plot to see the results parameters['n_rep'] = 5 # add a value for...
repetition parameters: {'v_1', 'n_rep', 'v_0', 't'} repetition measurements: {'M'}
MIT
doc/source/examples/03xComposedPulses.ipynb
lankes-fzj/qupulse
The same remarks that were made about `SequencePT` also hold for `RepetitionPT`: it will expose all parameters and measurements defined by its subtemplate and will be defined on the same channels. ForLoopPulseTemplate: Repeat a Pulse with a Varying Loop ParameterThe `RepetitionPT` simple repeats the exact same subtempl...
from qupulse.pulses import ForLoopPT for_loop_pt = ForLoopPT(first_point_pt, 't', ('t_start', 't_end', 2)) print("for loop parameters: {}".format(for_loop_pt.parameter_names)) print("for loop measurements: {}".format(for_loop_pt.measurement_names)) # plot it parameters['t_start'] = 4 parameters['t_end'] = 13 _ = plo...
for loop parameters: {'t_start', 'v_1', 'v_0', 't_end'} for loop measurements: {'M'}
MIT
doc/source/examples/03xComposedPulses.ipynb
lankes-fzj/qupulse
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. 02. Facial Expression Recognition using ONNX Runtime GPU on AzureMLThis example shows how to deploy an image classification neural network using the Facial Expression Recognition ([FER](https://www.kaggle.com/c/challenges-in-rep...
# Check core SDK version number import azureml.core print("SDK version:", azureml.core.VERSION) from azureml.core import Workspace ws = Workspace.from_config() print(ws.name, ws.location, ws.resource_group, ws.location, sep = '\n')
_____no_output_____
MIT
onnx/onnx-inference-emotion-recognition.ipynb
sxusx/MachineLearningNotebooks