I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Agora, vamos passar por cada nome de personagem e time. Primeiramente, vamos definir um DataFrame, e faremos um filtro nos nomes das comics que possuem o nome deste personagem ou time. Depois, vamos extrair algumas informações daí. A quantidade de comics será basicamente o número de linhas do DataFrame, obtido através da função len(). Depois, as médias de avaliação, preço e quantidade de páginas. Cada uma destas informações será salva em um dictionary, que será adicionado a uma lista. No fim, teremos uma lista de dicts para os personagens e uma lista de dicts para os times:
Can you write Python code for it?

character_row = {}
characters_dicts = []

for character in main_dc_characters:
    character_df = comixology_df[(comixology_df['Name'].str.contains(character)) &
                                 (comixology_df['Publisher'] == 'DC Comics')]
    character_row['Character_Name'] = character
    character_row['Quantity_of_comics'] = len(character_df)
    character_row['Average_Rating'] = np.nanmean(character_df['Rating'])
    character_row['Average_Price'] = np.nanmean(character_df['Original_price'])
    character_row['Average_Pages'] = np.nanmean(character_df['Page Count'])
    character_row['Publisher'] = "DC Comics"
    characters_dicts.append(character_row)
    character_row = {}

for character in main_marvel_characters:
    character_df = comixology_df[(comixology_df['Name'].str.contains(character)) &
                                 (comixology_df['Publisher'] == 'Marvel')]
    character_row['Character_Name'] = character
    character_row['Quantity_of_comics'] = len(character_df)
    character_row['Average_Rating'] = np.nanmean(character_df['Rating'])
    character_row['Average_Price'] = np.nanmean(character_df['Original_price'])
    character_row['Average_Pages'] = np.nanmean(character_df['Page Count'])
    character_row['Publisher'] = "Marvel"
    characters_dicts.append(character_row)
    character_row = {}

characters_df = pd.DataFrame(characters_dicts)

team_row = {}
teams_dicts = []

for team in dc_teams:
    team_df = comixology_df[(comixology_df['Name'].str.contains(team)) &
                                 (comixology_df['Publisher'] == 'DC Comics')]
    team_row['Team_Name'] = team
    team_row['Quantity_of_comics'] = len(team_df)
    team_row['Average_Rating'] = np.nanmean(team_df['Rating'])
    team_row['Average_Price'] = np.nanmean(team_df['Original_price'])
    team_row['Average_Pages'] = np.nanmean(team_df['Page Count'])
    team_row['Publisher'] = "DC Comics"
    teams_dicts.append(team_row)
    team_row = {}

for team in marvel_teams:
    team_df =...


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Análise de Comics Digitais (Python) - Marvel ou DC?
Introdução
Depois de ter feito a análise do site (post aqui) e de ter feito um scraping dos dados do site da Comixology (post aqui), agora vamos fazer uma bela análise de dados das informações de comics digitais com Python (Pandas).
Vamos descobrir quais editoras tem os melhores preços relativos à quantidade de páginas de seus comics, as editoras com as melhores avaliações médias, além de uma análise mais profunda do duelo das gigantes: Marvel x DC Comics. Vamos começar.
Preparação Inicial
Primeiro, como de costume, vamos importar os pacotes que iremos utilizar. O pacote warnings, serve somente para desligar possíveis avisos relativos à este código no notebook, para que o código não fique extenso. Os outros pacotes já são velhos conhecidos: numpy, pandas, matplotlib e seaborn.
Can you write Python code for it?

import warnings
warnings.filterwarnings('ignore')

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

comixology_df = pd.read_csv("comixology_comics_dataset_19.04.2016.csv", encoding = "ISO-8859-1")


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Apenas como curiosidade, vamos verificar o número de avaliações dadas em comics de cada uma, através de mais uma pivot table:
Can you write Python code for it?

# Somar a quantidade de avaliações em comics de cada editora
marvel_dc_pivot_sums = pd.pivot_table(marvel_dc_comics,
                               values=['Ratings_Quantity'],
                               index=['Publisher'],
                               aggfunc=[np.sum])
print(marvel_dc_pivot_sums)


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Aqui temos uma surpresa na liderança. Mesmo com a quantidade de comics não sendo tão grande, acho difícil que alguém previsse que a Mystique seria o personagem com a avaliação média mais alta no meio destes personagens todos, tão mais populares. Nas primeiras posições, outros resultados surpreendentes, com Booster Gold em segundo, Jonah Hex em terceiro, Blue Beetle em quinto. Dos super populares que vimos na lista de cima, temos o Spider-Man, Deadpool e Wonder Woman, já no fim da lista do top 20.
Can you write Python code for it?


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Entre os times com mais comics, nada de muito surpreendente também. Os eternos X-Men em primeiro, Avengers em segundo e Justice League em terceiro. Depois, seguem os outros times menos populares.
Can you write Python code for it?


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Interessante notar que mesmo a Marvel tendo uma quantidade maior de comics, como vimos na tabela anterior, a quantidade de avaliações em comics da DC é bem maior, cerca de 55% a mais. Parece que os fãs dos comics da DC são mais propensos a avaliar os comics na Comixology que os da Marvel.
Nossa próxima avaliação será a de personagens e equipes de heróis / vilões. Primeiramente, vamos criar listas com personagens de cada uma, e igualmente para times. Dividi os personagens entre as Publishers e criei as listas na mão. Deu um trabalhinho, mas nada demais.
Can you write Python code for it?

main_dc_characters = ['Superman','Batman','Aquaman','Wonder Woman', 'Flash',
                      'Robin','Arrow', 'Batgirl', 'Bane', 'Harley Queen',
                      'Poison Ivy', 'Joker','Firestorm','Vixen',
                      'Martian Manhunter','Zod','Penguin','Lex Luthor',
                      'Green Lantern','Supergirl','Atom','Cyborg','Hawkgirl',
                      'Starfire','Jonah Hex','Booster Gold','Black Canary',
                      'Shazam','Catwoman','Nightwing','Zatanna','Hawkman',
                      'Power Girl','Rorschach','Doctor Manhattan',
                      'Blue Beetle','Batwoman','Darkseid','Vandal Savage',
                      "Ra's Al Ghul",'Riddler','Reverse Flash','Black Adam',
                      'Deathstroke','Brainiac','Sinestro','Two-Face']

