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 |
|---|---|---|---|---|---|
[this doc on github](https://github.com/dotnet/interactive/tree/main/samples/notebooks/powershell) Interactive Host Experience in PowerShell notebook The PowerShell notebook provides a rich interactive experience through its host.The following are some examples. 1. _You can set the foreground and background colors for ... | $host.UI.RawUI.ForegroundColor = [System.ConsoleColor]::Blue
$PSVersionTable | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
2. _You can write to the host with specified foreground and background colors_ | Write-Host "Something to think about ..." -ForegroundColor Blue -BackgroundColor Gray | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
3. _Warning, Verbose, and Debug streams are rendered with the expected color:_ | Write-Warning "Warning"
Write-Verbose "Verbose" -Verbose
Write-Debug "Debug" -Debug | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
4. _You can use `Write-Host -NoNewline` as expected:_ | Write-Host "Hello " -NoNewline -ForegroundColor Red
Write-Host "World!" -ForegroundColor Blue | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
5. _You can read from user for credential:_ | $cred = Get-Credential
"$($cred.UserName), password received!" | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
6. _You can read from user for regular input:_ | Write-Verbose "Ask for name" -Verbose
$name = Read-Host -Prompt "What's your name? "
Write-Host "Greetings, $name!" -ForegroundColor DarkBlue | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
7. _You can read from user for password:_ | Read-Host -Prompt "token? " -AsSecureString | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
8. _You can use the multi-selection when running commands:_ | Get-Command nonExist -ErrorAction Inquire | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
9. _You can user the mandatory parameter prompts:_ | Write-Output | ForEach-Object { "I received '$_'" } | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
10. _Of course, pipeline streaming works:_ | Get-Process | select -First 5 | % { start-sleep -Milliseconds 300; $_ } | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
11. _Progress bar rendering works as expected:_ | ## Demo the progress bar
For ($i=0; $i -le 100; $i++) {
Write-Progress -Id 1 -Activity "Parent work progress" -Status "Current Count: $i" -PercentComplete $i -CurrentOperation "Counting ..."
For ($j=0; $j -le 10; $j++) {
Start-Sleep -Milliseconds 5
Write-Progress -Parent 1 -Id 2 -Activity "Chi... | _____no_output_____ | MIT | samples/notebooks/powershell/Docs/Interactive-Host-Experience.ipynb | flcdrg/dotnet-interactive |
Fundamentos de Análise de Dados 2022.1 Trabalho 01 - Regressão: _Naval Propulsion Plants_**Nome:** Carolina Araújo Dias Dataset_Naval Propulsion Plants_: regressão múltipla (2 variáveis de saída), estimar cada variável de saída separadamente:- 11934 amostras;- 16 características reais;- 2 características reais para e... | !python --version
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Funções Auxiliares | def check_constant_columns(dataframe: pd.DataFrame) -> None:
"""Checa se existem colunas constantes no dataframe
e imprime o nome e os valores de tais colunas."""
for column in dataframe.columns:
if len(dataframe[column].unique()) == 1:
print(f'Coluna: "{column}", Valor constante: {da... | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
02. Fazer a leitura dos dados | column_names = [
"Lever position",
"Ship speed",
"Gas Turbine shaft torque",
"GT rate of revolutions",
"Gas Generator rate of revolutions",
"Starboard Propeller Torque",
"Port Propeller Torque",
"Hight Pressure Turbine exit temperature",
"GT Compressor inlet air temperature",
"GT... | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Só por olharmos para os dados conseguimos enxergar alguns problemas com as colunas. Por exemplo, aparentemente as colunas `Starboard Propeller Torque` e `Port Propeller Torque` são iguais. Além disso, as colunas `GT Compressor inlet air temperature` e `GT Compressor inlet air pressure` parecem ter apenas um valor const... | if raw_data['Starboard Propeller Torque'].equals(raw_data['Port Propeller Torque']):
print(f'As colunas "Starboard Propeller Torque" e "Port Propeller Torque" são iguais.')
else:
print(f'As colunas não são iguais.')
check_constant_columns(raw_data) | Coluna: "GT Compressor inlet air temperature", Valor constante: [288.]
Coluna: "GT Compressor inlet air pressure", Valor constante: [0.998]
| MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Como identificamos essas colunas problemáticas, iremos removê-las a seguir. | data = raw_data.copy()
data.drop(['GT Compressor inlet air temperature',
'GT Compressor inlet air pressure',
'Port Propeller Torque'],
axis=1,
inplace=True) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
03. Se necessário, dividir os dados em conjunto de treinamento (70%) e teste (30%), utilizando a função apropriada do scikit-learn. Quatro NumPy arrays devem ser criados: X_train, y_train, X_test e y_test. | data.drop(["GT Turbine decay state coefficient"],
axis=1,
inplace=True)
print(f'Formato dos dados completos: {data.shape}')
X = data.drop(["GT Compressor decay state coefficient"],
axis=1)
y = data[["GT Compressor decay state coefficient"]]
print(f'Formato de X: {X.shape}')
print(f... | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
04. Acrescentar uma coluna de 1s ([1 1 . . . 1]^T) como última coluna da matriz de treinamento X_train. Repita o procedimento para a matriz de teste, chamando-a de X_test_2. [StackOverflow: How to add an extra column to a NumPy array](https://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-a-numpy-ar... | add_ones_column(X_train).shape | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
05. Calcular o posto das matrizes X_train_2 e X_test_2. Se necessário, ajustar as matrizes X_train_2 e X_test_2. Antes de remover as 3 colunas problemáticas: | raw_data.shape
X_raw = raw_data.drop(["GT Compressor decay state coefficient",
"GT Turbine decay state coefficient"],
axis=1)
add_ones_column(X_raw).shape
np.linalg.matrix_rank(add_ones_column(X_raw)) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Após remover as 3 colunas problemáticas: | np.linalg.matrix_rank(add_ones_column(X_train))
np.linalg.matrix_rank(add_ones_column(X_test))
add_ones_column(X_train).shape | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
06. Calcular a decomposição QR da matriz de treinamento: X_train_2 = QR, usando a função do NumPy apropriada. | Q, R = np.linalg.qr(add_ones_column(X_train)) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Questão 04Verificar numericamente que $Q^TQ = I$, para o respectivo banco de dados.*R.* Multiplicamos $Q^T$ por Q e salvamos em uma matriz M e comparamos essa matriz com uma matriz identidade de mesma dimensão. A função `np.allclose()` compara os valores levando em consideração as aproximações dos número. | M = np.matmul(Q.T, Q)
np.allclose(M, np.eye(M.shape[0])) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
07. Calcular o vetor de coeficientes $\mathbf{\tilde{x}}$ da Equação (1), utilizando a função do NumPy `linalg.solve()`. | coefs_lineares = np.linalg.solve(R, np.dot(Q.T, y_train)) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
08. Calcular as estimativas do modelo para os valores de treinamento e teste, utilizando o vetor de coeficientes $\mathbf{\tilde{x}}$, calculado no item anterior. Treino | y_train_preds = []
for i in range(len(X_train)):
y_train_preds.append(np.dot(np.squeeze(coefs_lineares), add_ones_column(X_train)[i])) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Teste | y_test_preds = []
for i in range(len(X_test)):
y_test_preds.append(np.dot(np.squeeze(coefs_lineares), add_ones_column(X_test)[i])) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
09. Gerar um gráfico com os valores reais de treinamento no eixo das abscissas e valores estimados de treinamento no eixo das ordenadas. Acrescentar ao gráfico uma reta pontilhada a +45◦ do eixo das abscissas. Treino | plot_data(x=y_train, y=y_train_preds) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Teste | plot_data(x=y_test, y=y_test_preds) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
10. Calcular a **raiz quadrada do erro médio quadrático** (RMSE) dos dados de treinamento e de teste. Treino | mean_squared_error(y_train, y_train_preds, squared=False) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Teste | mean_squared_error(y_test, y_test_preds, squared=False) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Repetir todo o processo acima para o outro target `GT Turbine decay state coefficient` | data = raw_data.copy()
data.drop(['GT Compressor inlet air temperature',
'GT Compressor inlet air pressure',
'Port Propeller Torque'],
axis=1,
inplace=True)
data.drop(["GT Compressor decay state coefficient"],
axis=1,
inplace=True)
X = data.drop(["GT Turb... | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Treino | mean_squared_error(y_train, y_train_preds, squared=False)
plot_data(x=y_train, y=y_train_preds) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Teste | mean_squared_error(y_test, y_test_preds, squared=False)
plot_data(x=y_test, y=y_test_preds) | _____no_output_____ | MIT | trabalho01_regressao/trabalho01_regressao_naval_dataset.ipynb | diascarolina/fundamentos-analise-dados |
Tutorial HowToAdaptiveOpticsThis report provides a tutorial to use the code develloped to compute the PSIM for the ELT SCAO systems. The code is object-oriented and its architecture is quite inspired from the ([OOMAO simulator](https://github.com/cmcorreia/LAM-Public/tree/master/_libOomao)). Modules requiredThe code ... | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 10:51:32 2020
@author: cheritie
"""
# commom modules
import matplotlib.pyplot as plt
import numpy as np
import time
# adding AO_Module to the path
import __load__psim
__load__psim.load_psim()
# loading AO modules
from AO_modules.Atmosphere import A... | Looking for AO_Modules...
['../AO_modules']
AO_Modules found! Loading the main modules:
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Read Parameter File | #import parameter file (dictionnary)
from parameterFile_VLT_I_Band import initializeParameterFile
param = initializeParameterFile()
# the list of the keys contained in the dictionnary can be printed using the following lines
# for key, value in param.items() :
# print (key, value) | Reading/Writting calibration data from /Disk3/cheritier/psim/data_calibration/
Writting output data in /diskb/cheritier/psim/data_cl
Creation of the directory /diskb/cheritier/psim/data_cl failed:
Directory already exists!
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Telescope Object | # create the Telescope object
tel = Telescope(resolution = param['resolution'],\
diameter = param['diameter'],\
samplingTime = param['samplingTime'],\
centralObstruction = param['centralObstruction']) | NGS flux updated!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SOURCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Wavelength 0.55 [microns]
Optical Band V
Magnitude -0.0
Flux 8967391304.0 [photons/m2/s]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SOURCE %%%%%%%%%%%%%%%%%%%%%%%%%%... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The mai informations contained in the telescope objects are the following: * tel. pupil : the pupil of the telescope as a 2D mask* tel.src : the source object attached to the telescope that contains the informations related to the wavelength, flux and phase. The default wavelength is the V band with a magnitude 0.* ... | tel.show() | telescope:
D: 8
OPD: (80, 80)
centralObstruction: 0
fov: 0
index_pixel_petals: None
isPaired: False
isPetalFree: False
pixelArea: 5024
pixelSize: 0.1
pupil: (80, 80)
pupilLogical: (1, 5024)
pupilRefle... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
We can show the 2D map corresponding to the pupil or to the OPD: | plt.figure()
plt.subplot(1,2,1)
plt.imshow(tel.pupil.T)
plt.title('Telescope Pupil: %.0f px in the pupil' %tel.pixelArea)
plt.subplot(1,2,2)
plt.imshow(tel.OPD.T)
plt.title('Telescope OPD [m]')
plt.colorbar() | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
And we can display the property of the child class tel.src that correspond to the default source object attached to the telescope: | tel.src.show() | source:
bandwidth: 9e-08
magnitude: -0.0
nPhoton: 8967391304.347826
optBand: V
phase: (80, 80)
tag: source
wavelength: 5.5e-07
zeroPoint: 8967391304.347826
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Source ObjectThe Source object allows to access the properties related to the flux and wavelength of the object. We consider only on-axis objects as a start. | ngs=Source(optBand = param['opticalBand'],\
magnitude = param['magnitude'])
print('NGS Object built!') | NGS flux updated!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SOURCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Wavelength 0.79 [microns]
Optical Band I
Magnitude 8.0
Flux 4629307.0 [photons/m2/s]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SOURCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The NGS object has to be attached to a telescope object using the ***** operator. This operation sets the telescope property tel.src to the ngs object considered. | ngs*tel | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The ngs object is now attached to the telescope. This means that the tel.src object now has a **phase** and a **fluxMap** property.If we display the properties of ngs and tel.src, they are the same: | # properties of ngs
ngs.show()
# properties of tel.src
tel.src.show() | source:
bandwidth: 1.5e-07
fluxMap: (80, 80)
magnitude: 8.0
nPhoton: 4629306.603523155
optBand: I
phase: (80, 80)
tag: source
var: 8.673617379884035e-19
wavelength: 7.9e-07
zeroPoint: 7336956521.73913
source:
b... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
We can compute and display the PSF corresponding to the telescope OPD and Source object attached to the telescope. |
zeroPaddingFactor = 8
tel.computePSF(zeroPaddingFactor = zeroPaddingFactor)
PSF_normalized = tel.PSF/tel.PSF.max()
nPix = zeroPaddingFactor*tel.resolution//3
plt.figure()
plt.imshow(np.log(np.abs(PSF_normalized[nPix:-nPix,nPix:-nPix])))
plt.clim([-13,0])
plt.colorbar()
| _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Atmosphere ObjectThe atmosphere object is created mainly from the telescope properties (diameter, pupil, samplingTime)and the *r0* and *L0* parameters. It is possible to generate multi-layers, each one is a child-class of the atmosphere object with its own set of parameters (windSpeed, Cn^2,windDirection, altitude). | atm=Atmosphere(telescope = tel,\
r0 = param['r0'],\
L0 = param['L0'],\
windSpeed = param['windSpeed'],\
fractionalR0 = param['fractionnalR0'],\
windDirection = param['windDirection'],\
altitude ... | Atmosphere Object built!
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The atmosphere object has to be initialized using: | # initialize atmosphere
atm.initializeAtmosphere(tel)
print('Done!') | Creation of layer1/5 ...
-> Computing the initial phase screen...
initial phase screen : 0.023934602737426758 s
ZZt.. : 0.7004520893096924 s
ZXt.. : 0.3715839385986328 s
XXt.. : 0.2279503345489502 s
Done!
Creation of layer2/5 ...
-> Computing the initial phase screen...
initial phase screen : 0.036902666091918945 s
ZZt... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Similarly to the Source object, the atmosphere object can be paired to the telescope **+**. In that case, if the atmosphere OPD is updated, the telescope OPD is automatically updated. | tel+atm
print(tel.isPaired) | Telescope and Atmosphere combined!
True
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
We can display the properties of the telescope object: | plt.figure()
plt.imshow(tel.OPD.T)
plt.title('Telescope OPD [m]')
plt.colorbar()
plt.figure()
plt.imshow(tel.src.phase.T)
plt.colorbar()
plt.title('NGS Phase [rad]') | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The atmosphere and the telescope can be separated using the **-** operator. This brings back the system to a diffraction limited case with a flat OPD. | tel-atm
print(tel.isPaired) | Telescope and Atmosphere separated!
False
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Deformable Mirror ObjectThe deformable mirror is mainly characterized with its influence functions. They can be user-defined and loaded in the model but the default case is a cartesian DM with gaussian influence functions and normalized to 1. The DM is always defined in the pupil plane. | dm=DeformableMirror(telescope = tel,\
nSubap = param['nSubaperture'],\
mechCoupling = param['mechanicalCoupling'])
print('Done!') | No coordinates loaded.. taking the cartesian geometry as a default
Generating a Deformable Mirror:
Computing the 2D zonal modes...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFORMABLE MIRROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Controlled Actuators 357
M4 influence functions No
Pixel Size 0.1 [m]
Pitch 0.4 [m]
Mechanical... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
We can display the cube of the influence functions to display the position of the actuators. | cube_IF = np.reshape(np.sum(dm.modes**3, axis =1),[tel.resolution,tel.resolution])
plt.figure()
plt.imshow(cube_IF.T) | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Light propagationThe light can be propagate through the DM using the ***** operator. To update the DM surface, the property **dm.coefs** must be updated to set the new values of the DM coefficients.Typically, using a random command vector, we can propagate the light through the DM (light is reflected hence the sign ch... | tel-atm
dm.coefs = (np.random.rand(dm.nValidAct)-0.5)*100e-9
tel*dm
plt.figure()
plt.subplot(121)
plt.imshow(dm.OPD)
plt.title('DM OPD [m]')
plt.colorbar()
plt.subplot(122)
plt.imshow(tel.OPD)
plt.colorbar()
plt.title('Telescope OPD [m]')
plt.figure()
plt.imshow(atm.OPD_no_pupil)
plt.colorbar()
plt.title('Atmosphere O... | Telescope and Atmosphere separated!
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Mis-registrationsThe DM/WFS mis-registrations are applied directly in the DM space, applying the transformations on the DM influence functions. First we create a **MisRegistration Object** that is initialized to 0. We can then update the values of the mis-registrations and input it to the DM model: | misReg = MisRegistration()
misReg.rotationAngle = 3
misReg.shiftX = 0.3*param['diameter']/param['nSubaperture']
misReg.shiftY = 0.25*param['diameter']/param['nSubaperture']
dm_misReg = DeformableMirror(telescope = tel,\
nSubap = param['nSubaperture'],\
mec... | No coordinates loaded.. taking the cartesian geometry as a default
Generating a Deformable Mirror:
Computing the 2D zonal modes...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFORMABLE MIRROR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Controlled Actuators 357
M4 influence functions No
Pixel Size 0.1 [m]
Pitch 0.4 [m]
Mechanical... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Pyramid ObjectThe pyramid object consists mainly in defining the PWFS mask to apply the filtering of the electro-magnetic field. Many parameters can allow to tune the pyramid model:* Centering of the mask and of the FFT on 1 or 4 pixels* Modulation radius in λ/D. By default the number of modulation points ensures to h... | # make sure tel and atm are separated to initialize the PWFS
tel-atm
# create the Pyramid Object
wfs = Pyramid(nSubap = param['nSubaperture'],\
telescope = tel,\
modulation = param['modulation'],\
lightRatio = param['lightThresh... | Telescope and Atmosphere separated!
Pyramid Mask initialization...
Done!
Selection of the valid pixels...
The valid pixel are selected on flux considerations
Done!
Acquisition of the reference slopes and units calibration...
WFS calibrated!
Done!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PYRAMID WFS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
The light can be propagated to the WFS through the different objects with using the ***** operator: | tel*wfs
plt.figure()
plt.imshow(wfs.cam.frame)
plt.colorbar()
| _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
We can display the PWFS signals that corresponds to a random actuation of the DM: | dm.coefs = (np.random.rand(dm.nValidAct)-0.5)*100e-9
tel*dm*wfs
plt.figure()
plt.imshow(wfs.pyramidSignal_2D)
plt.colorbar() | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Modal BasisIn this tutorial, we compute the mode-to-commands matrix (M2C) using the codes provided by C.Verinaud. It corresponds to a KL modal basis orthogonolized in the DM space. | # compute the modal basis
foldername_M2C = None # name of the folder to save the M2C matrix, if None a default name is used
filename_M2C = None # name of the filename, if None a default name is used
M2C_KL = compute_M2C(telescope = tel,\
atmosphere = atm,\
... | Creation of the directory /Disk3/cheritier/psim/data_calibration/ failed:
Directory already exists!
COMPUTING TEL*DM...
PREPARING IF_2D...
Computing Specific Modes ...
COMPUTING VON KARMAN 2D PSD...
COMPUTING COV MAT HHt...
TIME ELAPSED: 3 sec. COMPLETED: 100 %
SERIALIZING IFs...
SERIALIZING Specific Modes.... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Interaction MatrixThe interaction matrix can be computed using the M2C matrix and the function interactionMatrix.The output is stored as a class that contains all the informations about the inversion (SVD) such as eigenValues, reconstructor, etc. It is possible to add a **phaseOffset** to the interactionMatrix measure... | #%% to manually measure the interaction matrix
#
## amplitude of the modes in m
#stroke=1e-9
## Modal Interaction Matrix
#M2C = M2C[:,:param['nModes']]
#from AO_modules.calibration.InteractionMatrix import interactionMatrix
#
#calib = interactionMatrix(ngs = ngs,\
# atm ... | Creation of the directory /Disk3/cheritier/psim/data_calibration/ failed:
Directory already exists!
Loading the KL Modal Basis from: /Disk3/cheritier/psim/data_calibration/M2C_80_res
Computing the pseudo-inverse of the modal basis...
Diagonality criteria: 1.7785772854495008e-13 -- using the fast computation
Creation of... | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Display Modal Basis |
# project the mode on the DM
dm.coefs = ao_calib.M2C[:,:100]
tel*dm
#
# show the modes projected on the dm, cropped by the pupil and normalized by their maximum value
displayMap(tel.OPD,norma=True)
plt.title('Basis projected on the DM')
KL_dm = np.reshape(tel.OPD,[tel.resolution**2,tel.OPD.shape[2]])
covMat = (KL_d... | _____no_output_____ | MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Closed LoopHere is a code to do a closed-loop simulation using the PSIM code: |
# These are the calibration data used to close the loop
calib_CL = ao_calib.calib
M2C_CL = ao_calib.M2C
param['nLoop'] =100
plt.close('all')
# combine telescope with atmosphere
tel+atm
# initialize DM commands
dm.coefs=0
ngs*tel*dm*wfs
plt.ion()
# setup the display
fig = plt.figure(79)
ax1 ... | Telescope and Atmosphere combined!
| MIT | tutorials/tutorial_howToAdaptiveOptics.ipynb | joao-aveiro/OOPAO |
Contents* [1. Bernoulli Bandit](Part-1.-Bernoulli-Bandit) * [Bonus 1.1. Gittins index (5 points)](Bonus-1.1.-Gittins-index-%285-points%29.) * [HW 1.1. Nonstationary Bernoulli bandit](HW-1.1.-Nonstationary-Bernoulli-bandit)* [2. Contextual bandit](Part-2.-Contextual-bandit) * [2.1 Bulding a BNN agent](2.1-Buld... | class BernoulliBandit:
def __init__(self, n_actions=5):
self._probs = np.random.random(n_actions)
@property
def action_count(self):
return len(self._probs)
def pull(self, action):
if np.any(np.random.random() > self._probs[action]):
return 0.0
return 1.0
... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Epsilon-greedy agent**for** $t = 1,2,...$ **do** **for** $k = 1,...,K$ **do** $\hat\theta_k \leftarrow \alpha_k / (\alpha_k + \beta_k)$ **end for** $x_t \leftarrow argmax_{k}\hat\theta$ with probability $1 - \epsilon$ or random action with probab... | class EpsilonGreedyAgent(AbstractAgent):
def __init__(self, epsilon=0.01):
self._epsilon = epsilon
def get_action(self):
# YOUR CODE HERE
@property
def name(self):
return self.__class__.__name__ + "(epsilon={})".format(self._epsilon) | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
UCB AgentEpsilon-greedy strategy heve no preference for actions. It would be better to select among actions that are uncertain or have potential to be optimal. One can come up with idea of index for each action that represents otimality and uncertainty at the same time. One efficient way to do it is to use UCB1 algori... | class UCBAgent(AbstractAgent):
def get_action(self):
# YOUR CODE HERE | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Thompson samplingUCB1 algorithm does not take into account actual distribution of rewards. If we know the distribution - we can do much better by using Thompson sampling:**for** $t = 1,2,...$ **do** **for** $k = 1,...,K$ **do** Sample $\hat\theta_k \sim beta(\alpha_k, \b... | class ThompsonSamplingAgent(AbstractAgent):
def get_action(self):
# YOUR CODE HERE
def plot_regret(env, agents, n_steps=5000, n_trials=50):
scores = {
agent.name: [0.0 for step in range(n_steps)] for agent in agents
}
for trial in range(n_trials):
env.reset()
for a in ... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Bonus 1.1. Gittins index (5 points).Bernoulli bandit problem has an optimal solution - Gittins index algorithm. Implement finite horizon version of the algorithm and demonstrate it's performance with experiments. some articles:- Wikipedia article - https://en.wikipedia.org/wiki/Gittins_index- Different algorithms for ... | class DriftingBandit(BernoulliBandit):
def __init__(self, n_actions=5, gamma=0.01):
"""
Idea from https://github.com/iosband/ts_tutorial
"""
super().__init__(n_actions)
self._gamma = gamma
self._successes = None
self._failures = None
self._steps = 0
... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
And a picture how it's reward probabilities change over time | drifting_env = DriftingBandit(n_actions=5)
drifting_probs = []
for i in range(20000):
drifting_env.step()
drifting_probs.append(drifting_env._probs)
plt.figure(figsize=(17, 8))
plt.plot(pandas.DataFrame(drifting_probs).rolling(window=20).mean())
plt.xlabel("steps")
plt.ylabel("Success probability")
plt.title... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Your task is to invent an agent that will have better regret than stationary agents from above. | # YOUR AGENT HERE SECTION
drifting_agents = [
ThompsonSamplingAgent(),
EpsilonGreedyAgent(),
UCBAgent(),
YourAgent()
]
plot_regret(DriftingBandit(), drifting_agents, n_steps=20000, n_trials=10) | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Part 2. Contextual banditNow we will solve much more complex problem - reward will depend on bandit's state.**Real-word analogy:**> Contextual advertising. We have a lot of banners and a lot of different users. Users can have different features: age, gender, search requests. We want to show banner with highest click p... | all_states = np.load("all_states.npy")
action_rewards = np.load("action_rewards.npy")
state_size = all_states.shape[1]
n_actions = action_rewards.shape[1]
print("State size: %i, actions: %i" % (state_size, n_actions))
import theano
import theano.tensor as T
import lasagne
from lasagne import init
from lasagne.layers ... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
2.1 Bulding a BNN agentLet's implement epsilon-greedy BNN agent | class BNNAgent:
"""a bandit with bayesian neural net"""
def __init__(self, state_size, n_actions):
input_states = T.matrix("states")
target_actions = T.ivector("actions taken")
target_rewards = T.vector("rewards")
self.total_samples_seen = theano.shared(
np.int32(0)... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
2.2 Training the agent | N_ITERS = 100
def get_new_samples(states, action_rewards, batch_size=10):
"""samples random minibatch, emulating new users"""
batch_ix = np.random.randint(0, len(states), batch_size)
return states[batch_ix], action_rewards[batch_ix]
from IPython.display import clear_output
from pandas import DataFrame
movi... | iteration #90 mean reward=0.560 mse=0.457 kl=0.044
| Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
HW 2.1 Better explorationUse strategies from first part to gain more reward in contextual setting | class ThompsonBNNAgent(BNNAgent):
def get_action(self, states):
"""
picks action based by taking _one_ sample from BNN and taking action with highest sampled reward (yes, that simple)
This is exactly thompson sampling.
"""
# YOUR CODE HERE
thompson_agent_rewards = train_cont... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Part 3. Exploration in MDPThe following problem, called "river swim", illustrates importance of exploration in context of mdp's. Picture from https://arxiv.org/abs/1306.0940 Rewards and transition probabilities are unknown to an agent. Optimal policy is to swim against current, while easiest way to gain reward is to g... | class RiverSwimEnv:
LEFT_REWARD = 5.0 / 1000
RIGHT_REWARD = 1.0
def __init__(self, intermediate_states_count=4, max_steps=16):
self._max_steps = max_steps
self._current_state = None
self._steps = None
self._interm_states = intermediate_states_count
self.reset()
... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Let's implement q-learning agent with epsilon-greedy exploration strategy and see how it performs. | class QLearningAgent:
def __init__(self, n_states, n_actions, lr=0.2, gamma=0.95, epsilon=0.1):
self._gamma = gamma
self._epsilon = epsilon
self._q_matrix = np.zeros((n_states, n_actions))
self._lr = lr
def get_action(self, state):
if np.random.random() < self._epsilon:
... | /usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:6: FutureWarning: pd.ewm_mean is deprecated for ndarrays and will be removed in a future version
| Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Let's visualize our policy: | def plot_policy(agent):
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(111)
ax.matshow(agent.get_q_matrix().T)
ax.set_yticklabels(['', 'left', 'right'])
plt.xlabel("State")
plt.ylabel("Action")
plt.title("Values of state-action pairs")
plt.show()
plot_policy(agent) | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
As your see, agent uses suboptimal policy of going left and does not explore the right state. Bonus 3.1 Posterior sampling RL (3 points) Now we will implement Thompson Sampling for MDP!General algorithm:>**for** episode $k = 1,2,...$ **do**>> sample $M_k \sim f(\bullet\ |\ H_k)$>> compute policy $\mu_k$ for $M_k$>> **... | def sample_normal_gamma(mu, lmbd, alpha, beta):
""" https://en.wikipedia.org/wiki/Normal-gamma_distribution
"""
tau = np.random.gamma(alpha, beta)
mu = np.random.normal(mu, 1.0 / np.sqrt(lmbd * tau))
return mu, tau
class PsrlAgent:
def __init__(self, n_states, n_actions, horizon=10):
s... | _____no_output_____ | Unlicense | week05_explore/week5.ipynb | kianya/Practical_RL |
Agenda 1. [Review](0)2. [Numpy Intro and Installation](2)2. [Exercise](10) 3. [Exercise](12) Review ExerciseThe following list represents the diameters of circles:circle_diameters = [1,2,3,5,8,13,21]1 - Calculate the area of each circle2 - Calculate the circumference of each circleUse Numpy for the solution ... | import numpy as np
circle_diameters = [1,2,3,5,8,13,21]
area = [round(np.pi*(x/2)**2,2) for x in circle_diameters]
circ = [round(np.pi*x) for x in circle_diameters]
print(circ)
print(area) | _____no_output_____ | BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
ExerciseFor each tuple in the list print the area of each rectangleEach element in the list represents the length and the widthdimensions = [(20,2),(2,3),(4,4),(6,6)]Solve as a non numpy problem Solution | dimensions = [(20,2),(2,3),(4,4),(6,6)]
areas = [i*x for i,x in dimensions]
print(areas) | [40, 6, 16, 36]
| BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
ExerciseThe following dictionary represents the dimensions of an apartment in New York City. apartment = {'Bedroom 1':(12,12), 'Bedroom 2': (12,10), 'Bathroom 1': (6,8), 'Bathroom 2': (6,8), 'Kitchen': (10,8), 'Foyer': (14,4), 'Dining Room': (12,10), 'Living Room': (12,15)}1 - Calculate the square footage of eac... | apartment = {'Bedroom 1':(12,12), 'Bedroom 2': (12,10), 'Bathroom 1': (6,8), 'Bathroom 2': (6,8), 'Kitchen': (10,8), 'Foyer': (14,4), 'Dining Room': (12,10), 'Living Room': (12,15)}
areas = [(v[0]*v[1]) for i,v in apartment.items()]
print(areas)
print(sum(areas))
print('$',sum(areas)*90) | [144, 120, 48, 48, 80, 56, 120, 180]
796
$ 71640
| BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
Exercise5 friends go out to dinner and their individual amounts were tallied on 1 billdinner = [36, 42, 27, 32, 39]Using numpy calculate the following:1 - The average meal price2 - The median meal price3 - The maximum cost for the meal4 - The least expensive meal5 - The difference each person varied from the mean6 - Ad... | import numpy as np
dinner = [36, 42, 27, 32, 39]
avg = np.mean(dinner)
median = np.median(dinner)
m = np.max(dinner)
mi = np.min(dinner)
diff_mean = [round(x-avg,2) for x in dinner]
print('avg:', avg, 'median:', median, 'max:', m, 'min:', mi)
print(diff_mean)
adjusted_dinner = [round((x*1.2)*1.0875,2) for x in dinner]... | avg: 35.2 median: 36.0 max: 42 min: 27
[0.8, 6.8, -8.2, -3.2, 3.8]
[46.98, 54.81, 35.23, 41.76, 50.89]
[20.46, 23.86, 15.34, 18.18, 22.16] 100.0
[60.6825 48.9325 55.4625 64.5925]
| BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
Numpy continued Strings can also be stored in a numpy array.import numpy as nppasta_shapes = ['Macaroni','Rigatoni','Angel Hair','Spaghetti','Linguini']shapes = np.array(pasta_shapes)shapes = np.sort(shapes)print(shapes)print(shapes.dtype) | import numpy as np
pasta_shapes = ['Macaroni','Rigatoni','Angel Hair','Spaghetti','Linguini']
val= 5
val = np.array(val)
name= 'str'
name = np.array(name)
boo = True
boo = np.array(boo)
shapes = np.array(pasta_shapes)
print(np.sort(shapes))
print(type(shapes)) | ['Angel Hair' 'Linguini' 'Macaroni' 'Rigatoni' 'Spaghetti']
<U10
<class 'numpy.ndarray'>
| BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
We can use short cut abreviations to assign the data types to numpyarrays:For i, u, f, S and U we can define size as well. We can combine each letter with a size as well like: 4,8import numpy as nparr = np.array(list(range(1,11)), dtype='i8')print(arr, arr.dtype) | import numpy as np
np.array(list(range(1,11)), dtype='i8') | _____no_output_____ | BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
CastingWe can convert python data type into numpy data type using 2 methodsMethod 1Use dtype parameterarr_string = np.array(list(range(1,11)), dtype='S')print(arr_string)Method 2Use astype()import numpy as nparr = np.array(list(range(1,11)), dtype='i8')arr_2 = arr.astype('S')print(arr_2) | arr_string = np.array(list(range(1,11)))
print(arr_string)
import numpy as np
arr = np.array(list(range(1,11)), dtype='i8')
arr_2 = arr.astype('S')
print(arr_2)
| [ 1 2 3 4 5 6 7 8 9 10]
[b'1' b'2' b'3' b'4' b'5' b'6' b'7' b'8' b'9' b'10']
| BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
ExerciseTake the following floating point number and cast them as integersUse both methods.rainfall = [2.3,3.7,2.4,1.9] Solution |
import numpy as np
rainfall = np.array([2.3,3.7,2.4,1.9])
r2 = rainfall.astype(int)
print(r2)
import numpy as np
| _____no_output_____ | BSD-Source-Code | CI_Data_Science_Lesson_06_ANSWERS.ipynb | MaxDGU/datasciencenotebooks |
Repairing Code AutomaticallySo far, we have discussed how to track failures and how to locate defects in code. Let us now discuss how to _repair_ defects – that is, to correct the code such that the failure no longer occurs. We will discuss how to _repair code automatically_ – by systematically searching through possi... | from bookutils import YouTubeVideo
YouTubeVideo("UJTf7cW0idI") | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
**Prerequisites*** Re-read the [introduction to debugging](Intro_Debugging.ipynb), notably on how to properly fix code.* We make use of automatic fault localization, as discussed in the [chapter on statistical debugging](StatisticalDebugger.ipynb).* We make extensive use of code transformations, as discussed in the [ch... | import bookutils | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
SynopsisTo [use the code provided in this chapter](Importing.ipynb), write```python>>> from debuggingbook.Repairer import ```and then make use of the following features.This chapter provides tools and techniques for automated repair of program code. The `Repairer()` class takes a `RankingDebugger` debugger as input (s... | from StatisticalDebugger import middle
# ignore
from bookutils import print_content
# ignore
import inspect
# ignore
_, first_lineno = inspect.getsourcelines(middle)
middle_source = inspect.getsource(middle)
print_content(middle_source, '.py', start_line_number=first_lineno) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
In most cases, `middle()` just runs fine: | middle(4, 5, 6) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
In some other cases, though, it does not work correctly: | middle(2, 1, 3) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Validated Repairs Now, if we only want a repair that fixes this one given failure, this would be very easy. All we have to do is to replace the entire body by a single statement: | def middle_sort_of_fixed(x, y, z): # type: ignore
return x | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
You will concur that the failure no longer occurs: | middle_sort_of_fixed(2, 1, 3) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
But this, of course, is not the aim of automatic fixes, nor of fixes in general: We want our fixes not only to make the given failure go away, but we also want the resulting code to be _correct_ (which, of course, is a lot harder). Automatic repair techniques therefore assume the existence of a _test suite_ that can ch... | from StatisticalDebugger import MIDDLE_PASSING_TESTCASES, MIDDLE_FAILING_TESTCASES | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
The `middle_test()` function fails whenever `middle()` returns an incorrect result: | def middle_test(x: int, y: int, z: int) -> None:
m = middle(x, y, z)
assert m == sorted([x, y, z])[1]
from ExpectError import ExpectError
with ExpectError():
middle_test(2, 1, 3) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Locating the Defect Our next step is to find potential defect locations – that is, those locations in the code our mutations should focus upon. Since we already do have two test suites, we can make use of [statistical debugging](StatisticalDebugger.ipynb) to identify likely faulty locations. Our `OchiaiDebugger` rank... | from StatisticalDebugger import OchiaiDebugger, RankingDebugger
middle_debugger = OchiaiDebugger()
for x, y, z in MIDDLE_PASSING_TESTCASES + MIDDLE_FAILING_TESTCASES:
with middle_debugger:
middle_test(x, y, z) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
We see that the upper half of the `middle()` code is definitely more suspicious: | middle_debugger | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
The most suspicious line is: | # ignore
location = middle_debugger.rank()[0]
(func_name, lineno) = location
lines, first_lineno = inspect.getsourcelines(middle)
print(lineno, end="")
print_content(lines[lineno - first_lineno], '.py') | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
with a suspiciousness of: | # ignore
middle_debugger.suspiciousness(location) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Random Code Mutations Our third step in automatic code repair is to _randomly mutate the code_. Specifically, we want to randomly _delete_, _insert_, and _replace_ statements in the program to be repaired. However, simply synthesizing code _from scratch_ is unlikely to yield anything meaningful – the number of combina... | import string
string.ascii_letters
len(string.ascii_letters + '_') * \
len(string.ascii_letters + '_' + string.digits) * \
len(string.ascii_letters + '_' + string.digits) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Hence, we do _not_ synthesize code from scratch, but instead _reuse_ elements from the program to be fixed, hypothesizing that "a program that contains an error in one area likely implements the correct behavior elsewhere" \cite{LeGoues2012}. This insight has been dubbed the *plastic surgery hypothesis*: content of new... | import ast
import astor
import inspect
from bookutils import print_content, show_ast
def middle_tree() -> ast.AST:
return ast.parse(inspect.getsource(middle))
show_ast(middle_tree()) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
You see that it consists of one function definition (`FunctionDef`) with three `arguments` and two statements – one `If` and one `Return`. Each `If` subtree has three branches – one for the condition (`test`), one for the body to be executed if the condition is true (`body`), and one for the `else` case (`orelse`). Th... | print(ast.dump(middle_tree())) | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
This is the path to the first `return` statement: | ast.dump(middle_tree().body[0].body[0].body[0].body[0]) # type: ignore | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Picking Statements For our mutation operators, we want to use statements from the program itself. Hence, we need a means to find those very statements. The `StatementVisitor` class iterates through an AST, adding all statements it finds in function definitions to its `statements` list. To do so, it subclasses the Pyth... | from ast import NodeVisitor
# ignore
from typing import Any, Callable, Optional, Type, Tuple
from typing import Dict, Union, Set, List, cast
class StatementVisitor(NodeVisitor):
"""Visit all statements within function defs in an AST"""
def __init__(self) -> None:
self.statements: List[Tuple[ast.AST, st... | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
The function `all_statements()` returns all statements in the given AST `tree`. If an `ast` class `tp` is given, it only returns instances of that class. | def all_statements_and_functions(tree: ast.AST,
tp: Optional[Type] = None) -> \
List[Tuple[ast.AST, str]]:
"""
Return a list of pairs (`statement`, `function`) for all statements in `tree`.
If `tp` is given, return only statements of that cl... | _____no_output_____ | MIT | notebooks/Repairer.ipynb | HGUISEL/debuggingbook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.