main_marvel_characters = ['Spider-Man','Captain Marvel','Hulk','Thor',
                          'Iron Man','Luke Cage','Black Widow','Daredevil',
                          'Captain America','Jessica Jones','Ghost Rider',
                          'Spider-Woman','Silver Surfer','Beast','Thing',
                          'Kitty Pride','Doctor Strange','Black Panther',
                          'Invisible Woman','Nick Fury','Storm','Professor X',
                          'Cyclops','Jean Grey','Wolverine','Scarlet Witch',
                          'Gambit','Rogue','X-23','Iceman','She-Hulk',
                          'Iron Fist','Hawkeye','Quicksilver','Vision',
                          'Ant-Man','Cable','Bishop','Colossus','Deadpool',
                          'Human Torch','Mr. Fantastic','Nightcrawler','Nova',
                          'Psylocke','Punisher','Rocket Raccoon','Groot',
                          'Star-Lord','War Machine','Gamora','Drax','Venom',
                          'Carnage','Octopus','Green Goblin','Abomination',
                          'Enchantress','Sentinel','Viper','Lady Deathstrike',
                          'Annihilus','Ultron','Galactus','Kang','Bullseye',
     ...


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Na próxima análise, usaremos apenas comics com mais de 5 avaliações. Para isso, vamos filtrar:
Can you write Python code for it?

# Para a próxima análise, usaremos somente comics com mais de 5 ratings
comics_more_than_5_ratings = comixology_df[comixology_df.Ratings_Quantity > 5]


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Novamente, aqui, a DC Comics se mostra um pouquinho melhor. Tem uma maior proporção de comics bons e uma menor proporção de comics ruins. Ponto para a DC de novo. Abaixo, o gráfico fazendo as comparações:
Can you write Python code for it?

plt.figure(2,figsize=(10, 6))

plt.subplot(221) # Total de Comics de cada editora
y_axis = [dc_total, marvel_total]
x_axis = np.arange(len(y_axis))
plt.bar(x_axis, y_axis)
plt.xticks(x_axis+0.4, ('DC Comics','Marvel'))
plt.title('Comics Totais')
plt.tight_layout()

plt.subplot(222) # Proporção de Comics com avaliação 4 ou 5
y_axis = [dc_proportion_4_or_5 * 100, marvel_proportion_4_or_5 * 100]
x_axis = np.arange(len(y_axis))
plt.bar(x_axis, y_axis)
plt.xticks(x_axis+0.4, ('DC Comics','Marvel'))
plt.title('Proporção de Comics com avaliação 4 ou 5')
plt.tight_layout()

plt.subplot(223) # Proporção de Comics com avaliação 1 ou 2
y_axis = [dc_proportion_1_or_2 * 100, marvel_proportion_1_or_2 * 100]
x_axis = np.arange(len(y_axis))
plt.bar(x_axis, y_axis)
plt.xticks(x_axis+0.4, ('DC Comics','Marvel'))
plt.title('Proporção de Comics com avaliação 1 ou 2')
plt.tight_layout()

plt.show()


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
O próximo passo é ver alguns números relativos a quantidade de comics de cada uma. Quantos comics cada uma possui, qual o número de comics bons (avaliação 4 ou 5) e ruins (avaliação 1 ou 2) e sua proporção perante o número total de comics. Para fazer esta análise, vamos meramente fazer alguns filtros e verificar o comprimento do DataFrame após estes filtros. Simples:
Can you write Python code for it?

# Vamos agora verificar a quantidade de comics de cada uma e fazer uma proporção
# com a quantidade de comics de cada uma com rating maior ou igual a 4. Desta
# forma podemos ver qual delas, proporcionalmente, lança bons comics
marvel_total = len(marvel_dc_comics[marvel_dc_comics['Publisher'] == 'Marvel'])
marvel_4_or_5 = len(marvel_dc_comics[(marvel_dc_comics['Publisher'] == 'Marvel')
                                     & (marvel_dc_comics['Rating'] >= 4)])
marvel_proportion_4_or_5 = marvel_4_or_5 / marvel_total
marvel_1_or_2 = len(marvel_dc_comics[(marvel_dc_comics['Publisher'] == 'Marvel')
                                     & (marvel_dc_comics['Rating'] <= 2)])
marvel_proportion_1_or_2 = marvel_1_or_2 / marvel_total

dc_total = len(marvel_dc_comics[marvel_dc_comics['Publisher'] == 'DC Comics'])
dc_4_or_5 = len(marvel_dc_comics[(marvel_dc_comics['Publisher'] == 'DC Comics')
                                 & (marvel_dc_comics['Rating'] >= 4)])
dc_proportion_4_or_5 = dc_4_or_5 / dc_total
dc_1_or_2 = len(marvel_dc_comics[(marvel_dc_comics['Publisher'] == 'DC Comics')
                                 & (marvel_dc_comics['Rating'] <= 2)])
dc_proportion_1_or_2 = dc_1_or_2 / dc_total

print("\n")
print("Total de Comics Marvel: " + str(marvel_total))
print("Total de Comics Marvel com avaliação maior ou igual a 4: " +
      str(marvel_4_or_5))
print("Proporção de Comics Marvel com avaliação maior ou igual a 4: " +
      str("{0:.2f}%".format(marvel_proportion_4_or_5 * 100)))
print("Total de Comics Marvel com avaliação menor ou igual a 2: " +
      str(marvel_1_or_2))
print("Proporção de Comics Marvel com avaliação menor ou igual a 2: " +
      str("{0:.2f}%".format(marvel_proportion_1_or_2 * 100)))
print("\n")
print("Total de Comics DC Comics: " + str(dc_total))
print("Total de Comics DC Comics com avaliação maior ou igual a 4: " +
      str(dc_4_or_5))
print("Proporção de Comics DC Comics com avaliação maior ou igual a 4: " +
      str("{0:.2f}%".format(dc_proportion_4_or_5 * 100)))
print("Total de...


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Os números mostram que o crescimento era moderado, até que na década de 2000 ocorreu um boom, com um crescimento bastante considerável até 2012, quando a quantidade de lançamentos começou a oscilar. A queda mostrada no ano de 2016 ocorre, obviamente, pois ainda estamos na metade do mesmo.
Agora, para fazer uma avaliação dos comics mais baixados no site (não dá para aferir os mais comprados, visto que alguns dos comics são gratuitos). Para esta análise, vamos ver quais são os 30 comics com mais avaliações.
Can you write Python code for it?

# Vejamos agora as 30 comics com mais avaliações; se for mantida a proporção,
# pode-se dizer que estas são as comics mais baixadas (e não vendidas, pois
# algumas destas são gratuitas)
comics_by_ratings_quantity = comixology_df[['Name','Publisher',
                                            'Ratings_Quantity']].sort_values(
                                            by='Ratings_Quantity',
                                            ascending=False)
print(comics_by_ratings_quantity.head(30))

y_axis = comics_by_ratings_quantity.head(30)['Ratings_Quantity']
x_axis = np.arange(len(y_axis))

plt.figure(figsize=(10, 6))
plt.bar(x_axis, y_axis)
plt.xticks(x_axis+0.5, tuple(comics_by_ratings_quantity.head(30)['Name']),
           rotation=90)
plt.show()


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Para as análises (e avante)
A primeira análise que faremos será o cálculo dos valores médios do site em geral, como preço médio dos comics, quantidade média de páginas, entre outros. Usaremos a função nanmean() do numpy, que calcula a média excluindo os NaN, que é quando não possuímos a informação.
Can you write Python code for it?

# Algumas informações médias do site
average_price = np.nanmean(comixology_df['Original_price'])
average_page_count = np.nanmean(comixology_df['Page Count'])
average_rating = np.nanmean(comixology_df['Rating'])
average_rating_quantity = np.nanmean(comixology_df['Ratings_Quantity'])
average_price_per_page = np.nanmean(comixology_df['Price_per_page'])

print("Preço médio: " + str(average_price))
print("Quantidade média de páginas: " + str(average_page_count))
print("Avaliação média: " + str(average_rating))
print("Quantidade média de avaliações por comic: " +
      str(average_rating_quantity))
print("Preço por página médio por comic: " + str(average_price_per_page))


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Vamos agora usar a função iterrows() do Dataframe para extrair o ano de publicação da versão impressa do comic. Esta função cria uma espécie de forloop, que itera sobre cada linha do DataFrame. Vamos usar o split para dividir a string que contém a data de publicação em uma lista. O terceiro valor será o ano. Em alguns casos, o ano retorna um valor maior que 2016. Como isto é impossível, estes valores também serão definidos como NaN:
Can you write Python code for it?

# Vamos extrair o ano da string de data de publicação da versão impressa
print_dates = []
for index, row in comixology_df.iterrows():
    if type(comixology_df.ix[index]['Print Release Date']) == float:
        row_year = np.nan
    else:
        row_year = int(comixology_df.ix[index]['Print Release Date'].split()[2])
        if row_year > 2016:
            row_year = np.nan
    print_dates.append(row_year)

comixology_df['Print_Release_Year'] = pd.Series(print_dates,
                                                index=comixology_df.index)


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Vamos considerar apenas times e personagens que possuam mais de 20 comics onde seu nome está no título do comic.
Can you write Python code for it?

teams_df = teams_df[teams_df['Quantity_of_comics'] > 20]
characters_df = characters_df[characters_df['Quantity_of_comics'] > 20]


I am working on the file "Comixology Analysis Notebook - Português.ipynb".
The first task is:
Walking Dead liderando com (muuuita) folga. Depois, algumas comics de Marvel e DC e mais alguns comics variados.
Agora, vamos fazer uma análise mais profunda dos comics das gigantes: Marvel e DC Comics.
Primeiro, vamos filtrar o DataFrame para que sobrem apenas comics destas duas. Depois, vamos calcular através da função pivot table alguns valores médios das duas:
Can you write Python code for it?

# Vamos agora ver dados somente das duas maiores: Marvel e DC
marvel_dc_comics = comixology_df[(comixology_df.Publisher == 'Marvel') |
                                 (comixology_df.Publisher == 'DC Comics')]

# Primeiro, alguns valores médios de cada uma
marvel_dc_pivot_averages = pd.pivot_table(marvel_dc_comics,
                               values=['Rating','Original_price','Page Count',
                                       'Price_per_page'],
                               index=['Publisher'],
                               aggfunc=[np.mean])
print(marvel_dc_pivot_averages)


I am working on the file "Communication between components - redis.ipynb".
The first task is:
The simplest thing we can do with the Redis server is to set and get key values.  The keys are strings and the values are strings, so you can do whatever you want here.  Here's a quick example of using it to have two different Nengo models talk to each other.  If you start both of these models running, the value in the first one is sent to the second one.
Can you write Python code for it?

import nengo
import numpy as np

r = redis.StrictRedis(host='localhost')
model1 = nengo.Network()
with model1:
    stim = nengo.Node(np.sin)
    a = nengo.Ensemble(100, 1)
    output = nengo.Node(lambda t, x: r.set('decoded_value', x[0]), size_in=1)
    nengo.Connection(stim, a)
    nengo.Connection(a, output)

import nengo_gui.ipython
nengo_gui.ipython.IPythonViz(model1, 'model1.cfg')

import nengo
import numpy as np

r2 = redis.StrictRedis(host='localhost')

model2 = nengo.Network()
with model2:
    reader = nengo.Node(lambda t: float(r2.get('decoded_value')))
    a = nengo.Ensemble(100, 1)
    nengo.Connection(reader, a)

import nengo_gui.ipython
nengo_gui.ipython.IPythonViz(model2, 'model2.cfg')


I am working on the file "Community_identity.ipynb".
The first task is:
Import Game Modules From a Given Path
User have to edit the path and put the correct one on his/her machine.
Can you write Python code for it?

import sys
# search path for modules
sys.path.append('/Users/hn/Documents/GitHub/PyOpinionGame/')

import opiniongame.config as og_cfg
import opiniongame.IO as og_io
import opiniongame.coupling as og_coupling
import opiniongame.state as og_state
import opiniongame.adjacency as og_adj
import opiniongame.selection as og_select
import opiniongame.potentials as og_pot
import opiniongame.core as og_core
import opiniongame.stopping as og_stop
import opiniongame.opinions as og_opinions


I am working on the file "Community_identity.ipynb".
The first task is:
Initiate State
Can you write Python code for it?

# These are the default matrices for the state of the system:
# If you want to change them, you can generate a new one in the following cell
default_weights = og_coupling.weights_no_coupling(config.popSize, config.ntopics)
default_initialOpinions = og_opinions.initialize_opinions(config.popSize, config.ntopics)
default_adj = og_adj.make_adj(config.popSize, 'full')

state = og_state.WorldState(adj=default_adj,
                            couplingWeights=default_weights,
                            initialOpinions=default_initialOpinions,
                            initialHistorySize=100,
                            historyGrowthScale=2)
state.validate()

#
# run
#
numberOfCommunities = 3
communityPopSize    = 25
config.popSize = numberOfCommunities * communityPopSize

# List of upper bound probability of interaction between communities
uppBound_list = np.array([.001, 0.004, 0.007, 0.01, 0.013, 0.016, 0.019])
#
# List of uniqueness Strength parameter
#
individStrength = np.arange(0.00001, 0.000251, 0.00006)
individStrength = np.append(0, individStrength)
individStrength = np.array([0.0])
skewstrength = 2.0

tau = 0.62
config.iterationMax = 30000
config.printOut()

#
# functions for use by the simulation engine
#
ufuncs = og_cfg.UserFunctions(og_select.PickTwoWeighted,
                              og_stop.iterationStop,
                              og_pot.createTent(tau))

noInitials = np.arange(1) # Number of different initial opinions.
noGames = np.arange(1)    # Number of different game orders.
# Run experiments with different adjacencies, different initials, and different order of games.
for uniqForce in individStrength:
    config.uniqstrength = uniqForce
    for upperBound in uppBound_list:
        """
        Generate different adjacency matrix with different prob. of interaction
        between different communities
        """
        state.adj = og_adj.CommunitiesMatrix(communityPopSize, numberOfCommunities, upperBound)
        print"(upperBound, uniqForce) = (",...


I am working on the file "Community_identity.ipynb".
The first task is:
Plot the experiment done above:
Can you write Python code for it?

time, population_size, no_of_topics = evolution = all_experiments_history['experiment1'].shape
evolution = all_experiments_history['experiment1'].reshape(time, population_size)

fig = plt.figure()
plt.plot(evolution)
plt.xlabel('Time')
plt.ylabel('Opinionds')
plt.title('Evolution of Opinions')
fig.set_size_inches(10,5)
plt.show()


I am working on the file "Community_identity.ipynb".
The first task is:
Setting Up Game Parameters
Can you write Python code for it?

config = og_cfg.staticParameters()

path = '/Users/hn/Documents/GitHub/PyOpinionGame/'  # path to the 'staticParameters.cfg'
staticParameters = path + 'staticParameters.cfg'

config.readFromFile(staticParameters) # Read static parameters
config.threshold = 0.0001
config.Kthreshold = 0.00001
config.startingseed = 10
config.learning_rate = 0.1
tau = 0.62 #tip of the tent potential function
config.printOut()


I am working on the file "Community_identity.ipynb".
The first task is:
Skew Uniqueness Tendency Driver:
I observed when having tendency for uniqueness is drawn from normal distribution, we do not get an interesting result. For example, initial intuition was that uniqueness for tendency would delay stabilization of the network, however, it did not. So, here we draw uniqueness tendencies from skew normal distribution.
When most neighbors tend to go in one directions, then probability of individuals to go to the opposite direction would be more than the niose in the same direction:
Can you write Python code for it?

state = og_state.WorldState(adj=default_adj,
                            couplingWeights=default_weights,
                            initialOpinions=default_initialOpinions,
                            initialHistorySize=100,
                            historyGrowthScale=2)
state.validate()

#
# load configuration
#
config = og_cfg.staticParameters()
config.readFromFile('staticParameters.cfg')
config.threshold = 0.01
config.printOut()

#
# seed PRNG: must do this before any random numbers are
# ever sampled during default generation
#
print(("SEEDING PRNG: "+str(config.startingseed)))
np.random.seed(config.startingseed)


I am working on the file "Community_identity.ipynb".
The first task is:
User Defined States and parameters Can go in the following cell:
Can you write Python code for it?

numberOfCommunities = 3
communityPopSize    = 25
config.popSize = numberOfCommunities * communityPopSize

# List of upper bound probability of interaction between communities
uppBound_list = [0.0]

# List of uniqueness Strength parameter
individStrength = [0.0]

config.learning_rate = 0.1
config.iterationMax = 10000
tau = 0.62
config.printOut()
#
# functions for use by the simulation engine
#
ufuncs = og_cfg.UserFunctions(og_select.PickTwoWeighted,
                              og_stop.iterationStop,
                              og_pot.createTent(tau))

# Number of different initial opinions,
# i.e. number of different games with different initials.
noInitials = np.arange(1)
noGames = np.arange(1)    # Number of different game orders.

# Run experiments with different adjacencies, different initials, and different order of games.
for uniqForce in individStrength:
    config.uniqstrength = uniqForce
    for upperBound in uppBound_list:
        # Generate different adjacency matrix with different prob. of interaction
        # between different communities
        state.adj = og_adj.CommunitiesMatrix(communityPopSize, numberOfCommunities, upperBound)

        for countInitials in noInitials:
            # Pick three communities with similar opinions to begin with!
            state.initialOpinions = np.zeros((config.popSize, 1))
            state.initialOpinions[0:25]  = np.random.uniform(low=0.0, high=.25, size=(25,1))
            state.initialOpinions[25:50] = np.random.uniform(low=0.41, high=.58, size=(25,1))
            state.initialOpinions[50:75] = np.random.uniform(low=0.74, high= 1, size=(25,1))

            state.couplingWeights = og_coupling.weights_no_coupling(config.popSize, config.ntopics)
            all_experiments_history = {}
            print "(uniqForce, upperBound)  = ({}, {})".format(uniqForce, upperBound)
            print "countInitials = {}".format(countInitials + 1)

            for gameOrders in noGames:
               ...


I am working on the file "CompanionPSF.ipynb".
The first task is:
First, we turn to GAIA. While the current DR2 does not explicitly mark catalog entries as multiple systems or extended sources, we can just look at the error in RA and dec. For stars as bright as the ones we've chosen, those errors are typically i nthe range 0.05 milliarcsec. Anything larger than that indicates that the source is not a good point source, so we want to reject it.
Can you write Python code for it?

radius = u.Quantity(1.0, u.arcsec)
gaia = []

for i, p in enumerate(prflist):
    wcs = WCS(fits.getheader(datapath + p[0], 1))
    ra, dec = wcs.all_pix2world(p[1], p[2], 1)
    coord = SkyCoord(ra=ra, dec=dec, unit=(u.degree, u.degree), frame='icrs')
    j = Gaia.cone_search(coord, radius)
    r = j.get_results()
    r['i'] = i
    r['file'] = p[0]
    r['x'] = p[1]
    r['y'] = p[2]
    gaia.append(r)

gaiatab = table.vstack(gaia)
gaiatab

# Select only those stars that are likely good single point sources
gaiatab = gaiatab[(gaiatab['ra_error'] < 0.1) & (gaiatab['dec_error'] < 0.1)]


I am working on the file "CompanionPSF.ipynb".
The first task is:
Look at fit results when alpha is frozen
Even if the alpha is frozen to a differnet value then what I will ultimately use to fit the LOCI subtracted data, it's close enough. The goal here is to remove source that obviously have a different PSF shape, e.g. because they are unresolved binaries or background sources or something.
Can you write Python code for it?

out = plt.hist([res621['r0'], res845['r0']], bins=np.arange(1., 2.51, .05))

ind = (np.abs(res621['r0'] - 1.65) < .4) & (np.abs(res845['r0'] - 1.6) < 0.4)

ind.sum(), len(res621)

out = plt.hist([res621['ampl'][ind], res845['ampl'][ind]], bins=20, range=[0,2000])

plt.scatter(res621['ampl'], res845['ampl'], c=ind)

plt.scatter(res621['ampl'] / res845['ampl'], res845['r0'], c=gaiatab['parallax'])
plt.colorbar()

psf_621 = sherpa.astro.models.Beta2D()
psf_621.alpha = 2.2
psf_621.r0 = 1.7

psf_845 = sherpa.astro.models.Beta2D()
psf_845.alpha = 2
psf_845.r0 = 1.625

for this_psf in [psf_621, psf_845]:
    # Set starting values
    this_psf.xpos = 12.5
    this_psf.ypos = 12.5
    # Freeze psf values
    this_psf.alpha.frozen = True
    this_psf.r0.frozen = True

data = stars845[5].data
plt.plot(data[12, :])

psf_845.ampl = np.max(data)
x, y = np.indices(data.shape)
dpsf = sherpa.data.Data2D('', x.flatten(), y.flatten(), data.flatten())
fpsf = sherpa.fit.Fit(dpsf, psf_845, stat=sherpa.stats.LeastSq())
fpsf.fit()
plt.plot(psf_845(x.flatten(), y.flatten()).reshape(data.shape)[12, :])


I am working on the file "CompanionPSF.ipynb".
The first task is:
Next, we load all remaining sources.
Can you write Python code for it?

# -1 because the above positions are measured in ds9, which counts from (1,1)
# while the python code counts from (0,0)
stars621 = extract_stars([NDData(fits.open(datapath + row['file'])[1].data) for row in gaiatab],
                         [Table({'x': [row['x'] - 1], 'y': [row['y'] - 1]}) for row in gaiatab],
                         size=25)
stars845 = extract_stars([NDData(fits.open(datapath + row['file'].replace('10_', '20_'))[1].data)
                          for row in gaiatab],
                         [Table({'x': [row['x'] - 1], 'y': [row['y'] - 1]}) for row in gaiatab],
                         size=25)

def sherpa_phot(psf, data):
    # Set sensible starting values
    # Use hasattr so I can use the same function for e.g. Gauss2D if I want to try that
    if hasattr(psf, 'alpha') and not psf.alpha.frozen:
        psf.alpha = 2
    if hasattr(psf, 'r0') and not psf.r0.frozen:
        psf.r0 = 2
    psf.ampl = np.max(s.data)
    x, y = np.indices(data.shape)
    dpsf = sherpa.data.Data2D('', x.flatten(), y.flatten(), data.flatten())
    fpsf = sherpa.fit.Fit(dpsf, psf, stat=sherpa.stats.LeastSq())
    fpsf.fit()
    return data - psf(x.flatten(), y.flatten()).reshape(data.shape)

beta2d = sherpa.astro.models.Beta2D()
beta2d.xpos = stars621[0].data.shape[0] / 2
beta2d.ypos = stars621[0].data.shape[1] / 2
beta2d.alpha = 2
beta2d.alpha.frozen = True

results = []

for i, s in enumerate(stars621):
    out = sherpa_phot(beta2d, s.data)
    results.append([p.val for p in beta2d.pars])
res621 = Table(rows=results, names = [p.name for p in beta2d.pars])

results = []

for i, s in enumerate(stars845):
    out = sherpa_phot(beta2d, s.data)
    results.append([p.val for p in beta2d.pars])
res845 = Table(rows=results, names = [p.name for p in beta2d.pars])


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Buscaremos al expresidente Barack Obama
Can you write Python code for it?

obama = people[people['name'] == 'Barack Obama']

obama

obama['text']


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Cargar el dataset
Can you write Python code for it?


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Convertir el diccionario en una tabla
Can you write Python code for it?

obama_word_count_table = obama[['word_count']].stack('word_count', new_column_name = ['word','count'])


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
El algoritmo TF-IDF nos aporta más información.
Construir un modelo de nearest neighbor.
Can you write Python code for it?


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Examinar el TF-IDF del articulo de OBAMA
Can you write Python code for it?

obama = people[people['name'] == 'Barack Obama']

obama[['tfidf']].stack('tfidf',new_column_name=['word','tfidf']).sort('tfidf',ascending=False)


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Las palabras más comunes no nos aportan información.
Desarrollar un algoritmo TF-IDF para resolver este problema. Aplicaremos el contador de palabra como una columna y aplicaremos a todos los articulos.
Can you write Python code for it?

people['word_count'] = graphlab.text_analytics.count_words(people['text'])
people.head()

people['tfidf'] = graphlab.text_analytics.tf_idf(people['word_count'])


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Los datos contienen articulos de wikipedia sobre diferentes personas.
Can you write Python code for it?


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Otros ejemplos
Can you write Python code for it?

swift = people[people['name'] == 'Taylor Swift']

knn_model.query(swift)

jolie = people[people['name'] == 'Angelina Jolie']

knn_model.query(jolie)

arnold = people[people['name'] == 'Arnold Schwarzenegger']

knn_model.query(arnold)


I am working on the file "Comparacion de Documentos.ipynb".
The first task is:
Qué persona esta más relacionada con Obama?
Can you write Python code for it?


I am working on the file "Comparaison_Text.ipynb".
The first task is:
Comparaison $T_{ext}$ mesurée et celle de la météo
Can you write Python code for it?

coords_grenoble = (45.1973288, 5.7139923) #(45.1973288, 5.7103223)

startday, lastday = pd.to_datetime('22/06/2017', format='%d/%m/%Y'), pd.to_datetime('now')

# download the data:
data = wf.buildmultidayDF(startday, lastday, coords_grenoble )

import emoncmsfeed as getfeeds

dataframefreq = '10min'
feeds =  {  'T_ext':2  } # 'T_int':3 ,

df = getfeeds.builddataframe( feeds, dataframefreq ) # startdate=pd.to_datetime('22/06/2017')

df['Tmeteo'] = data['temperature']
df = df.interpolate()

df.plot( figsize=(14, 5) ); # plt.ylim([10, 30])


I am working on the file "Comparaison_Text.ipynb".
The first task is:
Comparaison avec une autre position GPS
Can you write Python code for it?

coords_bis = (45.1673058,5.7514976)

# download the data:
data_bis = wf.buildmultidayDF(startday, lastday, coords_bis )

data_coors = pd.concat( (data['temperature'], data_bis['temperature']) , axis=1  )

data_coors.plot(figsize=(14, 5))


I am working on the file "Comparaison_Text.ipynb".
The first task is:
Data from ROMMA
http://romma.fr/station_24.php?id=4&tempe=1
http://romma.fr/frame_station24.php?&id_station=4&tempe=1&humi=&pluie=&vent=&pressure=&rayonnement=
 /javascript/ copy()
Can you write Python code for it?

import json

with open('data/romma_temp.json') as data_file:
    data_romma = json.load(data_file)

dateindex = pd.to_datetime(data_romma[0], unit='ms')

df_romma = pd.DataFrame( {'T_romma':data_romma[1]}, index=dateindex )#,  parse_dates=True )

# Zoom
zoom_start = pd.to_datetime( '22/06/2017' )
mask = (df_romma.index > zoom_start)

df['T_romma'] = df_romma.loc[mask]
df = df.interpolate()

df.plot( figsize=(14, 5) ); plt.ylim([10, 40])


I am working on the file "Comparaison_Text.ipynb".
The first task is:
laquelle est correcte ??
 à priori Romma
Can you write Python code for it?

delta = df['T_romma'] - df['T_ext']

dd.plot()


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Ah zut, pour l'instant la magic cell %%tutor ne connaît pas d'autres modes pour Python 3.
En effet elle date de 2017, mais le nouveau mode de PythonTutor est plus récent !
J'ai ouvert ce ticket pour suggérer le support de ce nouveau mode ! Et cette PR
Can you write Python code for it?

%%tutor --lang py3anaconda --height 500
# https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html

x = 4
print("Hello world!" * x)

import numpy as np

I = np.sqrt(2/np.pi)*(18.0/27*np.sqrt(2)*np.cos(4.5) - 4.0/27*np.sqrt(2)*np.sin(4.5))

print(I)

import scipy.integrate as integrate
import scipy.special as special
result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5)
print(result)

I += np.sqrt(2*np.pi) * special.fresnel(3/np.sqrt(np.pi))[0]
print(I)

print(abs(result[0]-I))


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Aucun message d'erreur, rien dans la console qui a lancé Jupyter...
Je pense que l'extension est cassée avec les nouvelles variantes de Python ou de Jupyter, qui comme je le suspectais a beaucoup changé depuis 2016 (dernier commit de ce projet)...
J'ai demandé au développeur s'il maintenait encore son projet.
Et pour l'exemple plus gros :
Can you write Python code for it?

%%nbtutor --reset --force

import calendar

def filter_annee(annee):
    return (
        set(calendar.Calendar(annee).itermonthdays2(annee, 2))
        & {(1,0), (28, 6), (29, 0)}
    ) == {(1, 0), (28, 6)}

nb_bonnes_annees = len(list(filter(filter_annee, ( annee
        for annee in range(1994, 2077 + 1)
        # if not calendar.isleap(annee) # en fait c'est inutile
    )
)))


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Avec tutormagic
Alors évidemment, la "cell magic" %%tutor ne marche pas depuis le kernel C, mais en repassant au kernel Python 3, on peut faire :
Can you write Python code for it?

%reload_ext tutormagic

%%tutor --lang c --height 600

/* Cette cellule est écrite en langage C, il ne faut pas l'exécuter avec le kernel Python */
/* Installez le kernel https://github.com/brendan-rius/jupyter-c-kernel */

#include <stdio.h>
#define MIN_I 1
#define MAX_I 10
#define MIN_POWER 1
#define MAX_POWER 5

unsigned long power(int n, unsigned long acc, unsigned long x) {
    if (n == 0) { return acc; }
    if (n % 2 == 0) { return power(n/2, acc, x*x); }
    else { return power((n-1)/2, acc * x, x*x); }
}

int main(void) {
    for (int i = MIN_I; i <= MAX_I; i++) {
        printf("\n- Pour i = %i :", i);
        for (int n = MIN_POWER; n <= MAX_POWER; ++n) {
            printf("\n\ti^%i = %li", n, power(n, 1, i));
        }
    }
}


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Avec tutormagic
Je suis le tutoriel présent sur la documentation.
Can you write Python code for it?

%load_ext tutormagic

%%tutor --lang python3 --height 500

URL = "http://PythonTutor.com"
test = "Démo de tutormagic"
explication = f"avec un iframe vers {URL}"
print(test, explication)

somme = 0
MAX_I = 10
for i in range(1, MAX_I):
    somme += i**3
print(f"Somme des {MAX_I} premiers cubes = {somme}")


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Avec tutormagic ?
Can you write Python code for it?

%%tutor --lang python3 --height 100

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

X = np.linspace(-10, 10)

def f1(x): return np.cos(x**2)
def f2(x): return np.sin(x**2)
def f3(x): return f1(x)+f2(x)
Y1 = f1(X)
Y2 = f2(X)
Y3 = f3(X)

with plt.xkcd():
    plt.figure(figsize=(14,8))
    plt.plot(X, Y1, "+-r", label="$f_1(x)$", ms=10, lw=3)
    plt.plot(X, Y2, "o-b", label="$f_2(x)$", ms=10, lw=3)
    plt.plot(X, Y3, "d-y", label="$f_3(x)$", ms=10, lw=3)
    plt.legend()
    plt.xlabel("Axe $x$")
    plt.ylabel("Axe $y$")
    plt.title("Trois fonctions de la variable réelle")
    plt.show()


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Bon, le package semble installé, et ajouté comme une extension Jupyter, qui le reconnaît et la valide...
Chargez l'extension avec %load_ext nbtutor a fonctionné... juste la magic %%nbtutor ne marche pas.
Can you write Python code for it?


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
C'est un bon exemple car il utilise des listes, des ensembles etc.
Peut-être restreindre le nombre d'année considérées, pour simplifier ?
Et donc on a juste à compter les années, de 1994 à 2077 inclus, qui ne sont pas des années bissextiles et qui satisfont le filtre :
Can you write Python code for it?

%%time
len(list(filter(filter_annee, ( annee
        for annee in range(1994, 2077 + 1)
        # if not calendar.isleap(annee) # en fait c'est inutile
    )
)))


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Ca marche ! Wooo!

Avec numpy et matplotlib ?
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

X = np.linspace(-10, 10)

def f1(x): return np.cos(x**2)
def f2(x): return np.sin(x**2)
def f3(x): return f1(x)+f2(x)
Y1 = f1(X)
Y2 = f2(X)
Y3 = f3(X)

# avec la police "Humour Sans", téléchargée depuis https://aur.archlinux.org/packages/ttf-humor-sans/
with plt.xkcd():
    plt.figure(figsize=(14,8))
    plt.plot(X, Y1, "+-r", label="$f_1(x)$", ms=10, lw=3)
    plt.plot(X, Y2, "o-b", label="$f_2(x)$", ms=10, lw=3)
    plt.plot(X, Y3, "d-y", label="$f_3(x)$", ms=10, lw=3)
    plt.legend()
    plt.xlabel("Axe $x$")
    plt.ylabel("Axe $y$")
    plt.title("Trois fonctions de la variable réelle")
    plt.show()


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Ca marche bien pour ce petit exemple !
Essayons plus solide :
Can you write Python code for it?

%%tutor --lang python3 --run --height 500 --curInstr 11

import calendar

def filter_annee(annee):
    return (
        set(calendar.Calendar(annee).itermonthdays2(annee, 2))
        & {(1,0), (28, 6), (29, 0)}
    ) == {(1, 0), (28, 6)}

nb_bonnes_annees = len(list(filter(filter_annee, ( annee
        for annee in range(1994, 2077 + 1)
        # if not calendar.isleap(annee) # en fait c'est inutile
    )
)))


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Ca semble bien chargé, essayons !
Can you write Python code for it?

%%nbtutor --reset --force --debug

explication = "Démo de nbtutor, normalement sans iframe vers PythonTutor.com"
print(explication)

somme = 0
MAX_I = 10
for i in range(1, MAX_I):
    somme += i**3
print(f"Somme des {MAX_I} premiers cubes = {somme}")


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Et donc ce notebook peut déclarer ses dépendances :
Can you write Python code for it?

%load_ext watermark

watermark -a "Lilian Besson (Naereen)" -p tutormagic,nbtutor,numpy,matplotlib


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Ici, le problème vient de la "cell magic" %matplotlib en ligne 4 !
Et si on essaie sans cette cell magic ?
Can you write Python code for it?

%%tutor --lang python3 --height 500

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-10, 10)

def f1(x): return np.cos(x**2)
def f2(x): return np.sin(x**2)
def f3(x): return f1(x)+f2(x)
Y1 = f1(X)
Y2 = f2(X)
Y3 = f3(X)

print(Y1)
print(Y2)
print(Y3)


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
POUF ça marche, merci à ma petite modification (trois lignes changées).

C'est quand même beau les logiciels open-source...

Une remarque en passant : avoir PythonTutor offline? semble possible !
Au fait, PythonTutor n'est plus libre, mais un fork récent existe : c'est peut-être un vol de propriété intellectuelle, mais bon, ça peut dépanner !
TODO: l'installer chez moi, et faire en sorte que tutormagic fonctionne en local aussi ! Regardez ce ticket assez récent, mais pas avancé (mais très détaillé), et celui là sur un clone de PythonTutor.
=> J'ai réussi à avoir PyTutor (v5-unity) mais juste pour Python3... pas C ou Java... et je sais pas comment faire !
Avec nbtutor ?
Can you write Python code for it?

%%nbtutor --reset --force --debug

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-10, 10, 40)

def f1(x): return np.cos(x**2)
def f2(x): return np.sin(x**2)
def f3(x): return f1(x)+f2(x)
Y1 = f1(X)
Y2 = f2(X)
Y3 = f3(X)

with plt.xkcd():
    plt.figure(figsize=(14,8))
    plt.plot(X, Y1, "+-r", label="$f_1(x)$", ms=10, lw=3)
    #plt.plot(X, Y2, "o-b", label="$f_2(x)$", ms=10, lw=3)
    #plt.plot(X, Y3, "d-y", label="$f_3(x)$", ms=10, lw=3)
    plt.legend()
    #plt.xlabel("Axe $x$")
    #plt.ylabel("Axe $y$")
    plt.title("Trois fonctions de la variable réelle")
    plt.show()


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Première comparaison
Can you write Python code for it?

test = "Démo de jupyter notebook"
print(test)

somme = 0
MAX_I = 10
for i in range(1, MAX_I):
    somme += i**3
print(f"Somme des {MAX_I} premiers cubes = {somme}")


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Sa documentation se charge bien !
```
Docstring:
::
%nbtutor [-r] [-f] [-i] [-d N] [--digits D] [--max_size S] [--step_all]
               [--expand_arrays] [--nolies] [--debug]
```
Mais rien ne se passe ! Même en mode --debug...
Can you write Python code for it?

%%nbtutor --reset --force --debug

x = sum([i**3 for i in range(1, 10)])
print(x)


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
Un petit programme à tester avec les deux interfaces
Je vais emprunter le petit problème arithmético-algorithmique suivant, posé à mes élèves au début de février 2021 :

Mini challenge algorithmique pour les passionnés en manque de petits exercices de code : (optionnel) Vous avez dû observer que ce mois de février est spécial parce que le 1er février est un lundi, et qu'il a exactement 4 lundis, 4 mardis, 4 mercredis, 4 jeudis, 4 vendredis, 4 samedis et 4 dimanches.
Question : Comptez le nombre de mois de février répondant à ce critère (je n'ai pas trouvé de nom précis), depuis l'année de création de l'ENS Rennes (1994, enfin pour Cachan antenne Bretagne) jusqu'à 2077 (1994 et 2077 inclus).

Pour plus d'informations, cf ce notebook (aussi sur GitHub et nbviewer).
Avec le module calendar on pourrait faire comme en Bash : imprimer les calendriers, et rechercher des chaînes particulières... mais ce n'est pas très propre. Essayons avec ce même module mais en écrivant une solution fonctionnelle !
Can you write Python code for it?

import calendar

def filter_annee(annee):
    return (
        set(calendar.Calendar(annee).itermonthdays2(annee, 2))
        & {(1,0), (28, 6), (29, 0)}
    ) == {(1, 0), (28, 6)}

filter_annee(2020), filter_annee(2021), filter_annee(2022)


I am working on the file "Comparaison_de_tutormagic_et_nbtutor_pour_visualiser_du_code_Python_et_C_dans_un_notebook_Jupyter.ipynb".
The first task is:
~~Ca marche pas :(~~ Apparemment ça marche pas bien si tutormagic a aussi été exécuté...
Je vois sur la documentation du projet que l'installation de l'extension ajoute une "barre d'outil de cellule", ~~mais je ne l'ai pas~~... je l'ai désormais, en rechargeant le notebook !
Elle prend la place de la barre d'outil pour les slides RISE, mais ce n'est pas grave, on peut passer de l'un à l'autre.
Je rencontre le même problème que ce ticket.
Essayons de comprendre ce problème de nbtutor !!
Can you write Python code for it?

!pip show nbtutor

!jupyter-nbextension list 2>&1 | grep -A 2 nbtutor


I am working on the file "Compare Fingers.ipynb".
The first task is:
And some more specialized dependencies:
 1. Slict provides a convenient slice-able dictionary interface
 2. Chest is an out-of-core dictionary that we'll hook directly to a globus remote using...
 3. glopen is an open-like context manager for remote globus files
Can you write Python code for it?

from chest import Chest
from slict import CachedSlict
from glopen import glopen, glopen_many


I am working on the file "Compare Fingers.ipynb".
The first task is:
Configuration for this figure.
Can you write Python code for it?

config = Foo()
config.name0     = "HighAspect/HA_base/HA_base"
config.name1     = "HighAspect/HA_visc/HA_visc"
#config.arch_end = "maxhutch#alpha-admin/~/pub/"
config.arch_end = "alcf#dtn_mira/projects/alpha-nek/"


I am working on the file "Compare Fingers.ipynb".
The first task is:
Open a chest located on a remote globus endpoint and load a remote json configuration file.
Can you write Python code for it?

c0 = Chest(path      = "{:s}-results".format(config.name0),
          open      = partial(glopen,      endpoint=config.arch_end),
          open_many = partial(glopen_many, endpoint=config.arch_end))
sc0 = CachedSlict(c0)
with glopen(
            "{:s}.json".format(config.name0), mode='r',
            endpoint = config.arch_end,
            ) as f:
    params0 = json.load(f)

c1 = Chest(path      = "{:s}-results".format(config.name1),
          open      = partial(glopen,      endpoint=config.arch_end),
          open_many = partial(glopen_many, endpoint=config.arch_end))
sc1 = CachedSlict(c1)
with glopen(
            "{:s}.json".format(config.name1), mode='r',
            endpoint = config.arch_end,
            ) as f:
    params1 = json.load(f)


I am working on the file "Compare Fingers.ipynb".
The first task is:
Plot the bubble height, the 'H' keys, vs. time.
Use a spline to compute the derivative.
Can you write Python code for it?

spl0 = InterpolatedUnivariateSpline(sc0[:,'H'].keys(), sc0[:,'H'].values(), k=3)
dHdt0 = spl0.derivative()
Ts0 = np.linspace(sc0[:,'H'].keys()[0], sc0[:,'H'].keys()[-1], 1000)
Vb0 = -dHdt0(Ts0)
Vm0 = np.array([np.max(sc0[t,'w_max_z']) for t in sc0[:,'w_max_z'].keys()])
Vc0 = np.array([sc0[t,'w_max_z'][sc0[t,'w_max_z'].shape[0]/2] for t in sc0[:,'w_max_z'].keys()])
theory0 = np.sqrt(
                  params0["atwood"] * params0["g"] * params0["extent_mesh"][0] / np.pi
                + (2.*np.pi*params0["viscosity"] / params0["extent_mesh"][0])**2
                ) - (2.*np.pi*params0["viscosity"] / params0["extent_mesh"][0])

spl1 = InterpolatedUnivariateSpline(sc1[:,'H'].keys(), sc1[:,'H'].values(), k=3)
dHdt1 = spl1.derivative()
Ts1 = np.linspace(sc1[:,'H'].keys()[0], sc1[:,'H'].keys()[-1], 1000)
Vb1 = -dHdt1(Ts1)
Vm1 = np.array([np.max(sc1[t,'w_max_z']) for t in sc1[:,'w_max_z'].keys()])
Vc1 = np.array([sc1[t,'w_max_z'][sc1[t,'w_max_z'].shape[0]/2] for t in sc1[:,'w_max_z'].keys()])
theory1 = np.sqrt(
                  params1["atwood"] * params1["g"] * params1["extent_mesh"][0] / np.pi
                + (2.*np.pi*params1["viscosity"] / params1["extent_mesh"][0])**2
                ) - (2.*np.pi*params1["viscosity"] / params1["extent_mesh"][0])

fig, axs = plt.subplots(2,1, sharex=True)

axs[0].plot(Ts0, -spl0(Ts0));
axs[0].plot(Ts1, -spl1(Ts1));
#axs[0].plot(sc[:,'H'].keys(), -np.array(sc[:,'H'].values()), 'yo');
axs[0].set_ylabel('Depth (m)')

axs[1].plot(Ts0, Vb0, 'b-');
axs[1].plot(Ts1, Vb1, 'b-');
axs[1].plot(sc0[:,'w_max_z'].keys(), Vm0, 'g-');
axs[1].plot(sc1[:,'w_max_z'].keys(), Vm1, 'g-');
axs[1].plot(sc0[:,'w_max_z'].keys(), Vc0, 'r-');
axs[1].plot(sc1[:,'w_max_z'].keys(), Vc1, 'r-');
axs[1].plot([Ts0[0],Ts0[-1]], [theory0, theory0], 'k--');
axs[1].plot([Ts1[0],Ts1[-1]], [theory1, theory1], 'k--');
axs[1].set_ylabel('Velocity (scaled)')
axs[1].set_xlabel('Time (s)');
plt.savefig('Figure1.eps')

%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py...


I am working on the file "Comparing JavaScript with Python.ipynb".
The first task is:
Another example of features JavaScript is acquiring with ES6 (Sixth Edition we might call it), are rest and default parameters.  A "rest" parameter has nothing to do with RESTful, and everything to do with "the rest" as in "whatever is left over."
For example, in the function below, we pass in more ingredients than some recipe requires, yet because of the rest argument, which has to be the last, the extra ingredients are kept.  Pre ES6, JavaScript had no simple mechanism for allowing parameters to "rise to the occasion." Instead they would match up, or stay undefined.
Can you write Python code for it?

%%javascript
var sendTo = function(s){
    element.append(s + "<br />");
}

//Function to send everyone their Surface Studio!
let sendSurface = recepient => {
   sendTo(recepient);
}

function recipe(ingredient0, ingre1, ing2, ...more){
    sendSurface(ingredient0 + " is one ingredient.");
    sendSurface(more[1] + " is another.");
}
recipe("shrimp", "avocado", "tomato", "potato", "squash", "peanuts");


I am working on the file "Comparing JavaScript with Python.ipynb".
The first task is:
In Python we have both sequence and dictionary parameters, which we could say are both rest parameters, one for scooping up positionals, the other for gathering the named.  Here's how that looks:
Can you write Python code for it?

def recipe(ingr0, *more, ingr1, meat="turkey", **others):
    print(more)
    print(others)

recipe("avocado", "tomato", "potato", ingr1="squash", dessert="peanuts", meat = "shrimp")


I am working on the file "Comparing_DMRG_ED_and_SDP.ipynb".
The first task is:
Comparison
The level-one relaxation matches the ground state energy given by DMRG and ED.
Can you write Python code for it?

data = [dmrg_ground_state_energy,\
        sparsediag_ground_state_energy,\
        sdp_ground_state_energy]
labels = ["DMRG", "ED", "SDP"]
print ("{:>4} {:>9} {:>10} {:>10} {:>10}").format("", *lattice_range)
for label, row in zip(labels, data):
    print ("{:>4} {:>7.6f} {:>7.6f} {:>7.6f} {:>7.6f}").format(label, *row)


I am working on the file "Comparing_DMRG_ED_and_SDP.ipynb".
The first task is:
We invoke the solvers and extract the ground state energies from the solutions. First we use exact diagonalization, which, unfortunately does not scale beyond a lattice size of $4\times 4$.
Can you write Python code for it?

prefix_sparse = 'comparison_sparse'
input_file_sparse = pyalps.writeInputFiles(prefix_sparse, parms[:-1])

res = pyalps.runApplication('sparsediag', input_file_sparse)
sparsediag_data = pyalps.loadEigenstateMeasurements(
                     pyalps.getResultFiles(prefix=prefix_sparse))

sparsediag_ground_state_energy = extract_ground_state_energies(sparsediag_data)
sparsediag_ground_state_energy.append(0)


I am working on the file "Comparing_DMRG_ED_and_SDP.ipynb".
The first task is:
We will need a helper function to extract the ground state energy from the solutions:
Can you write Python code for it?

def extract_ground_state_energies(data):
    E0 = []
    for Lsets in data:
        allE = []
        for q in pyalps.flatten(Lsets):
            allE.append(q.y[0])
        E0.append(allE[0])
    return sorted(E0, reverse=True)


I am working on the file "Comparison.ipynb".
The first task is:
1.2) SOSM + AddBOS
Can you write Python code for it?

prop_matched, resp_matched, prop_indptr, resp_indptr = mf.DA(prop_prefs, resp_prefs, resp_caps, prop_caps, list_length-1)
print('prop_matched = ' + str(prop_matched))
print('resp_matched = ' + str(resp_matched))
print('prop_indptr = ' + str(prop_indptr))
print('resp_indptr = ' + str(resp_indptr))
mf.Graph(prop_matched, resp_matched, prop_indptr, resp_indptr)

prop_matched, resp_matched, prop_indptr, resp_indptr = mf.AddBOS(prop_prefs, resp_prefs, prop_matched, resp_matched, resp_caps, prop_caps)
print('prop_matched = ' + str(prop_matched))
print('resp_matched = ' + str(resp_matched))
print('prop_indptr = ' + str(prop_indptr))
print('resp_indptr = ' + str(resp_indptr))
mf.Graph(prop_matched, resp_matched, prop_indptr, resp_indptr)


I am working on the file "Comparison.ipynb".
The first task is:
1.3) SOSM
Can you write Python code for it?

prop_matched, resp_matched, prop_indptr, resp_indptr = mf.DA(prop_prefs, resp_prefs, resp_caps, prop_caps, resp_num)
print('prop_matched = ' + str(prop_matched))
print('resp_matched = ' + str(resp_matched))
print('prop_indptr = ' + str(prop_indptr))
print('resp_indptr = ' + str(resp_indptr))
mf.Graph(prop_matched, resp_matched, prop_indptr, resp_indptr)


I am working on the file "Comparison.ipynb".
The first task is:
2) Comparison
Evaluate Axis is below;
    1. Stability
    2. Truth-telling
    3. Efficiency
    4. Fairness
    5. Feasibility
2.1) truth-telling circumstances
The result is
|| BOS | DAAdd | DA |
|:-----:|:-----------:|:------------:|:------------:|
|Stability| 1 | 0 | 0 |
|Truth-telling| 5 | 5 | 5 |
|Efficiency| 0.733, 2.167 | 0.9, 1.333 | 0.9, 1.333|
|Fairness| 0, 0 | 0, 0 | 0, 0|
|Feasibility| 9 | 13 | 15|
Can you write Python code for it?

# BOS
mf.Comp('BOS', prop_prefs, resp_prefs, resp_caps, prop_caps, list_length)

# DAAdd
mf.Comp('DAAdd', prop_prefs, resp_prefs, resp_caps, prop_caps, list_length)

# DA
mf.Comp('DA', prop_prefs, resp_prefs, resp_caps, prop_caps, resp_num)


I am working on the file "Comparison.ipynb".
The first task is:
2.3) Common-Value Model
Utility Function for the i-th student is given as follows.
$U_{i} = \alpha CV_{j} + (1-\alpha) PV_{ij}$
$CV_{j}$ means a common value to the j-th seminar. (popularity etc.)
$PV_{ij}$ means the i-th student's private value to the j-th seminar.
These are uniformly distributed over [0, 1), and the lower j is, the higher CV is.
$\alpha$ is a parameter, default set is 0.3.
Utility Function for the j-th seminar is given as follows.
$U_{j} = \beta CV_{i} + (1-\beta) PV_{ji}$
$CV_{i}$ means a common value to the i-th student. (grade etc.)
$PV_{ji}$ means the j-th seminar's private value to the i-th student.
These are uniformly distributed over [0, 1), and the lower i is, the higher CV is.
$\beta$ is a parameter, default set is also 0.3.
Suppose that the preferences of the students and seminars are decided by these utility functions,
and the number of students is 345, that of seminars is 38.
Half of the seminars have capacity 6, while the other half have capacity 13.
All students have 2 capacity.
Can you write Python code for it?

prop_num = 9
resp_num = 6
alpha = 0.3
beta = 0.3
prop_caps = [2 for i in range(prop_num)]
resp_caps = [2, 2, 2, 4, 4, 4]
list_length = 3

prop_prefs, resp_prefs = mf.MakeCVprefs(prop_num, resp_num, alpha, beta)

print('prop_prefs =')
print(prop_prefs)
print('\nresp_prefs = ')
print(resp_prefs)
print('\nprop_caps = ')
print(prop_caps)
print('\nresp_caps = ')
print(resp_caps)

result1 = mf.Comp('BOS', prop_prefs, resp_prefs, resp_caps, prop_caps, list_length)
result2 = mf.Comp('DAAdd', prop_prefs, resp_prefs, resp_caps, prop_caps, list_length)
result3 = mf.Comp('DA', prop_prefs, resp_prefs, resp_caps, prop_caps)

print('Justified Envy')
print('1: %s \n2: %s \n3: %s' % (result1[0], result2[0], result3[0]))
print('Truth-telling')
print('1: %s \n2: %s \n3: %s' % (result1[1], result2[1], result3[1]))
print('Efficiency of the students')
print('1: %s \n2: %s \n3: %s' % (result1[2], result2[2], result3[2]))
print('Efficiency of the seminars')
print('1: %s \n2: %s \n3: %s' % (result1[3], result2[3], result3[3]))
print('None Zemi')
print('1: %s \n2: %s \n3: %s' % (result1[4], result2[4], result3[4]))
print('Vacant Caps')
print('1: %s \n2: %s \n3: %s' % (result1[5], result2[5], result3[5]))
print('Interviews')
print('1: %s \n2: %s \n3: %s' % (result1[6], result2[6], result3[6]))


I am working on the file "Competitions/qiskit-qchack/qiskit.ipynb".
The first task is:
In pulse we calibrate the ground state measurement.
Can you write Python code for it?

from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.test.mock import FakeValencia

backend = FakeValencia()

with pulse.build(backend, name='hadamard') as h_q0:
    pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))

h_q0.draw()

circ.add_calibration('h', [0], h_q0)

from qiskit import transpile
from qiskit.test.mock import FakeAlmaden

backend = FakeAlmaden()

circ = transpile(circ, backend)

print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)


I am working on the file "Competitions/qiskit-qchack/qiskit.ipynb".
The first task is:
Qiskit pulse allows the use of the general unitary through the u3 gate.
On IBM hardware, the U3Gate is implemented using two X90 pulses. [r1]
There are different layouts for this part, and this is in-depth discussed in 3.1.
There are also advantages and disadvantages for different layouts, as will be seen.
It is not discussed how analysis of the underlying matrices are related to the QEC (quantum error correction) or noise, but decompositions similar to [r2] can be a starting point.
r1: https://qiskit.org/documentation/stubs/qiskit.circuit.library.U3Gate.html
r2: https://qiskit.org/textbook/ch-quantum-hardware/cQED-JC-SW.html#2.-The-Schrieffer-Wolff-Transformation-
Can you write Python code for it?


I am working on the file "Competitive_VergutsFias.ipynb".
The first task is:
Fit the Net
Can you write Python code for it?


I am working on the file "Competitive_VergutsFias.ipynb".
The first task is:
Mean activation value of number filed nodes as a function of the distance to eache node's preferred numerosity
Activation gradually diminish as the distance increase

percentage normalize the input responses
center plot to preferred numerosity
label the distances
Can you write Python code for it?

# Percentage normalization
for i in range(5):
    v[:,i] = v[:,i]/np.max(v[:,i])*100

import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")

x =np.arange(1,6)
plt.figure(figsize=(9, 2))
for i in range(5):
    plt.subplot(1,5,i+1)
    plt.plot(x,v[:,i],'*-', color='#99a2a1')
    plt.axis([0, 6, plt.axis()[2], plt.axis()[3]],color='#99a2a1')

plt.subplots_adjust(wspace=0.5, hspace=0.5, top=1, bottom=0, left=0, right=1)
plt.savefig('normalized_response.png')
plt.show()


I am working on the file "Competitive_VergutsFias.ipynb".
The first task is:
Weights
Can you write Python code for it?

maxnum=5;
nmagnodes=2*maxnum;
nhidnodes=500;
Weight = np.zeros((10,500))
Weight=np.random.rand(nmagnodes,nhidnodes)*(np.random.rand(nmagnodes,nhidnodes)<0.3)
# Note with random weights as defined below the net doesn't work
#Weights = np.random.rand(10,100)
Weight[:,78]


I am working on the file "Complete-Python-Bootcamp-master/Advanced Dictionaries.ipynb".
The first task is:
One of the reasons it is not as common is the difficulty in structuring the key names that are not based off the values.
Iteration over keys,values, and items
Dictionaries can be iterated over using the iter methods available in a dictionary. For example:
Can you write Python code for it?

for k in d.iterkeys():
    print k

for v in d.itervalues():
    print v

for item in d.iteritems():
    print item


I am working on the file "Complete-Python-Bootcamp-master/Advanced Dictionaries.ipynb".
The first task is:
view items,keys and values
You can use the view methods to view items keys and values. For example:
Can you write Python code for it?

d.viewitems()

d.viewkeys()

d.viewvalues()


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
Basic List Methods
If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
Let's go ahead and explore some more special methods for lists:
Can you write Python code for it?


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
Indexing and Slicing
Indexing and slicing works just like in strings. Let's make a new list to remind ourselves of how this works:
Can you write Python code for it?

my_list = ['one','two','three',4,5]

# Grab element at index 0
my_list[0]

# Grab index 1 and everything past it
my_list[1:]

# Grab everything UP TO index 3
my_list[:3]


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
List Comprehensions
Python has an advanced feature called list comprehensions. They allow for quick construction of lists. To fully understand list comprehensions we need to understand for loops. So don't worry if you don't completely understand this section, and feel free to just skip it since we will return to this topic later.
But in case you want to know now, here are a few examples!
Can you write Python code for it?

# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]

first_col


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
Nesting Lists
A great feature of of Python data structures is that they support nesting. This means we can have data structures within data structures. For example: A list inside a list.
Let's see how this works!
Can you write Python code for it?

# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]

# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]

# Show
matrix


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
Note: This doesn't actually change the original list!
Can you write Python code for it?


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
Use the append method to permanently add an item to the end of a list:
Can you write Python code for it?

# Append
l.append('append me!')

# Show
l


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
We can also use + to concatenate lists, just like we did for strings.
Can you write Python code for it?


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
We can also use the * for a duplication method similar to strings:
Can you write Python code for it?

# Make the list double
my_list * 2

# Again doubling not permanent
my_list


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
We can use the sort method and the reverse methods to also effect your lists:
Can you write Python code for it?

new_list = ['a','e','x','b','c']

#Show
new_list

# Use reverse to reverse order (this is permanent!)
new_list.reverse()

new_list

# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()

new_list


I am working on the file "Complete-Python-Bootcamp/Lists.ipynb".
The first task is:
You would have to reassign the list to make the change permanent.
Can you write Python code for it?

# Reassign
my_list = my_list + ['add new item permanently']

my_list


I am working on the file "Complete-Python-Bootcamp/Print Formatting.ipynb".
The first task is:
Floating Point Numbers
Floating point numbers use the format %n1.n2f where the n1 is the total minimum number of digits the string should contain (these may be filled with whitespace if the entire number does not have this many digits. The n2 placeholder stands for how many numbers to show past the decimal point. Lets see some examples:
Can you write Python code for it?

print 'Floating point numbers: %1.2f' %(13.144)

print 'Floating point numbers: %1.0f' %(13.144)

print 'Floating point numbers: %1.5f' %(13.144)

print 'Floating point numbers: %10.2f' %(13.144)

print 'Floating point numbers: %25.2f' %(13.144)


I am working on the file "Complete-Python-Bootcamp/Print Formatting.ipynb".
The first task is:
Multiple Formatting
Pass a tuple to the modulo symbol to place multiple formats in your print statements:
Can you write Python code for it?


I am working on the file "Complete-Python-Bootcamp/Print Formatting.ipynb".
The first task is:
Strings
You can use the %s to format strings into your print statements.
Can you write Python code for it?

s = 'STRING'
print 'Place another string with a mod and s: %s' %(s)


I am working on the file "Complete-Python-Bootcamp/Print Formatting.ipynb".
The first task is:
Using the string .format() method
The best way to format objects into your strings for print statements is using the format method. The syntax is:
'String here {var1} then also {var2}'.format(var1='something1',var2='something2')

Lets see some examples:
Can you write Python code for it?

print 'This is a string with an {p}'.format(p='insert')

# Multiple times:
print 'One: {p}, Two: {p}, Three: {p}'.format(p='Hi!')

# Several Objects:
print 'Object 1: {a}, Object 2: {b}, Object 3: {c}'.format(a=1,b='two',c=12.3)


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
Python 3 Alert!
Something to note. In Python 3, print is a function, not a statement. So you would print statements like this:
print('Hello World')
If you want to use this functionality in Python2, you can import form the future module.
A word of caution, after importing this you won't be able to choose the print statement method anymore. So pick whichever one you prefer depending on your Python installation and continue on with it.
Can you write Python code for it?

# To use print function from Python 3 in Python 2
from __future__ import print_function

print('Hello World')


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
Basic Built-in String methods
Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.
We call methods with a period and then the method name. Methods are in the form:
object.method(parameters)
Where parameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. Later on we will be creating our own objects and functions!
Here are some examples of built-in methods in strings:
Can you write Python code for it?

s

# Upper Case a string
s.upper()

# Lower case
s.lower()

# Split a string by blank space (this is the default)
s.split()

# Split by a specific element (doesn't include the element that was split on)
s.split('W')


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
Notice how the error tells us directly what we can't do, change the item assignment!
Something we can do is concatenate strings!
Can you write Python code for it?

s

# Concatenate strings!
s + ' concatenate me!'

# We can reassign s completely though!
s = s + ' concatenate me!'

print(s)

s


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
Now let's learn about printing strings!
Printing a String
Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function.
Can you write Python code for it?

# We can simply declare a string
'Hello World'

# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
String Basics
We can also use a function called len() to check the length of a string!
Can you write Python code for it?


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
String Properties
Its important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. For example:
Can you write Python code for it?

s

# Let's try to change the first letter to 'x'
s[0] = 'x'


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
The reason for the error above is because the single quote in I'm stopped the string. You can use combinations of double and single quotes to get the complete statement.
Can you write Python code for it?

"Now I'm ready to use the single quotes inside a string!"


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
There are many more methods than the ones covered here. Visit the advanced String section to find out more!
Print Formatting
We can use the .format() method to add formatted objects to printed string statements.
The easiest way to show this is through an example:
Can you write Python code for it?

'Insert another string with curly brackets: {}'.format('The inserted string')


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
We can use a : to perform slicing which grabs everything up to a designated point. For example:
Can you write Python code for it?

# Grab everything past the first term all the way to the length of s which is len(s)
s[1:]

# Note that there is no change to the original s
s

# Grab everything UP TO the 3rd index
s[:3]


I am working on the file "Complete-Python-Bootcamp/Strings.ipynb".
The first task is:
We can use a print statement to print a string.
Can you write Python code for it?

print 'Hello World 1'
print 'Hello World 2'
print 'Use \n to print a new line'
print '\n'
print 'See what I mean?'


I am working on the file "Components.ipynb".
The first task is:
IPython Console
IPython started as a terminal based interactive console with tab completion, integrated help, plotting support, etc. This runs the Python based kernel in proces or out of process:
Can you write Python code for it?


I am working on the file "Components.ipynb".
The first task is:
IPython Qt Console
The Qt Console Console provides another frontend with inline plotting and multiline code editing.
Can you write Python code for it?


I am working on the file "Components.ipynb".
The first task is:
IPython.parallel
This same abstraction of running code remotely enables a high-level parallel computing framework.
Can you write Python code for it?


I am working on the file "CompoundFiveOctahedra.ipynb".
The first task is:
David:  "So, the beauty of working with these bits is that I can move them around."
Can you write Python code for it?


I am working on the file "CompoundFiveOctahedra.ipynb".
The first task is:
Lets take this opportunity to contextualize the above in terms of our larger volumes table.  We'll need a few more players, namely the E family.
The T_factor, about 0.99948333, and discussed in Synergetics, is the linear scale factor by which the E module is reduced to create a T module.  This T_factor to the 3rd power would be the volumetric reduction factor, and applied to the E module returns volume 1/24.
T_factor = $(\Phi/\sqrt{2}) (\sqrt[3]{2/3})$.
An RT of 120 T modules has a volume of exactly 5, where T = A = B = 1/24 tetravolumes.
An RT of 120 E modules has a radius (center to diamond face centers) of exactly 1, and encases a unit radius sphere.
This slightly larger RT shows up as RT5+ in the table below.
Can you write Python code for it?

E  = (root2/8) * (Ø ** -3)  # home base Emod
E3 = E * Ø **  3            # Emod phi up
e3 = E * Ø ** -3            # Emod phi down
SuperRT = 120 * E3          # = 20 * Synergetics Constant sqrt(9/8)

F  = gmpy2.mpfr(gmpy2.mpq(1, 16))   # space-filling shape, appears in 5RD

T_factor = Ø/root2 * gmpy2.root( gmpy2.mpq(2, 3), 3) # T radius vs. E radius of 1
T = E * T_factor ** 3
T_factor

print("Five VEs      : {:60.57}".format(480*S + 280*s3)) # compound shape
print("SuperRT       : {:60.57}".format(SuperRT))        # formed by P Dodeca + Icosa verts
print("Cubocta       : {:60.57}".format(20*S6 + 20*S3))  # classic Jitterbug (JB) starts here
print("Icosa         : {:60.57}".format(100*E3 + 20*E))  # JB icosa
print("SmallGuy      : {:60.57}".format(360*E + 85*e3))  # skew to JB icosa
print("P Dodeca      : {:60.57}".format(348*E + 84*e3))  # dual to JB icosa, edges crossing
print("Five Octas    : {:60.57}".format(132*S + 36*s3))  # compound shape
print("Rh Dodeca (RD): {:60.57}".format(6*S6 + 6*S3))    # space filler, shares verts with RT7.5
print("RT5+          : {:60.57}".format(120*E))          # 120 E modules
print("RT5           : {:60.57}".format(5*S6 + 5*S3))    # 120 T modules
print("RT5 (check)   : {:60.57}".format(T * 120))
print("Octa          : {:60.57}".format(4*S6 + 4*S3))    # JB octahedron
print("Cube          : {:60.57}".format(3*S6 + 3*S3))
print("Skew Icosa    : {:60.57}".format(Icosa_within))   # askew to 2.5 VE
print("Small VE      : {:60.57}".format(cubocta))        # 1/8 volume of JB cubocta
print("Five Tetras   : {:60.57}".format(35*S + 45*s3))   # per Koski
print("Tetra         : {:60.57}".format(5*S3 + S))       # unit volume
print("-" * 76)
print("F             : {:60.57}".format(F))              # fourth RITE (Rite = 2 Mites)
print("E3            : {:60.57}".format(E3))
print("E             : {:60.57}".format(E))
print("e3            : {:60.57}".format(e3))
print("T             : {:60.57}".format(E * T_factor**3))
print("S6            : {:60.57}".format(S6))
print("S3        ...


I am working on the file "CompoundFiveOctahedra.ipynb".
The first task is:
The S may be expressed in terms of phi-scaled versions of itself.
Can you write Python code for it?


I am working on the file "Compressed Sensing/IHT -- Compressed Sensing.ipynb".
The first task is:
Here, $\eta \approx 10^{-2}$ gives the best results.
For a larger value the signal is too sparse to fit the data well.
On the other hand, for smaller values we overfit the data to the noisy measurements.
In the following we will use noiseless measurements.
Constant IHT
First of all we will try iterative hard thresholding (IHT) with a constant stepsize $\mu = 1$.
In this case it can be proven that the algorithm converges provided $\Vert A \Vert_2 < 1$ [1].
Note that a rescaling of the design matrix $A$ can be compensated by rescaling the step size [2].
Due to our choice of normalization for $A$, we have that $\mu = 0.5$ will suffice with high probability.
Since we cannot expect that cIHT is as efficient w.r.t. the sample size as the basis pursuit denoising, we increase the number of measurements.
Can you write Python code for it?

import sys
sys.path.append('/Users/dsuess/Code/CS\ Algorithms/')

from csalgs.cs import iht
%autoreload 2

def cIHT(x, m, r, stepsize=1.0, rgen=np.random, sensingmat=None, x_init=None):
    A = sensingmat_gauss(m, len(x)) if sensingmat is None else sensingmat
    y = np.dot(A, x)
    x_hat = np.zeros(x.shape) if x_init is None else x_init
    while True:
        x_hat += stepsize * A.T.dot(y - A.dot(x_hat))
        compress(x_hat, r)
        yield x_hat

%debug

MEASUREMENTS = 50

for _ in Progress(range(1)):
    A = sensingmat_gauss(MEASUREMENTS, len(signal))
    y = A @ signal
    solution = iht.csIHT(A, y, 2 * NNZ, stepsize=iht.adaptive_stepsize())
    pl.plot([np.linalg.norm(signal - x_hat) for x_hat in it.islice(solution, 100)])

pl.xlabel = "\# iterations"
pl.ylabel = r"\Vert x - \hat x \Vert_2"


I am working on the file "Compressed Sensing/IHT -- Compressed Sensing.ipynb".
The first task is:
Note that the cIHT algorithm does not converge reliably even for a large number of iterations.
Even worse, the algorithm gets trapped for a finite amount of time.
This behavior is not good if one wants to check convergence by comparing two consecutive iteration steps.
Adaptive IHT
Can you write Python code for it?

SCALE_CONST = .5
KAPPA = 3.

assert KAPPA > 1 / (1 - SCALE_CONST)

def get_stepsize(A, g, supp):
    return norm(g[supp])**2 / norm(np.dot(A[:, supp], g[supp]))**2

def same_supports(supp1, supp2):
    return np.all(np.sort(supp1) == np.sort(supp2))

def compute_omega(x_np, x_n, A):
    diff = x_np - x_n
    return (1 - SCALE_CONST) * norm(diff)**2 / norm(A.dot(diff))**2

def get_update(A, x, y, supp, r):
    g = A.T.dot(y - A.dot(x))
    mu = norm(g[supp])**2 / norm(np.dot(A[:, supp], g[supp]))**2
    while True:
        x_new, supp_new = compression(x + mu * g, r, retsupp=True)
        if same_supports(supp, supp_new) or (mu < compute_omega(x_new, x, A)):
            return x_new, supp_new
        mu /= KAPPA * SCALE_CONST

def aIHT(x, m, r, rgen=np.random, sensingmat=None, x_init=None):
    A = sensingmat_gauss(m, len(x)) if sensingmat is None else sensingmat
    y = np.dot(A, x)

    x_hat = np.zeros(x.shape) if x_init is None else x_init
    _, supp = compression(A.T.dot(y), r, retsupp=True)

    while True:
        x_hat, supp = get_update(A, x_hat, y, supp, r)
        yield x_hat

DIM = 1000
NNZ = 25
MEASUREMENTS = 200

for _ in Progress(range(20)):
    signal = random_sparse_vector(DIM, NNZ)
    solution = aIHT(signal, MEASUREMENTS, int(2 * NNZ))
    pl.plot([np.linalg.norm(signal - x_hat) for x_hat in it.islice(solution, 250)])

pl.xlabel = "\# iterations"
pl.ylabel = r"\Vert x - \hat x \Vert_2"


I am working on the file "Compressed Sensing/IHT -- Compressed Sensing.ipynb".
The first task is:
The normalization of the sensing matrices $A$ is choosen in such a way that $\mathbb{E}\Vert A \Vert_2 = 1$ is independent of $m$ and $n$.
This allows us to normalize $A$ later to $\Vert A \Vert_2 < 1$ with high probability.
The latter condition is important for the convergence of the constant step-size IHT algorithm.
For the other approaches (convex programming or adaptive IHT), the normalization does not matter.
Convex Programming
The first question we will check is: "How many measurements do we need to recover the signal?".
For this purpose we will use basis pursuit denoising (the $\ell_1$-regularized least square estimator), which is very efficient in the number of samples.
On the other hand it does not scale well for large systems, due to the higher order polynomial scaling of the corresponding Second order cone program.
Can you write Python code for it?

def recover(x, m, eta=1.0, sigma=0.0, rgen=np.random):
    A = sensingmat_gauss(m, len(x), rgen)
    y = np.dot(A, x) + sigma / np.sqrt(len(x)) * rgen.randn(m)

    x_hat = cvx.Variable(len(x))
    objective = cvx.Minimize(cvx.norm(A * x_hat - y, 2)**2 + eta * cvx.norm(x_hat, 1))
    problem = cvx.Problem(objective, [])
    problem.solve()

    return np.ravel(x_hat.value)

def check(signal, sigma, rgen=np.random):
     return np.frompyfunc(lambda m, eta: np.linalg.norm(signal - recover(signal, m, eta, sigma, rgen)),
                          2, 1)

DIM = 100
NNZ = 5
SAMPLES = 20
MAX_MEASUREMENTS = 100
SIGMA = 0

signal = random_sparse_vector(DIM, NNZ)
ms, etas = np.meshgrid(np.linspace(1, MAX_MEASUREMENTS, 20), np.logspace(-4, 1, 20))

errors = [check(random_sparse_vector(DIM, NNZ), SIGMA)(ms, etas)
          for i in Progress(range(SAMPLES))]
errors = np.mean(errors, axis=0).reshape(ms.shape).astype('float64')

value = np.log(errors)
levels = np.linspace(np.min(value), np.max(value), 15)

pl.yscale('log')
pl.contourf(ms, etas, value, levels=levels)
pl.xlabel = r"m"
pl.ylabel = r"$\lambda$"
pl.colorbar()


I am working on the file "ComptonScattering/.ipynb_checkpoints/DataAndAnalysis-checkpoint.ipynb".
The first task is:
0. Calibrate MCA Channels to sources of known emission energy
Can you write Python code for it?

CS137Peaks = np.array([165.85]) #Channel Number of photopeak
CS137Energy = np.array([661.7]) #Accepted value of emission energy

BA133Peaks = np.array([21.59, 76.76, 90.52])
BA133Energy = np.array([81.0, 302.9, 356.0])

Mn54Peaks = np.array([207.72])
Mn54Energy = np.array([834.8])

Na22Peaks = np.array([128.84])
Na22Energy = np.array([511.0])

CO57Peaks = np.array([31.98])
CO57Energy = np.array([122.1])

Peaks = np.hstack([CS137Peaks,BA133Peaks,Mn54Peaks,Na22Peaks,CO57Peaks])

Energy = np.hstack([CS137Energy,BA133Energy,Mn54Energy,Na22Energy,CO57Energy])

plt.figure(figsize=(10,6));
plt.scatter(Peaks,Energy);

plt.xlabel('MCA Number',fontsize=20);
plt.ylabel('Energy (keV)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
#plt.savefig('Sample')

def myfun(N,a,b,c):
    ans = a + b*N + c*N**2  # this is y, "the function to be fit"
    return ans

p0 = [-2,1,0]

xlots = np.linspace(0,240)  # need lots of data points for smooth curve
yfit = np.zeros((len(Peaks),xlots.size))

plsq, pcov = curve_fit(myfun, Peaks, Energy, p0)  # curve fit returns p and covariance matrix
# these give the parameters and the uncertainties
a = plsq[0]
da = np.sqrt(pcov[0,0])
b = plsq[1]
db = np.sqrt(pcov[1,1])
c = plsq[2]
dc = np.sqrt(pcov[2,2])

yfit = myfun(xlots,plsq[0],plsq[1],plsq[2])  # use fit results for a, b, c

print('a = %.7f +/- %.7f' % (plsq[0], np.sqrt(pcov[0,0])))
print('b = %.7f +/- %.7f' % (plsq[1], np.sqrt(pcov[1,1])))
print('c = %.7f +/- %.7f' % (plsq[2], np.sqrt(pcov[2,2])))

plt.figure(figsize=(10,6));
plt.scatter(Peaks,Energy);
plt.xlim(0,240)
plt.ylim(0,1000)
plt.xlabel('x (mm)');
plt.ylabel('y (mm)');
plt.plot(xlots,yfit);
plt.legend(['data','Fit'],loc='lower right');
plt.text(5,900,'a = %.1f +/- %.1f keV' % (plsq[0], np.sqrt(pcov[0,0])),size=17)
plt.text(5,800,'b = %.2f +/- %.2f keV MCA$^{-1}$' % (plsq[1], np.sqrt(pcov[1,1])),size=17)
plt.text(5,700,'c = %.1f +/- %.1f keV MCA$^{-2}$' % (plsq[2]*1e3, np.sqrt(pcov[2,2])*1e3),size=17)
plt.xlabel('MCA Number',fontsize=20);
plt.ylabel('Energy...


I am working on the file "ComptonScattering/.ipynb_checkpoints/DataAndAnalysis-checkpoint.ipynb".
The first task is:
1. Test how the energy of scattered atoms varies with scattering angle
Can you write Python code for it?

N = np.array([102.20, 85.85, 121.57, 140.34, 127.77, 115.69]) #Photopeak channel of scattered rays
dN = np.array([5.37, 8.01, 5.13, 5.54, 8.91, 5.5]) #Uncertainty in channel number
theta = np.array([60, 75, 45, 30, 40, 50])*np.pi/180 #Scattering angle entered in degrees converted to radians afterwords

def deltaE(N,dN):
    daN = np.sqrt((da/a)**2 + (dN/N)**2)*(a*N)

    dbN2 = np.sqrt((db/b)**2 + 4*(dN/N)**2)*(b*N**2)

    dcN3 = np.sqrt((dc/c**2) + 9*(dN/N)**2)*(c*N**3)

    dEMeas = np.sqrt(daN**2 + dbN2**2 + dcN3**2)*1e-3 #Convert to KeV

    return dEMeas

EMeas = myfun(N,a,b,c)
EMeas

dEMeas = deltaE(N,dN)
dEMeas

Eo = 661.7 #Initial keV energy of gamma rays (before scattering)
mc2 = 511 #electron mass in keV

def ECompton(Eo,mc2,theta):
    return Eo/(1+(Eo/mc2)*(1-np.cos(theta)))

EComp = ECompton(Eo,mc2,theta)
EComp

thetas = np.linspace(0,np.pi,50);

plt.figure(figsize=(10,6));
plt.plot(thetas,ECompton(Eo,mc2,thetas),label='Compton');
plt.errorbar(theta,EMeas,yerr = dEMeas,fmt='none');
plt.scatter(theta,EMeas,label='Measured',color='k');
plt.legend();

plt.xlabel('Scattering Angle [Radians]',fontsize=20);
plt.ylabel('Final Energy (keV)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.xlim(0,np.pi);
plt.savefig('ComptonEnergy')


I am working on the file "ComptonScattering/.ipynb_checkpoints/DataAndAnalysis-checkpoint.ipynb".
The first task is:
2. Use (1) to determine keV mass of electron
Can you write Python code for it?

y = np.array([1/entry for entry in EMeas])
dy = np.array([dEMeas[i]/EMeas[i]**2 for i in np.arange(len(EMeas))])

x = np.array([1-np.cos(entry) for entry in theta])

plt.figure(figsize=(10,6));
plt.scatter(x + 1/Eo,y);
plt.errorbar(x + 1/Eo,y,dy,fmt='none')

plt.xlabel('(1-cos(theta))',fontsize=20);
plt.ylabel('(1/Ef)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.ylim(0.0015,0.0035);

def myfun2(x,mc2):
    # x = (1-np.cos(theta))
    return 1/Eo + (1/mc2)*x

p02 = [511]

xlots2 = np.linspace(0,1)  # need lots of data points for smooth curve
yfit = np.zeros((len(Peaks),xlots2.size))

plsq, pcov = curve_fit(myfun2, np.array([1-np.cos(entry) for entry in theta]), np.array([1/entry for entry in EMeas]), p02)  # curve fit returns p and covariance matrix
# these give the parameters and the uncertainties
mc2Meas = plsq[0]
dmc2Meas = np.sqrt(pcov[0,0])

yfit2 = myfun2(xlots2,plsq[0])  # use fit results for a, b, c

print('mc2Meas = (%.1f +/- %.1f) keV/c2' % (plsq[0], np.sqrt(pcov[0,0])))

plt.figure(figsize=(10,6));
plt.scatter(x + 1/Eo,y,label='Measured');
plt.errorbar(x + 1/Eo,y,dy,fmt='none')
plt.plot(xlots2,yfit2,label='Fit')
plt.legend(loc='upper left')

plt.xlabel('(1-cos(theta))',fontsize=20);
plt.ylabel('(1/$E_f$)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.ylim(0.0015,0.0031);
plt.xlim(0,0.81)
plt.text(0.01,0.0027,'$mc^2$ = (%.0f +/- %.0f) keV/$c^2$' % (plsq[0], np.sqrt(pcov[0,0])),size=17)
plt.savefig('ElectronMass')


I am working on the file "ComptonScattering/.ipynb_checkpoints/DataAndAnalysis-checkpoint.ipynb".
The first task is:
3. Which of Thomson and Klein-Nishina differential cross section is a better description?
Can you write Python code for it?

EMeas #For determining efficiency from manual

Counts = np.array([2446, 1513, 3357, 3231, 1285, 1944])

#This is the detector efficiency which is a function of the incoming gamma energy (EMeas)
e = np.array([0.6, 0.67, 0.52, 0.475, 0.51, 0.55])

Counts = np.array([Counts[i]/e[i] for i in np.arange(len(Counts))])
unc = np.array([np.sqrt(entry) for entry in Counts])

Time = np.array([1531.76, 1952.72, 1970.43, 629.12, 663.42, 750.65])
Rates = np.array([Counts[i]/Time[i] for i in np.arange(len(Counts))])
unc = np.array([unc[i]/Time[i] for i in np.arange(len(Counts))])

def Thomson(theta):
    ro = 2.82*1e-15
    return (1/2)*(ro**2)*(1+np.cos(theta)**2)*1.20e30 #set b = 1

def KleinNishina(theta):
    ro = 2.82*1e-15
    gamma = Eo/mc2

    return (1/2)*(ro**2)*(1+np.cos(theta)**2)*((1+gamma*(1-np.cos(theta)))**(-2))*(1+((gamma*(1-np.cos(theta)))**2)/((1+np.cos(theta)**2)*(1+gamma*(1-np.cos(theta)))))*1.20e30

thetas = np.linspace(0,np.pi/2,50);

plt.figure(figsize=(10,6));
plt.plot(thetas,Thomson(thetas),label='Thomson');
plt.plot(thetas,KleinNishina(thetas),label='Klein-Nishina');
plt.scatter(theta,Rates,label='Measured',marker = '.',color='red')
plt.errorbar(theta,Rates,unc,fmt='none')
plt.legend();

plt.xlabel('Scattering Angle [Radians]',fontsize=20);
plt.ylabel('Count Rate [$s^{-1}$]',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.xlim(0,np.pi/2);
plt.savefig('ThomsonKleinNishina')


I am working on the file "ComptonScattering/DataAndAnalysis.ipynb".
The first task is:
0. Calibrate MCA Channels to sources of known emission energy
Can you write Python code for it?


I am working on the file "ComptonScattering/DataAndAnalysis.ipynb".
The first task is:
2. Use (1) to determine keV mass of electron
Can you write Python code for it?

y = np.array([1/entry for entry in EMeas])
dy = np.array([dEMeas[i]/EMeas[i]**2 for i in np.arange(len(EMeas))])

x = np.array([1-np.cos(entry) for entry in theta])

plt.figure(figsize=(10,6));
plt.scatter(x + 1/Eo,y);
plt.errorbar(x + 1/Eo,y,dy,fmt='none')

plt.xlabel('(1-cos(theta))',fontsize=20);
plt.ylabel('(1/Ef)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.ylim(0.0015,0.0035);

def myfun2(x,mc2):
    # x = (1-np.cos(theta))
    return 1/Eo + (1/mc2)*x

p02 = [511]

xlots2 = np.linspace(0,1)  # need lots of data points for smooth curve
yfit = np.zeros((len(Peaks),xlots2.size))

plsq, pcov = curve_fit(myfun2, np.array([1-np.cos(entry) for entry in theta]), np.array([1/entry for entry in EMeas]), p02)  # curve fit returns p and covariance matrix
# these give the parameters and the uncertainties
mc2Meas = plsq[0]
dmc2Meas = np.sqrt(pcov[0,0])

yfit2 = myfun2(xlots2,plsq[0])  # use fit results for a, b, c

print('mc2Meas = (%.1f +/- %.1f) keV/c2' % (plsq[0], np.sqrt(pcov[0,0])))

plt.figure(figsize=(10,6));
plt.scatter(x + 1/Eo,y,label='Measured');
plt.errorbar(x + 1/Eo,y,dy,fmt='none')
plt.plot(xlots2,yfit2,label='Fit')
plt.legend(loc='upper left')

plt.xlabel('(1-cos(theta))',fontsize=20);
plt.ylabel('(1/$E_f$)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.ylim(0.0015,0.0031);
plt.xlim(0,0.81)
plt.text(0.01,0.0027,'$mc^2$ = %.0f +/- %.0f keV' % (plsq[0], np.sqrt(pcov[0,0])),size=17)
plt.savefig('ElectronMass')


I am working on the file "ComptonScattering/Day1.ipynb".
The first task is:
1
Can you write Python code for it?

plt.figure(figsize=(10,6));
plt.scatter(Peaks,Energy);
plt.xlim(0,240)
plt.ylim(0,1000)
plt.xlabel('x (mm)');
plt.ylabel('y (mm)');
plt.plot(xlots,yfit);
plt.legend(['data','Fit'],loc='lower right');
plt.text(5,900,'a = %.3f +/- %.3f keV' % (plsq[0], np.sqrt(pcov[0,0])),size=17)
plt.text(5,800,'b = %.3f +/- %.3f keV MCA$^{-1}$' % (plsq[1], np.sqrt(pcov[1,1])),size=17)
plt.text(5,700,'c = (%.4f +/- %.4f)$\cdot 10^{-3}$ keV MCA$^{-2}$' % (plsq[2]*1e3, np.sqrt(pcov[2,2])*1e3),size=17)
plt.xlabel('MCA Number',fontsize=20);
plt.ylabel('Energy (keV)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.savefig('LinearMCAFit')

def deltaE(N,dN):
    daN = np.sqrt((da/a)**2 + (dN/N)**2)*(a*N)

    dbN2 = np.sqrt((db/b)**2 + 4*(dN/N)**2)*(b*N**2)

    dcN3 = np.sqrt((dc/c**2) + 9*(dN/N)**2)*(c*N**3)

    dEMeas = np.sqrt(daN**2 + dbN2**2 + dcN3**2)*1e-3 #Convert to KeV

    return dEMeas

N = np.array([102.40]) #Channel number of 60 degree scattered photopeak
dN = np.array([9.00])
theta = np.array([60])*np.pi/180

EMeas = myfun(N,a,b,c)
EMeas

dEMeas = deltaE(N,dN)
dEMeas

Eo = 661.7 #Initial keV energy of gamma rays (before scattering)
mc2 = 511 #electron mass in keV

def ECompton(Eo,mc2,theta):
    return Eo/(1+(Eo/mc2)*(1-np.cos(theta)))

EComp = ECompton(Eo,mc2,theta)
EComp


I am working on the file "ComptonScattering/Day1.ipynb".
The first task is:
2

Test how the energy of scattered atoms varies with scattering angle
Use (1) to determine keV mass of electron
Which of Thomson and Klein-Nishina differential cross section is a better description?
Can you write Python code for it?

thetas = np.linspace(-np.pi,np.pi,50);

plt.figure(figsize=(10,6));
plt.plot(thetas,ECompton(Eo,mc2,thetas),label='Compton');
plt.errorbar(theta,EMeas,dEMeas);
plt.scatter(theta,EMeas,dEMeas,label='Measured');
plt.legend();

plt.xlabel('Scattering Angle [Radians]',fontsize=20);
plt.ylabel('Final Energy (keV)',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.xlim(-np.pi,np.pi);
#plt.savefig('Sample')

def Thomson(theta):
    ro = 2.82*1e-15
    return (1/2)*(ro**2)*(1+np.cos(theta)**2) #set b = 1

def KleinNishina(theta):
    ro = 2.82*1e-15
    gamma = Eo/mc2

    return (1/2)*(ro**2)*(1+np.cos(theta)**2)*((1+gamma*(1-np.cos(theta)))**(-2))*(1+((gamma*(1-np.cos(theta)))**2)/((1+np.cos(theta)**2)*(1+gamma*(1-np.cos(theta)))))

thetas = np.linspace(-np.pi,np.pi,50);

plt.figure(figsize=(10,6));
plt.plot(thetas,Thomson(thetas),label='Thomson');
plt.plot(thetas,KleinNishina(thetas),label='Klein-Nishina');
plt.legend();

plt.xlabel('Scattering Angle [Radians]',fontsize=20);
plt.ylabel('Differential Cross section',fontsize = 20);
plt.xticks(size = 13);
plt.yticks(size = 13);
plt.xlim(-np.pi,np.pi);
#plt.savefig('Sample')


I am working on the file "Computacion/Verano-2019/clase_de_notebooks/Analisis de artistas.ipynb".
The first task is:
Extra
Hay una forma sencilla de armar canciones nuevas de un artista usando cosas que vimos. Si bien es una solucion "burda", las soluciones mas sofisticadas siguen la misma idea
Can you write Python code for it?

import csv

data = {}

authors =  ["ABBA"]

with open("songdata.csv") as file:
    for author,_,_,lyric in csv.reader(file):

        if author not in authors:
            continue

        prev = ""
        for word in lyric.lower().split():
            new_word = word
            while new_word and not new_word[-1].isalpha():
                new_word = new_word[:-1]

            data[prev] = data.get(prev,[])
            data[prev].append(new_word)

            prev = new_word

            if not word[-1].isalpha():
                data[prev] = data.get(prev,[])
                data[prev].append(word[-1])

                prev = word[-1]

        data[prev] = data.get(prev,[])
        data[prev].append("")


I am working on the file "Computacion/Verano-2019/clase_de_notebooks/Analisis de artistas.ipynb".
The first task is:
Incluso para ser algo rapido, alguna clase de sentido tiene. Si le queremos dar mas sentido, deberiamos analizar mas que la palabra anterior, por ejemplo las 2 anteriores, y eso deberia mejorar
Can you write Python code for it?

import csv

data = {}

authors =  ["ABBA"]

with open("songdata.csv") as file:

    prev = ("","")
    for author,_,_,lyric in csv.reader(file):

        if author not in authors:
            continue

        for word in lyric.lower().split():
            new_word = word

            if not word[0].isalpha():
                data[prev] = data.get(prev,[])
                data[prev].append(word[0])

                prev = (prev[-1],word[0])

            while new_word and not new_word[0].isalpha():
                new_word = new_word[1:]

            while new_word and not new_word[-1].isalpha():
                new_word = new_word[:-1]

            data[prev] = data.get(prev,[])
            data[prev].append(new_word)

            prev = (prev[-1],new_word)

            if not word[-1].isalpha():
                data[prev] = data.get(prev,[])
                data[prev].append(word[-1])

                prev = (prev[-1],word[-1])

        data[prev] = data.get(prev,[])
        data[prev].append("")
        prev = (prev[-1],"")

cancion = []
prev = ("","")
for _ in range(100):
    next_word = random.choice(data[prev])
    cancion.append(next_word)
    prev = (prev[-1],next_word)

display(Markdown("_" + " ".join(cancion) + "_") )


I am working on the file "Computacion/Verano-2019/clase_de_notebooks/Analisis de artistas.ipynb".
The first task is:
Lo que hice es armar un diccionario con las palabras de las canciones, y a cada una asociarle una lista con todas las palabras que aparecen despues de esa. Al ser una lista con repeticiones, si elijo una palabra al azar, es mas probable que elija una palabra que aparece mas seguido que otras. Entonces, al igual que con el predictivo, puedo armar una cancion de ABBA asi:
Can you write Python code for it?

cancion = []
prev = ""
for _ in range(100):
    next_word = random.choice(data[prev])
    cancion.append(next_word)
    prev = next_word

display(Markdown("_" + " ".join(cancion) + "_") )


I am working on the file "Computacion/Verano-2019/clase_de_notebooks/Analisis de artistas.ipynb".
The first task is:
Pruebo que tanto se parecen algunos artistas al azar. Voy a necesitar markdown para que se vea mas lindo, asi que puedo importar la funcion para mostrarlo directamente desde el output:
Can you write Python code for it?

from IPython.display import display, Markdown, Latex

import random

artists = list(data.keys())

artist_a = random.choice(artists)
artist_b = random.choice(artists)
diference = utilidades_diccionarios.calcular_distancia(data[artist_a],data[artist_b],2)

display(Markdown( f'Diferencia entre *{artist_a}* y _{artist_b}_ es: **{diference}** '))

artist_a = random.choice(artists)
artist_b = random.choice(artists)
diference = utilidades_diccionarios.calcular_distancia(data[artist_a],data[artist_b],2)

display(Markdown( f'Diferencia entre *{artist_a}* y _{artist_b}_ es: **{diference}** '))

artist_a = random.choice(artists)
artist_b = random.choice(artists)
diference = utilidades_diccionarios.calcular_distancia(data[artist_a],data[artist_b],2)

display(Markdown( f'Diferencia entre *{artist_a}* y _{artist_b}_ es: **{diference}** '))

artist_a = random.choice(artists)
artist_b = random.choice(artists)
diference = utilidades_diccionarios.calcular_distancia(data[artist_a],data[artist_b],2)

display(Markdown( f'Diferencia entre *{artist_a}* y _{artist_b}_ es: **{diference}** '))

artist_a = random.choice(artists)
artist_b = random.choice(artists)
diference = utilidades_diccionarios.calcular_distancia(data[artist_a],data[artist_b],2)

display(Markdown( f'Diferencia entre *{artist_a}* y _{artist_b}_ es: **{diference}** '))