I am working on the file "Homework/04 - Applied ML/Homework04_Referees_teamawesome_Q2.ipynb".
The first task is:
Player position doesn't have much impact either. We can try to remove the number of games, but it won't make sense: some player will have an absolute higher number of cards, only because they played a lot more games. But we will lost this information.
Can you write Python code for it?

x_noGameNumber = x.drop(['games'], 1)
model = KMeans(n_clusters=2)
model = model.fit(x_noGameNumber)
score_noGameNumber = silhouette_score(x_noGameNumber, model.labels_)
score_noGameNumber

score_noGameNumber / score


I am working on the file "Homework/04 - Applied ML/Homework04_Referees_teamawesome_Q2.ipynb".
The first task is:
Seems like removing skin color from the input didn't change anything for the clustering performance !
Let's do this with removing another parameter: position.
Can you write Python code for it?

x_noPosition = x.drop(['position'], 1)
model = KMeans(n_clusters=2)
model = model.fit(x_noPosition)
score_noPosition= silhouette_score(x_noPosition, model.labels_)
score_noPosition

score_noPosition / score


I am working on the file "Homework/04 - Applied ML/Homework04_Referees_teamawesome_Q2.ipynb".
The first task is:
So, do we have any new information ? What can we conclude of this ?
We can use the "silhouette score", which is a metric showing if the two clusters are well separated. It it's equals to 1, the clusters are perfectly separated, and if it's 0, the clustering doesn't make any sense.
Can you write Python code for it?

score = silhouette_score(x, model.labels_)
score


I am working on the file "Homework/04 - Applied ML/Homework04_Referees_teamawesome_Q2.ipynb".
The first task is:
We got a silhouette score of 58%, which is honestly not enough to predict precisely the skin color of new players. A value closer to +1 would have indicated with higher confidence a difference between the clusters. 60% is enough to distinguish the two clusters but, still, we cannot rely on this model.
Let's try to remove features iterately, starting with skin color.
Can you write Python code for it?

x_noSkinColor = x.drop(['skinColor'], 1)
model = KMeans(n_clusters=2)
model = model.fit(x_noSkinColor)
score_noSkinColor = silhouette_score(x_noSkinColor, model.labels_)
score_noSkinColor

score_noSkinColor / score


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
1) Peeking into the Data
Can you write Python code for it?


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
3) Create the Training and Testing Datframes with only select data
Can you write Python code for it?

# Removing columns that we do not need
Data_Simple1 = Data_OneGamePerRow[['playerShort', 'yellowCards', 'yellowReds', 'redCards',
                              'refNum', 'refCountry', 'games', 'position', 'mean_rater']]

# Take a random 80% sample of the Data for the Training Sample
#Data_Training = Data_Simple1.sample(frac=0.8)

# Take a random 20% sample of the Data for the Testing Sample
#Data_Testing = Data_Simple1.loc[~Data_Simple1.index.isin(Data_Training.index)]

Data_Simple1

#find proportion of yellow & red cards to games
Data_Simple1['fractionYellow'] = Data_Simple1['yellowCards']/Data_Simple1['games']
Data_Simple1['fractionYellowRed'] = Data_Simple1['yellowReds']/Data_Simple1['games']
Data_Simple1['fractionRed'] = Data_Simple1['redCards']/Data_Simple1['games']
Data_Simple2 = Data_Simple1[['playerShort', 'fractionYellow', 'fractionYellowRed', 'fractionRed',
                              'refNum', 'refCountry', 'games', 'position', 'mean_rater']]
Data_Simple2

allpositions = (Data_Simple2['position'])
unique_pos = set(allpositions)
unique_pos_list = list(unique_pos)

unique_pos_list

# we must convert players positions into proxy numbers (floats) to run random forest
position_proxy = []
A = len(allpositions)
for i in range (0,A):
        if allpositions[i] == 'NaN':
            position_proxy.append(0);
        elif allpositions[i] == 'Center Midfielder':
            position_proxy.append(1);
        elif allpositions[i] == 'Attacking Midfielder':
            position_proxy.append(2);
        elif allpositions[i] == 'Goalkeeper':
            position_proxy.append(3);
        elif allpositions[i] == 'Right Winger':
            position_proxy.append(4);
        elif allpositions[i] == 'Left Winger':
            position_proxy.append(5);
        elif allpositions[i] == 'Center Forward':
            position_proxy.append(6);
        elif allpositions[i] == 'Right Fullback':
            position_proxy.append(7);
        elif allpositions[i] == 'Right Midfielder':
            position_proxy.append(8);
   ...


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
II. Preparing the training & test data : Fraction version
1) Create the Training and Testing Datframes with only select data
Can you write Python code for it?

#create test and training matrix

cols = ['games', 'fractionYellow', 'fractionYellowRed', 'fractionRed', 'refNum', 'refCountry', 'position_proxy']
exclude = ['raterScale','mean_rater', 'playerShort']
colsRes1 = ['raterScale']

# Take a random 80% sample of the Data for the Training Sample
Data_Training = Data_Simple5.sample(frac=0.8)

# Need to split this into the data and the results columns
# http://stackoverflow.com/questions/34246336/python-randomforest-unknown-label-error
Input_Data_Training = Data_Training.drop(exclude, axis=1)

#Results_Data_Training = list(Data_Training.raterAvg.values)
Results_Data_Training = Data_Training[colsRes1]
Input_Data_Training.head()

# Take a random 20% sample of the Data for the Testing Sample
#Data_Testing = Data_Simple1.loc[~Data_Simple1.index.isin(Data_Training.index)]

# Need to split this into the data and the results columns
# http://stackoverflow.com/questions/34246336/python-randomforest-unknown-label-error
#Input_Data_Testing = Data_Testing.drop(colsRes, axis=1)
#Results_Data_Testing = list(Data_Testing.raterAvg.values)

# Need to make arrays
# http://www.analyticbridge.com/profiles/blogs/random-forest-in-python
trainArr = Input_Data_Training.as_matrix() #training array
#trainRes = Results_Data_Training.as_matrix(colsRes) #training results
trainRes_1 = Data_Training['raterScale'].values
trainArr


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
Let's now disaggregate the games:
Can you write Python code for it?

game_counter = 0
game_total_number = sum(Data_hasImage['games'])
# Raw table that we'll have to convert to a dataframe later
output = [0 for i in range(game_total_number)]

# We now iterate each row of our dataframe, which may contains more that one game
for i, row in Data_hasImage.iterrows():
    # Number of games in the current row
    row_game_number = row['games']
    # Number of cumulated cards for the games in the current row
    yellowCards = row['yellowCards']
    yellowReds = row['yellowReds']
    redCards = row['redCards']
    # We want to seperate each of these games
    for j in range (row_game_number):
        game = row
        game['yellowCards'] = 0
        game['yellowReds'] = 0
        game['redCards'] = 0
        # Basically, we distribute the cards we have on separate games.
        # ie: if we have 2 yellowCard and 1 redCard for a total of 4 games,
        # the first two games will be assigned a yellowCard,
        # the third game will be assigned a redCard,
        # and the last game won't have any card assigned, because there is no card left.
        if yellowCards > 0:
            game['yellowCards'] = 1
            yellowCards = yellowCards - 1
        elif yellowReds > 0:
            game['yellowReds'] = 1
            yellowReds = yellowReds - 1
        elif redCards > 0:
            game['redCards'] = 1
            redCards = redCards - 1

        # Convert from pandas Series to prevent overwriting previous values of the output
        gamelist=list(game)
        # Add the new game to the output
        output[game_counter] = gamelist
        game_counter = game_counter + 1

# Here is the output dataframe

Data_OneGamePerRow = pd.DataFrame(output, columns=list(Data_hasImage.columns))
Data_OneGamePerRow


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
The most important feature in this case is refNum, games, refCountry, position_proxy
Alternatively we can see what happens when we only use the number of cards...
Can you write Python code for it?

exclude4 = ['raterScale','mean_rater', 'playerShort', 'refNum', 'refCountry', 'games', 'position_proxy']
exclude5 = ['raterScale','mean_rater', 'playerShort', 'refNum', 'refCountry', 'games', 'position_proxy', 'predictions', 'predictions2']
Input_Data_Training3 = Data_Training.drop(exclude4, axis=1)
trainArr3 = Input_Data_Training3.as_matrix() #training array
trainRes_3 = Data_Training['raterScale'].values

Input_Data_Testing3 = Data_Testing.drop(exclude5, axis=1)
testArr3 = Input_Data_Testing3.as_matrix()

testArr3

#Re-Initialize Classifier
forest = RandomForestClassifier(n_estimators = 100)

# Fit the training data and create the decision trees
forest = forest.fit(trainArr3,trainRes_3)

# Take the same decision trees and run it on the test data
results3 = forest.predict(testArr3)

Data_Testing['predictions3'] = results3
Data_Testing.head()

#see percentage of right predictions
correct = list(Data_Testing[Data_Testing['raterScale'] == Data_Testing['predictions3']].index)
A = len(correct)
percCorrect = A/Data_Testing['raterScale'].size
percCorrect


I am working on the file "Homework/04 - Applied ML/Homework_04_Referees_teamawesome-Q1 + Bonus.ipynb".
The first task is:
redCountry, Games, Position, and redNum are the most important features. We could therefore drop some features already, such as fraction yellow and fraction yellowRed & fraction Red. Let us delete all cards and see if we can better predict this.
Can you write Python code for it?

#make necessary changes to parameters
exclude2 = ['raterScale','mean_rater', 'playerShort', 'fractionYellowRed', 'fractionRed', 'fractionYellow']
exclude3 = ['raterScale','mean_rater', 'playerShort', 'fractionYellowRed', 'fractionRed', 'fractionYellow', 'predictions']
Input_Data_Training2 = Data_Training.drop(exclude2, axis=1)
trainArr2 = Input_Data_Training2.as_matrix() #training array
trainRes_2 = Data_Training['raterScale'].values

Input_Data_Testing2 = Data_Testing.drop(exclude3, axis=1)
testArr2 = Input_Data_Testing2.as_matrix()

testArr2

#Re-Initialize Classifier
forest = RandomForestClassifier(n_estimators = 100)

# Fit the training data and create the decision trees
forest = forest.fit(trainArr2,trainRes_2)

# Take the same decision trees and run it on the test data
results2 = forest.predict(testArr2)

Data_Testing['predictions2'] = results2
Data_Testing.head()

#see percentage of right predictions
correct = list(Data_Testing[Data_Testing['raterScale'] == Data_Testing['predictions2']].index)
A = len(correct)
percCorrect = A/Data_Testing['raterScale'].size
percCorrect


I am working on the file "Homework/05 - Taming Text/HW05.ipynb".
The first task is:
By reading a few emails we can see that the extracted body text is just the text that the email sender wrote (as stated on Kaggle) while the raw text gathers the previous emails forwarded or the whole discussion. Note that the extracted body text can sometimes contain NaNs. By including repeated messages in the raw text, you induce bias in the distribution of the words, thus we kept only the body text
1. Worldclouds
Can you write Python code for it?

# raw corpus
text_corpus = emails.ExtractedBodyText.dropna().values
raw_text = ' '.join(text_corpus)

# generate wordcloud
wordcloud = WordCloud().generate(raw_text)
plt.figure(figsize=(15,10))
plt.imshow(wordcloud)
plt.axis('off');

def preprocess(text, stemmer):
    print('Length of raw text: ', len(raw_text))

    # tokenization (need to install models/punk from nltk.download())
    tokens = nltk.word_tokenize(raw_text, language='english')
    print('Number of tokens extracted: ', len(tokens))

    # stopwords removal (need to install stopwords corpus in corpora/stopwords)
    # cach stopwords to improve performance (70x speedup)
    cached_stopwords = set(stopwords.words('english'))
    filtered_tokens = [word for word in tokens if word not in cached_stopwords]
    print('Number of tokens after stopword removal: ', len(filtered_tokens))

    # stemming
    if stemmer == 'snowball':
        stemmer = nltk.SnowballStemmer('english')
    elif stemmer == 'porter':
        stemmer = nltk.PorterStemmer('english')
    else:
        print('choose appropriate stemmer')
    stemmed_filtered_tokens = [stemmer.stem(t) for t in filtered_tokens]

    # dump array in text file
    output = ' '.join(stemmed_filtered_tokens)
    with open("preprocessed_text.txt", "w") as text_file:
        text_file.write(output)

preprocess(raw_text, 'snowball')

preprocessed_text = open('preprocessed_text.txt').read()
wordcloud2 = WordCloud().generate(preprocessed_text)
plt.figure(figsize=(15,10))
plt.imshow(wordcloud2)
plt.axis('off');


I am working on the file "Homework/05 - Taming Text/HW05.ipynb".
The first task is:
Comparison between the word clouds
Looking at the wordcloud generated after having preprocessed the data, it seems that stemming hurt the "performance" of the wordcloud, indeed a number of words have been incorrectly stemmed e.g. department has been reduced to depart, secretary to secretary, message to messag and so on.
2. Sentiment analysis
from this link,we added the following words to be removed from the emails:
* add "RE" because the iso3 code for Reunion islands.. but it appears a lot in emails to indicate the RE(sponses) to previous emails.
* FM
* TV is ISO2 code for Tuvalu but also refers to Television
* AL is a given name and also ISO2 for Albania
* BEN is a given name and also ISO3 for Benin
* LA is Los angeles and iso 2 for Lao
* AQ is abbreviation of "As Quoted" and iso 2 for Antarctica
After a few runs, we looked at the (unusual) countries extracted. For example the country Saint Pierre and Miquelon is mentionned 631 times, not bad for such a small country. We noticed that an important number of emails have words capitalized and are misinterpreted as ISO2/ISO3 codes for countries. To cope with this we added the following stop words:
* AND is ISO3 for Andorra
* AM is ISO2 for Armenia
* AT is ISO2 for Austria
* IN is ISO2 for India
* NO is ISO2 for Norway
* PM is iSO2 for Saint Pierre and Miquelon
* TO is ISO2 for Tonga
* BY is ISO2 for Belarus
* IE is ISO2 for Ireland (id est)
* IT is ISO2 for Italy
* MS is ISO2 for Montserrat
Can you write Python code for it?

def find_countries(tokens):
    # find countries in a list of token
    countries = []
    for token in tokens:
        try:
            # search for any alpha_2 country name e.g. US, CH
            country = pycountry.countries.get(alpha_2=token)
            countries.append(country.name)
        except KeyError:
            try:
                # search for any alpha_3 country name e.g. USA, CHE
                country = pycountry.countries.get(alpha_3=token)
                countries.append(country.name)
            except KeyError:
                try:
                    # search for a country by its name, title() upper cases every first letter but lower cases
                    # the other, hence it is handled last, but it deals with country written in lower case
                    country = pycountry.countries.get(name=token.title())
                    countries.append(country.name)
                except KeyError: pass
    return list(set(countries))

def foreign_policy(emails, sentiment_analyzer):
    start_time = time.time()
    words_to_be_removed = ["RE", "FM", "TV", "LA", "AL", "BEN", "AQ", "AND", "AM", "AT", "IN", "NO", "PM", "TO",
                          "BY", "IE", "IT", "MS"]
    vader_analyzer = SentimentIntensityAnalyzer()
    foreign_policy = {}
    cached_stopwords = set(stopwords.words('english'))
    cached_stopwords.update(words_to_be_removed)
    i=0

    for email in emails: # TODO: regex instead of tokens lookup parce que ca prend trop de teeeeemps
        #print('{:d} / {:d} emails processed'.format(i, len(emails)))
        tokens = nltk.word_tokenize(email, language='english')
        tokens = [word for word in tokens if word not in cached_stopwords]
        # country lookup in tokens
        countries = find_countries(tokens)
        i +=1
        if not countries: continue

        if sentiment_analyzer =='vader':
            sentiment = vader_analyzer.polarity_scores(email)
            score = sentiment['compound']
        #elif sentiment_analyzer ==''
...


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q2.ipynb".
The first task is:
Create list of countries
Can you write Python code for it?

countries_cited = []
for emails in emails_final['TokenizedText']:
    for word in emails:
        try:
            country_name = pycountry.countries.get(alpha_2=word)
            countries_cited.append(country_name.name)
        except KeyError:
            try:
                country_name = pycountry.countries.get(alpha_3=word)
                countries_cited.append(country_name.name)
            except KeyError:
                try:
                    country = pycountry.countries.get(name=word)
                    countries_cited.append(country_name.name)
                except KeyError: pass


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q2.ipynb".
The first task is:
Now we check sentiment on emails around these names
Can you write Python code for it?

sentiments = []
vader_analyzer = SentimentIntensityAnalyzer()

size = len(Country_Sent['Alpha_2'])
for i in range(1,size):
    country_score =[]
    for email in emails_no_stop['TokenizedText']:
        if Country_Sent['Alpha_2'][i] in email or Country_Sent['Alpha_3'][i] in email or Country_Sent['Country'][i] in email:
            str_email = ' '.join(email)
            sentiment = vader_analyzer.polarity_scores(str_email)
            score = sentiment['compound']
            country_score.append(score)
        else: pass
    if len(country_score)!=0:
        sentiment_score = sum(country_score) / float(len(country_score))
        sentiments.append(sentiment_score)
    else:
        sentiments.append(999)

sentiments

#error in iteration, must drop NZ because it was not taken into account in the sentiments analysis
Country_Sent = Country_Sent.drop(Country_Sent.index[[0]])

len(Country_Sent)

#add sentiment list to data frame
Country_Sent['Sentiment'] = sentiments
Country_Sent.head()

#delete any row with sentiment value of 999
Country_Sent = Country_Sent[Country_Sent['Sentiment'] != 999]
Country_Sent.head()

#reorder dataframe in ascending order of sentiment
Country_Sent.sort_values(['Sentiment'], ascending=True, inplace=True)
Country_Sent.head()

#reorder index
Country_Sent = Country_Sent.reset_index(drop=True)

Country_Sent.head()


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q2.ipynb".
The first task is:
Now we make a color gradient for the histogram
Can you write Python code for it?

#We must normalize the sentiment scores and create a gradient based on that (green, blue & red gradient)
#first we sort the ones that are below zero, than the ones above zero
color_grad = []
size = len(Country_Sent['Sentiment'])

for i in range(0,size):
    if Country_Sent['Sentiment'][i] < 0:
        high = 0
        low = np.min(sentiments)
        rg = low-high
        new_entry = (low-Country_Sent['Sentiment'][i])/rg
        red = 1 - new_entry
        color_grad.append((red,0,0))
    else:
        high = np.max(sentiments)
        low = 0
        rg2 = high-low
        new_entry = (Country_Sent['Sentiment'][i]-low)/rg2
        green = 1 - new_entry
        color_grad.append((0,green,0))

Country_Sent['color_grad'] = color_grad
Country_Sent.head()

#Now we create the bar plot based on this palette
import seaborn as sns
plt.figure(figsize=(30,20))
plot = sns.barplot(x='Country', y='Sentiment', data=Country_Sent, orient='vertical', palette=color_grad)
plt.ylabel('Country Sentiment');
plt.show()

#Now we create a bar plot with an automatic gradient based on sentiment
size = len(Country_Sent['Sentiment'])
plt.figure(figsize=(30,20))
grad = sns.diverging_palette(10, 225, n=32)
plot = sns.barplot(x='Country', y='Sentiment', data=Country_Sent, orient='vertical', palette = grad )
plt.xticks(rotation=60);
plt.ylabel('Country Sentiment');
plt.show()


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q3.ipynb".
The first task is:
During the topic modeling, we still see some words that don't really fit in any topic (eg: would) so we remove some of them intentionally.
Can you write Python code for it?

ignore_list = ['00', '10', '15', '30', 'also', 'would']

#for mail in emails_cleaned.TokenizedText


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q3.ipynb".
The first task is:
Now, time to do the modeling. We will play with the topic number in order to have a consistent result.
Let's try with different numbers. First 5, then 10, 25 and finally 50 topics:
Can you write Python code for it?

def show_topics(lda_model):
    for i in range(lda_model.num_topics):
        topic_words = [word for word, _ in lda_model.show_topic(i, topn = 15)]
        print('Topic ' + str(i+1) + ': ', end = ' ')
        for word in topic_words:
            print(word, end = ' ')
        print("")

lda_model = models.LdaMulticore(corpus, id2word = text_dictionary, num_topics = 5)
show_topics(lda_model)

lda_model = models.LdaMulticore(corpus, id2word = text_dictionary, num_topics = 10)
show_topics(lda_model)

lda_model = models.LdaMulticore(corpus, id2word = text_dictionary, num_topics = 25)
show_topics(lda_model)

lda_model = models.LdaMulticore(corpus, id2word = text_dictionary, num_topics = 50)
show_topics(lda_model)


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q3.ipynb".
The first task is:
Now, we convert all the mails' words in numbers, each number corresponding to a word. In other words, we convert our table of mail in a corpus, so we will be able to do topic modeling on it.
Can you write Python code for it?

text_dictionary = corpora.Dictionary(text)
corpus = [text_dictionary.doc2bow(t) for t in text]


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q3.ipynb".
The first task is:
We choose keep mails with at least 5 tokens: we can have sentences that might make sense, while keeping 40 % of the mails. This is about 5000 mails, so we should be able to extract some topics from them.
Can you write Python code for it?

MIN_MAIL_SIZE = 5

text = []
for mail in emails_cleaned.TokenizedText:
    # Take only mails that are long enough
    if (len(mail) >= MIN_MAIL_SIZE):
        # Remove unwanted words
        mail_filtered = mail
        for word in mail_filtered:
            if word in ignore_list:
                mail_filtered.remove(word)
        text.append(mail_filtered)
ratio = len(text) / emails_cleaned.size * 100


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q3.ipynb".
The first task is:
We put all the mails in a text table in order to prepare the corpus to be analysed. We exclude mails that are too small.
Can you write Python code for it?

min_mail_size = [2, 3, 4, 5, 6, 10, 15, 20, 50];
print("Total number of mail: " + str(emails_cleaned.size))
for i in min_mail_size:
    text = []
    for mail in emails_cleaned.TokenizedText:
        if (len(mail) >= i):
            text.append(mail)
    ratio = len(text) / emails_cleaned.size * 100
    print("Mails with at least " + str(i) + " tokens represent " + str(ratio).zfill(4) + " % of the total.")


I am working on the file "Homework/05 - Taming Text/HW05_awesometeam_Q4.ipynb".
The first task is:
Extra
Can you write Python code for it?

# from - http://perso.crans.org/aynaud/communities/api.html

dendo = community.generate_dendrogram(G)
for level in range(len(dendo) - 1) :
     print("partition at level", level,
           "is", partition_at_level(dendo, level))


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
1. How many different 5-card hands are there?  (Remember, in poker the order in which the cards are received does not matter.)
Can you write Python code for it?

import math
total=math.factorial(52)/math.factorial(52-5)/math.factorial(5)
print('Different 5-card hands =\t',total) # Pick 5 cards from 52 cards 5C52


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
2. What is the expectation value of the kinetic energy $K$ of a particle? How does your answer depend on the particle mass? On temperature?
$\int_{-\infty}^{\infty} Ce^{-\frac{mv^2}{2k_B T}} dv = C(\frac{2k_B T\pi}{m})^\frac{1}{2} $
$\int_{-\infty}^{\infty} \frac{mv^2}{2}Ce^{-\frac{mv^2}{2k_B T}} dv = \frac{Ck_B T}{2}(\frac{2k_B T\pi}{m})^\frac{1}{2} $
$K = \frac{\int_{-\infty}^{\infty} \frac{mv^2}{2}Ce^{-\frac{mv^2}{2k_B T}} dv}{\int_{-\infty}^{\infty} Ce^{-\frac{mv^2}{2k_B T}} dv}
=\frac{k_B T}{2}$
K will increase when temperature increases(linear relationship), but unrelated to the particle mass.
Hint:
$\int_{0}^{\infty} e^{-ax^2} dx = \frac{1}{2}(\frac{pi}{a})^\frac{1}{2} $
$\int_{0}^{\infty} xe^{-ax^2} dx = \frac{1}{2a}$
$\int_{0}^{\infty} x^2e^{-ax^2} dx = \frac{1}{4a}(\frac{pi}{a})^\frac{1}{2} $
Can you write Python code for it?

function3 = integrate(m*v**2/2*C*exp(-m*v**2/2/kB/T)/function,(v,-oo,+oo)) #Numerator
print('The expectation value of kinetic energy K is',function3)


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
2. What is the probability of being dealt four of a kind (a card of the same rank from each suit)?
Can you write Python code for it?

print('The probability of being dealt four of a kind =\t',round(13*(52-4)/total,9))
# First pick a kind (1C13), then one card from the remaining 48 cards (1C48)
# round() returns x rounded to n digits from the decimal point


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
2. What is the probability that the person won't have traveled any net distance at all after 20 steps?
Can you write Python code for it?

print('The probability that the person will not have traveled any net distance at all after 20 steps = \t',math.factorial(20)/math.factorial(10)/math.factorial(10)/2**20,)
# Going nowhere - 10 steps south + 10 steps north 10C20
# Total 2^20


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
3. What is the expectation value of $x$?
Can you write Python code for it?

def integrand1(x):
    return x*integrand(x)/I[0] # Return nomalized probability distribution * v

I1 = quad(integrand1,0,np.inf)
print(I1)


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
3. What is the probability that the person has traveled half the maximum distance after 20 steps?
Can you write Python code for it?

print('The probability that the person has traveled half the maximun distance after 20 steps = \t',2*math.factorial(20)/math.factorial(5)/math.factorial(15)/2**20,)
# Going half the maximun distance - 15 steps south + 5 steps north or 15 steps north + 5 steps south
# Total 2_20


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
4. Plot the probability of traveling a given distance vs distance. Does the probability distribution look familiar?  You'll see it again when we talk about diffusion.
Can you write Python code for it?

X=[]
Y=[]
for x in range(21): # x stps going south
  y=math.factorial(20)/math.factorial(x)/math.factorial(20-x)/2**20  # Pick x steps from 20 steps xC20 / Total
  X.append(x-(20-x))
  # X means the final distance. The steps going south - the steps going north. If x=0, X=-20 ... If x=20, X=20. Postive means south
  Y.append(y)

plt.bar(X,Y)
plt.xlabel('distance');
plt.ylabel('P(x)');
plt.title('Probability distribution')
plt.show()


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
4. What is the variance of $x$?
Can you write Python code for it?

def integrand2(x):
    return x*x*integrand(x)/I[0] # Return nomalized probability distribution * v^2

I2 = quad(integrand2,0,np.inf)

var=I2[0]-I1[0]**2 # Variance can be calculated as <P(x)^2>-<P(x)>^2
print(var)


I am working on the file "Homework/HW1-soln.ipynb".
The first task is:
Problem 4: Now this is what I call equilibrium
The Boltzmann distribution tells us that, at thermal equilibrium, the probability of a particle having an energy $E$ is proportional to $\exp(-E/k_\text{B}T)$, where $k_\text{B}$ is the Boltzmann constant.  Suppose a bunch of gas particles of mass $m$ are in thermal equilibrium at temperature $T$ and are traveling back and forth in one dimension with various velocities $v$ and kinetic energies $K=mv^2/2$.
1. What is the expectation value of the velocity $v$ of a particle?
$P = Ce^{-\frac{mv^2}{2k_B T}},-\infty\le v < \infty$.
$\int_{-\infty} ^{\infty} vCe^{-\frac{mv^2}{2k_B T}} dv = 0$
$V = \frac{\int_{0}^{\infty} vCe^{-\frac{mv^2}{2k_B T}} dv}{\int_{0}^{\infty} Ce^{-\frac{mv^2}{2k_B T}} dv}
=0$
Can you write Python code for it?

from sympy import *
v = Symbol('x')
C=Symbol('C',positive=True)
m=Symbol('m',positive=True)
kB=Symbol('kB',positive=True)
T=Symbol('T',positive=True)

#Next create a function
function = integrate(C*exp(-m*v**2/2/kB/T),(v,-oo,+oo)) #Denominator
function2 = integrate(v*C*exp(-m*v**2/2/kB/T)/function,(v,-oo,+oo)) #Numerator

print('The expectation value of velocity is',function2/function)


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
10. Determine $\Delta G^\circ$(298 K).  Recall that $G = A + PV = A + RT$ for an ideal ga.
$\Delta{G^{\circ}} = \Delta{A^{\circ}} + \Delta(PV)$
$\quad = \quad \Delta{A^{\circ}} + RT$
Can you write Python code for it?

dG = dA + R*T/1000 #kJ/mol
print("delta_G = %.2f kJ/mol"%dG)


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
12. Using the data provided, determine $K_c$ (298 K), assuming a 1 M standard state.  You may either determine from partition functions of from the relationship between $K_c$ and $\Delta G^\circ$.
$\mathrm{A} \rightarrow \mathrm{B + C}$$$K_c(T) = \frac{\frac{q_{\mathrm{B}}}{V}\frac{q_{\mathrm{C}}}{V}}{\frac{q_{\mathrm{A}}}{V}} \frac{1}{c^{\circ}} e^{-\Delta{E(0)}/kT} = e^{-\Delta G^\circ(T)/RT}, \quad \text{where} \quad \frac{q_i}{V} = \frac{q_{trans}}{V}q_{rot}q_{vib}$$
Note: $K_c(T)$ is formally unitless but "remembers" that it refers to 1 M standard state.
Can you write Python code for it?

Kc = Q *np.exp(-dE0*1000/(R*T)) # Kc equation from lecture notes
print('Kc = %.3f (unitless). '%(Kc))

Kc = np.exp(-dG*1000/(R*T))
print('Kc = %.3f (unitless). '%(Kc))


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
13. 1 mole of CF$_3$OH is generated in a 20 L vessel at 298 K and left long enough to come to equilibrium with respect to its decomposition reaction. What is the composition of the gas (concentrations of all the components) at equilibrium (in mol/L)?
1 mol/ 20 L = 0.05 mol/L
$\mathrm{A} \rightarrow \mathrm{B + C}$
$K_c = \frac{x^2}{0.05-x}$, solve for x. Note that x = $[\frac{mol}{L}]$.
Can you write Python code for it?

from sympy import *
x = symbols('x',positive=True)
c = solve(x**2-(0.05-x)*Kc,x)
print('At equilibrium, CF3OH = %.2E mol/L, COF2 = %.5f mol/L, HF = %.5f mol/L.'%(0.05-c[0],c[0],c[0]))
print('At equilibrium, CF3OH = %.2E mol, COF2 = %.5f mol, HF = %.5f mol.'%((0.05-c[0])*20,c[0]*20,c[0]*20))


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
14. How, directionally, would your answer to Question 13 change if the vessel was at a higher temperature? Use the van'T Hoff relationship to determine the equilibrium constant and equilibrium concentrations at 273 and 323 K. How good was your guess?
From question #8, we know that at 298K,  $\Delta U$ = 18.64 kJ/mol.
$\Delta H = \Delta U + \Delta (nRT) = \Delta U + RT\Delta n$
Can you write Python code for it?

dn = 2-1
R = 8.314/1000 #kJ/mol K
T = 298 #K
dH = dU+dn*R*T #kJ/mol
print("dH =",round(dH,3),"kJ/mol")


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
16. Consult a thermodynamics source (e.g. https://webbook.nist.gov/chemistry/) to determine $\Delta H^\circ$(298 K), $\Delta S^\circ$(298 K), and $\Delta G^\circ$(298 K) for the homologous reaction CH$_3$OH (g)$\rightarrow$ H$_2$O (g) + H$_2$CO (g).  Does the substitution of F by H make the reaction more or less favorable?
Can you write Python code for it?

T = 298 #K
#All values were taken from NIST

#Methanol
Hm = -205 #kJ/mol
Sm = .2399 #kJ/mol K
Gm = Hm - T*Sm #kJ/mol

#Hydrogen
Hh = 0
Sh = .13068 #J/mol K
Gh = Hh - T*Sh #kJ/mol

#Formaldehyde
Hf = -108.6 #kJ/mol
Sf = .21895 #kJ/mol K
Gf = Hf - T*Sf #kJ/mol

delta_H = Hf+Hh-Hm #kJ/mol
delta_S = Sf+Sh-Sm #kJ/mol K
delta_G = Gf+Gh-Gm #kJ/mol

print('Delta H =',delta_H,'kJ/mol.')
print('Delta S =',delta_S,'kJ/mol K.')
print('Delta G =',delta_G,'kJ/mol.')

print('Therefore, by substituting F with H makes the reaction less favorable.')


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
2. Calculate the translational partition function of a CO molecule in the bottle at 298 K. What is the unit of the partition function?
For $T \gg \theta_{trans}$, $\Lambda \ll L$, $q_{trans} = V/\Lambda^3$. $\Lambda = h \left(\frac{\beta}{2\pi m}\right)^{1/2}$.
Can you write Python code for it?

Lamda = h*(1/(kB*298*2*np.pi*m))**0.5
print(Lamda)
q_trans = V/Lamda**3
print('The translational partition function of a CO molecule in the bottle at 298 K is {:.4E}.'.format(q_trans))
print('It is dimensionless.')


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
3. Plot the rotational and vibrational partition functions of a CO molecule in the bottle from $T$ =  200  to 2000 K (assume the CO remains a gas over the whole range). Hint: Use your answer to Problem 1 to simplify calculating the rotational partition function.
$q_{rot} = \frac{1}{\sigma}\frac{T}{\theta_{rot}} = \frac{T}{\theta_{rot}}$
$q_{vib} = \frac{1}{1-e^{-\theta_{vib}/T}}$
Can you write Python code for it?

T = np.linspace(200,2000,1000) # r = R/a_0
q_rot = T/T_rot
q_vib = 1/(1-np.exp(-T_vib/T))
plt.plot(T,q_rot)
plt.xlabel('T (K)')
plt.ylabel('$q_{rot}$')
plt.title('The rotational partition function of a CO molecule')
plt.show()
plt.plot(T,q_vib)
plt.xlabel('T (K)')
plt.ylabel('$q_{vib}$')
plt.title('The vibrational partition function of a CO molecule')
plt.show()


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
4. Plot the total translational, rotational, and vibrational energies of CO in the bottle from $T =$ 200 to 2000 K (assume the CO remains a gas over the whole range). Which (if any) of the three types of motions dominate the total energy?
$U_{trans} = \frac{3}{2}RT$
$U_{rot} = RT$
$U_{vib} = R\frac{\theta_{vib}}{e^{\theta_{vib}/T}-1}$.
Can you write Python code for it?

R = 8.31447 # J/(mol*K)
U_trans = 1.5*R*T
U_rot = R*T
U_vib = R*T_vib/(np.exp(T_vib/T)-1)
plt.plot(T,U_trans,label='U_trans')
plt.plot(T,U_rot,label='U_rot')
plt.plot(T,U_vib,label='U_vib')
plt.legend()
plt.xlabel('T (K)')
plt.ylabel('Internal Energy (J/mol)')
plt.title('Internal energies of CO in the bottle')
plt.show()


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
9. Using the data provided, determine  $\Delta A^{\circ}$(298 K) in kJ mol$^{-1}$, assuming ideal behavior and 1 M standard state.  Recall that $A^\circ=E^\text{elec} + \text{ZPE}-RT\ln(q^\circ)-RT$ and that $q^\circ =(q^\text{trans}/V)q^\text{rot}q^\text{vib}/c^\circ$ in units corresponding with the standard state.
$\Delta{A^{\circ}}= \big{[-k_BT\ln(q_{t}q_{r}q_{v})-k_BT]{COF_2}+[-k_BT\ln(q{t}q_{r}q_{v})-k_BT]{HF}-[-k_BT\ln(q{t}q_{r}q_{v})-k_BT]_{CF_3OH}\big} *N_A + \Delta(E_0)$
$\quad \quad = \Delta(E_0)-RT\ln(Q)-RT$
Can you write Python code for it?

q_trans = [7.72e32/c,1.59e32/c,8.65e31/c] # change translational partition functions from 1/m3 to mol/l std state
q_rot = [61830,679,9.59] # unitless
q_vib = [2.33,1.16,1] # unitless
Q = (q_trans[1]*q_rot[1]*q_vib[1])*(q_trans[2]*q_rot[2]*q_vib[2])/(q_trans[0]*q_rot[0]*q_vib[0]) # total partition
dA = dE0 + (-R*T*np.log(Q)- R*T)/1000 #kJ/mol
print("Q = %.2f"%Q)
print("delta_E0 = %.2f"%dE0)
print("delta_A = %.2f kJ/mol"%dA)


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
Reactions from scratch
In 1996, Schneider and co-workers used quantum chemistry to compute the reaction pathway for unimolecular decomposition of trifluoromethanol, a reaction of relevance to the atmospheric degradation of hydrofluorocarbon refrigerants (J. Phys. Chem. 1996, 100, 6097- 6103, doi:10.1021/jp952703m): $$\mathrm{CF_3OH\rightarrow COF_2 + HF}$$
Following are some of the reported results, computed at 298 K:
|              | CF$_3$OH| C(O)F$_2$ | HF |    |
|:--------------|---------:|-----------:|----:|----:|
| $E^\text{elec}$ | -412.90047 | -312.57028 | -100.31885 | (Hartree) |
| ZPE             | 0.02889 | 0.01422 | 0.00925 | (Hartree) |
| $U^\text{trans}$ | 3.7 | 3.7| 3.7 | (kJ mol$^{-1}$) |
| $U^\text{rot }$ | 3.7 | 3.7| 2.5 | (kJ mol$^{-1}$) |
| $U^\text{vib}$ | 4.3 | 1.2 | 0 |  (kJ mol$^{-1}$) |
| $q^{\text{trans}}/V$ | $7.72\times 10^{32}$ | $1.59\times 10^{32}$ |$8.65\times 10^{31}$ | (m$^{-3}$) |
| $q^\text{rot}$ | 61830 | 679 | 9.59 | |
| $q^\text{vib}$ | 2.33 | 1.16 | 1 | |
8. Using the data provided, determine $\Delta U^{\circ}$(298 K)), in kJ mol$^{-1}$, assuming ideal behavior and 1 M standard state.  Recall that $U(T)$ is the sum of the contributions of all degrees of freedom.
Remember that $E_0$ is contained in $\Delta{U}^{\circ},\Delta{A}^{\circ},$ and $\Delta{G}^{\circ}.$ For example:
$$\Delta U^{\circ} =\sum_{product}U_{trans} + U_{rot} + U_{vib} + (E_{elec} + ZPE) - \sum_{reactant} U_{trans} + U_{rot} + U_{vib} + (E_{elec} + ZPE)$$$$=\sum_{product}U_{trans} + U_{rot} + U_{vib} + E_0 - \sum_{reactant} U_{trans} + U_{rot} + U_{vib} + E_0$$
$\Delta U^{\circ} =\Delta(U_{trans} + U_{rot} + U_{vib}) + \Delta(E_0)$
Can you write Python code for it?


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
Since $\Delta H$ is positive, we expect $K \uparrow$ as $T \uparrow$
The Van't Hoff equation states:
$ln\frac{K(T_2)}{K(T_1)}=\frac{-\Delta H^o}{R}(\frac{1}{T_2}-\frac{1}{T_1})$
We know from question 12, K = 2.926 at 298 K.
Can you write Python code for it?


I am working on the file "Homework/HW10-soln.ipynb".
The first task is:
Therefore, the at higher temperatures, the reaction shifts towards the products.
15. How, directionally, would your answer to Question 13 change if the vessel had a volume of 5 L? Redo the calculation at this volume to verify your guess.
If V = 5L, the initial concentration = $\frac{1 mol}{5 L}=.2 M$
$K_c = \frac{x^2}{0.2-x}$
At 298 K, Kc = 2.926 (from problem 12)
Can you write Python code for it?

T = 298 #K
R = 8.314
Kc = np.exp(-dG*1000/(R*T))
print('At 298 K, Kc = %.3f (unitless). '%(Kc))
x = symbols('x',positive=True)
c = solve(x**2-(0.2-x)*Kc,x)
print('At equilibrium, CF3OH = %.2E mol/L, COF2 = %.5f mol/L, HF = %.5f mol/L.'%(0.2-c[0],c[0],c[0]))
print('At equilibrium, CF3OH = %.2E mol, COF2 = %.5f mol, HF = %.5f mol.'%((0.2-c[0])*5,c[0]*5,c[0]*5))
print('At a smaller volume, the concentration of products increases, but the number of moles decreases.')


I am working on the file "Homework/HW11-soln.ipynb".
The first task is:
14. Use the data in the table to compute the overall reaction enthalpy, and the forward and reverse reaction enthalpies.
Can you write Python code for it?


I am working on the file "Homework/HW11-soln.ipynb".
The first task is:
15. Based on your computed rate constant, what is the half-life of CF$_3$OH at 298 K?
Can you write Python code for it?

t=np.log(2)/k2 # s
print('The half-life is %E s, which is about %E years.'%(t,t/3600/24/365))


I am working on the file "Homework/HW11-soln.ipynb".
The first task is:
6. Plot the reaction rate vs $X$. Be sure to include appropriate units.
Can you write Python code for it?

k = 0.8
r = k*P_e**(1/2)*P_o
plt.plot(X,r)
plt.xlabel('X')
plt.ylabel('r (bar/s)')
plt.show()


I am working on the file "Homework/HW11-soln.ipynb".
The first task is:
9. From the information given, can you predict the rate law for the reverse reaction?
No we can't predict the rate law. This is not an elementary step process so that we can't know the reaction order from the equation stoichiometry.
Rate constants from scratch
In 1996, Schneider and co-workers used quantum chemistry to compute the reaction pathway for unimolecular decomposition of trifluoromethanol, a reaction of relevance to the atmospheric degradation of hydrofluorocarbon refrigerants (J. Phys. Chem. 1996, 100, 6097- 6103, doi:10.1021/jp952703m):
$$\text{CF}_3\text{OH}\rightarrow \text{COF}_2 + \text{HF}$$
Following are some of the reported results, computed at 298 K:
|                     | CF$_3$OH             | [CF$_3$OH]$^\ddagger$ | C(O)F$_2$ | HF |    |
|:--------------------|---------------------:|-------------------------|----------:|---:|----:|
| $E^\text{elec}$     | -412.90047           | -412.82771              | -312.57028 | -100.31885 | (Hartree) |
| ZPE                 | 0.02889              | 0.02313                 | 0.01422 | 0.00925 | (Hartree) |
| $U^\text{trans}$    | 3.7                  | 3.7   | 3.7| 3.7 | (kJ mol$^{-1}$) |
| $U^\text{rot }$     | 3.7                  | 3.7   | 3.7| 2.5 | (kJ mol$^{-1}$) |
| $U^\text{vib}$      | 4.3                  | 4.1   |1.2 | 0 |  (kJ mol$^{-1}$) |
| $q^{\text{trans}}/V$| $7.72\times 10^{32}$ | $7.72\times 10^{32}$   |$1.59\times 10^{32}$ |$8.65\times 10^{31}$ | (m$^{-3}$) |
| $q^\text{rot}$      | 61830                |  68420  | 679 | 9.59 | |
| $q^\text{vib}$      | 2.33                 |  2.28  | 1.16 | 1 | |
10. Provide a rough sketch of what you expect the transition state to look like.

11. Based on the data in the table, sketch out an approximate potential energy surface for the unimolecular decomposition reaction. Indicate on the PES the location of the reactants, the products, and the transition state. Also indicate relevant zero point energies, the 0 K reaction energy, and the activation energy.

12. Using data from the table and...
Can you write Python code for it?


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
11. Using your estimate of the diffusion constant in the solvent, how long does it take the same fraction CO$_2$  molecules to diffuse a similar distance in 1-dimension in the liquid phase?
Can you write Python code for it?

t2 = sigma1**2/2/(D12*100**2)
print('Using the diffusion constant from #6, t =',round(t2,0),'s.')


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
12. Is it safe to assume that any CO$_2$ that travels from the surface into the bulk of the solvent is rapidly replaced from the gas phase?
Can you write Python code for it?

print('Comparing problems 7 and 11, we see that diffusion is order-of-magnitude greater in gas phase than in liquid phase.')
print('Therefore, gas molecule dissolved into solvent will be rapidly replaced by other gas molecules.')


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
3. Calculate the mean (expected value) of the speed of a 2-dimensional gas of molecules. How does your answer compare to a 3-dimensional gas?
Can you write Python code for it?

from sympy import *

T = Symbol('T',positive=True)
k = Symbol('k',positive=True)
m = Symbol('m',positive=True)
v = Symbol('v',positive=True)

#2D Gas
eqn2d = (2*pi*v)*(m/2/pi/k/T)*exp(-m*v**2/2/k/T)
vbar2top = integrate(eqn2d*(v),(v,0,oo))
vbar2bot = integrate(eqn2d,(v,0,oo))
pprint(vbar2top/vbar2bot)
pprint(vbar2top)

#1D Gas
eqn1d = (m/2/pi/k/T)**(0.5)*exp(-m*v**2/2/k/T)
vbar1top = integrate(eqn1d*(v),(v,0,oo))
vbar1bot = integrate(eqn1d,(v,0,oo))
pprint(vbar1top/vbar1bot)

#3D Gas
eqn3d = (4*pi*v**2)*(m/2/pi/k/T)**(1.5)*exp(-m*v**2/2/k/T)
vbar3top = integrate(eqn3d*(v),(v,0,oo))
vbar3bot = integrate(eqn3d,(v,0,oo))
pprint(vbar3top/vbar3bot)


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
4. Calculate the mean kinetic energy of a 2-dimensional gas. How does your answer compare to a one and 3-dimensional gas?
Can you write Python code for it?

from sympy import *

T = Symbol('T',positive=True)
k = Symbol('k',positive=True)
m = Symbol('m',positive=True)
v = Symbol('v')

#2D Gas
eqn2d = (2*pi*v)*(m/2/pi/k/T)*exp(-m*v**2/2/k/T)
vbar2top = integrate(eqn2d*(v**2/2),(v,0,oo))
vbar2bot = integrate(eqn2d,(v,0,oo))
pprint(vbar2top/vbar2bot)

#1D Gas
eqn1d = (m/2/pi/k/T)**(0.5)*exp(-m*v**2/2/k/T)
vbar1top = integrate(eqn1d*(v**2/2),(v,-oo,oo))
vbar1bot = integrate(eqn1d,(v,-oo,oo))
pprint(vbar1top/vbar1bot)

#3D Gas
eqn3d = (4*pi*v**2)*(m/2/pi/k/T)**(1.5)*exp(-m*v**2/2/k/T)
vbar3top = integrate(eqn3d*(v**2/2),(v,-oo,oo))
vbar3bot = integrate(eqn3d,(v,-oo,oo))
pprint(vbar3top/vbar3bot)


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
6. Use the Stokes-Einstein relationship to estimate the diffusion constant of CO$_2$ in the Stoddard solvent.  How does this compare with the diffusion constant in the gas phase? Why?
Can you write Python code for it?

r = d/2 #m
eta = 14.93e-6 # Pa*s, Viscosity of CO2 at 298 K (source from engineeringtoolbox.com)
D12 = kB*T/(4*np.pi*eta*r) #m^2/s

print('The diffusion constant in the Stoddard solvent is', round(D12*100**2,7),'cm^2/s.')
print('This value is smaller in Stoddard solvent due to greater viscosity.')


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
8. How many collisions on average does one of these diffusing CO$_2$ molecule make with other gas molecules on the way from the middle of the vapor space to the surface of the solvent?
Can you write Python code for it?


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
9. How far in total distance does this typical CO$_2$ molecule travel in the time it takes to reach the solvent surface from the middle of the cell?
Can you write Python code for it?


I am working on the file "Homework/HW2-soln.ipynb".
The first task is:
Problem 2. (Kinetics and Transport)
In junior Chemical Engineering laboratory, you will study the diffusion and solubility of CO$_2$ in an organic solvent using a diffusion cell like the one sketched here. <img src="https://gas spacegtheithub.com/wmfschneider/CHE30324/blob/master/Homework/imgs/HW2_P2.png?raw=1">Let’s suppose that the gas space at the top of the diffusion cell is approximately 2 cm high and 4 cm in diameter. Further suppose that the gas in the head of the cell is pure CO$_2$ at 298 K and 1 bar pressure. Note that CO$_2$ has a collision diameter d of 0.40 nm.
5. What does gas kinetic theory predict for the gas self-diffusion constant $D_{11}$ of CO$_2$ gas in the cell, in cm$^2$s$^{−1}$?
Can you write Python code for it?

import numpy as np

#Constants
T = 298 #K
P = 100000 #Pa (kg/m/s^2)
d = 4*10**-10 #m
MW = 44.01 #g/mol
Na = 6.022*10**23 #molecules/mol
kB = 1.38064582*10**-23 #m^2 kg/s^2/K
m = MW/Na/1000 # kg/molecule

v = (8*kB*T/np.pi/m)**0.5 #m/s, mean speed
V = Na*kB*T/P #m^3/mol, volume
sigma = np.pi*d**2  #m^2, collision cross section
z = np.sqrt(2)*sigma*Na/V*v #1/s, molecular collision frequency
lambd = v/z #m, mean free path
D11 = 1/3*v*lambd #m^2/s, self-diffusion constant

print('The self diffusion constant D11 is',round(D11*100**2,5),'cm^2/s')


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
14. What is the circumference of the $n$ = 2 orbit? What is the de Broglie wavelength of an electron in the $n$ = 2 orbit? How do these compare?
Can you write Python code for it?

import numpy as np
a0 = 5.29e-11 #m, Bohr radius
r = a0*n2**2 #m
l = np.pi*2*r #m
print('The circumference of the n=2 orbit is {} m'.format(l))

m = 9.109e-31 #kg
h = 6.626e-34 #m^2 kg/s
hbar = h/(2*np.pi) #m^2 kg/s, reduced Planck constant
k0 = 2.30708e-28
p0 = k0*m/hbar*1/1 #kg m/s
p2 = p0/2
wavelength3 = h/p2
print('The de Broglie wavelength for an electron in n=2 orbit is {} m.'.format(wavelength3))

print(l/wavelength3)


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
3. What is the probability for a C atom to have $n=1$ quanta of energy relative to $n=0$ at 1500 K?  At 150 K?
$P(n=1)/P(n=0) = \exp(-(E_1 -E_0)/k_BT) = \exp(-(1 h\nu - 0 h\nu)/k_BT) = \exp(-h\nu/k_BT)$
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

#Constants
h = 6.626e-34 #m^2 kg/s
kB = 1.3806e-23 #m^2 kg/s^2 K
v = 2.75e13 #1/s

P1500 = np.exp(-h * v/kB/1500.)
P150 = np.exp(-h * v/kB/150.)

print('Ratio at 1500 and 150 K are {} and {}, respectively'.format(P1500,P150))
T = 1500 #K


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
5. Based on this temperature, what wavelength $\lambda$ of light does the sun emit most intensely, in nm? What frequency of light, in s$^{–1}$? What color does this correspond to?
Can you write Python code for it?

wavelength = 2897768/Tsun #nm
c = 299792458 #m/s
freq= c/wavelength *1e9
print('The sun emits a wavelength of {} nm most intensely.'.format(wavelength))
print('The freqency is %E 1/s.'%(freq))
print('This wavelength corresponds to the color cyan/green.')


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
6. What is the ultraviolet catastrophe, and what did Planck have to assume to circumvent it?
In classical physics, Rayleigh-Jeans law predicted that radiation intensity approached infinity at small wavelengths. This phenomena is known as the ultraviolet catastrophe.
Planck assumed that a:
- the black body radiator is full of standing waves of light
- the energy of a wave of light is proportional to its frequency
- only discrete amounts of energy were possible at a given frequency, $E = n h \nu$
Photoelectric effect.
The photoelectric effect refers to the emission of electrons that is observed when light is shone on a metal. The effect was the clue that Einstein needed to illucidate the particulate nature of the interaction of light and matter.
7. You set up an experiment in which you shine light of varying intensity and constant frequency at a metal surface and measure the maximum kinetic energy of the emitted electrons. As an accomplished student of classical physics, you know that the energy contained in a wave is proportional to the square of its intensity. Based on this knowledge, sketch how you $expect$ the kinetic energy of the electrons to vary in the experiment. Briefly justify your answer.
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

I = np.linspace(0,2*np.pi,30)
E = I**2

plt.plot(I,E)
plt.xlabel('Intensity')
plt.ylabel('Energy')
plt.xticks([])
plt.yticks([])
plt.show()


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
9. What is the metal? $Hint:$ It is a coinage metal.
Copper has a work function of 4.7 eV.
Diffraction.
Diffraction is the scattering of particles off of a crystal, and is today an essential means of probing the structure of matter. Modern diffraction is performed using bright light and particle sources of various types.
10. The spacing between atoms in a Ag crystal is approximately 2.9 Å, a distance that can be measured by scattering photons of a comparable wavelength off the crystal. What is the energy (in eV) of a photon of wavelength 2.9 Å? What part of the electromagnetic spectrum does this correspond to?
Can you write Python code for it?

h = 4.135668e-15 #eV*s
c = 299792458e9 #nm/s
wavelength = .29 #nm

E = h*c/wavelength #eV
print ('The energy of a photon at 2.9 A is {} eV'.format(E))
print('This corresponds to soft X-rays in the electromagnetic spectrum.')


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
This is the basis of electron diffraction, often used to observe surfaces, eg with an electron microscope.
The Bohr atom.
Bohr developed the first successful model of the energy spectrum of a hydrogen atom by postulating that electrons can only exist in certain fixed energy “orbits” indexed by the quantum number $n$. (Recall that the equations describing the Bohr atom are in Table 4 of the course outline.)
13. Would light need to be absorbed or emitted to cause an electron to jump from the $n$ = 1 to the $n$ = 2 orbit? What wavelength of light does this correspond to?
Can you write Python code for it?

Z = 1
n1 = 1
n2 = 2
E1 = -13.6*Z**2/(n1**2) #eV
E2 = -13.6*Z**2/(n2**2) #eV

c = 299792458 #m/s
h = 6.626e-34 #m^2 kg/s

wavelength = h*c/(E2-E1)*1e9/1.60218e-19

print('Light needs to be absorbed to provide energy for electrons to jump to higher orbitals.')
print('This corresponds to a wavelength of',wavelength,'nm.')


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
This is the basis of x-ray diffraction, used to figure out the crystal structure of things, like proteins.
11. Suppose you have a device that produces these photons at a power of 1 μW. How many photons/s does this correspond to?
Can you write Python code for it?

P = 1e-6 #J/s
photons = P/E*6.242e18 #photons/s
print('1 microwatt corrsponds to %E photons/second.'%(photons))


I am working on the file "Homework/HW3-soln.ipynb".
The first task is:
Very probably at high $T$, not at all probable at low $T$.
Blackbody radiators.
By treating the sun as a blackbody radiator, Joseph Stefan derived the first reliable estimate of the temperature of the sun’s surface.
4. Stefan estimated that the power per unit area radiated from the surface of the sun was 43.5 times greater than that of a metal bar heated to 1950 ̊C. What is the temperature of the sun?
Stefan-Boltzmann law relates power and temperature, $I =\sigma T^4$.  $I_{sun}/I_{bar}=43.5 = (T_{sun}/T_{bar})^4$
Can you write Python code for it?

Tmetal = 1950+273.15 #K
Tsun = (43.5*Tmetal**4)**.25
print('The temperature of the sun is {} Kelvin.'.format(Tsun))


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
10. What is the maximum precision with which you could measure the position of the electron? Give your answer in units of $b$.
Can you write Python code for it?

dx=h/2/dp
print('The maximum precision with the position of the electron is ',dx)


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
7. Is your normalized $\tilde{\psi}(x)$ an eigenfunction of the linear momentum operator? If so, what is its eigenvalue?
Can you write Python code for it?

import numpy as np
der1 = Wavefunction_normalized.diff(x,1)
Eigenvalue=complex(0,-1)*h*der1/Wavefunction_normalized

if x in Eigenvalue.free_symbols: # check if Eigenvalue is a function of x or not
  print('No. It is not an eigenfunction of the linear momentum operator.')
else:
  print('Yes. It is an eigenfunction of the linear momentum operator.')


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
8. If you were to measure the linear momentum of many electrons, all with the same wavefunction $\tilde{\psi}(x)$ , will you get the same answer every time?
Can you write Python code for it?

# Not a eigenfunction
print('No. Because this wavefunction is not an eigenfunction of momentum.')
print('Only the eigenfunction of momentum can give us a single result.')


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
9. If you were to measure the linear momentum of many electrons, all with the same wavefunction $\tilde{\psi}(x)$ , what will you get on average?
Can you write Python code for it?

# Momentum operator
der1 = Wavefunction_normalized.diff(x,1)
P1 = complex(0,-1)*h*der1 # First momentum operator
Ep_p= integrate(P1*Wavefunction_normalized,(x,-oo,+oo))
print('Expectation value is equal to ', Ep_p)


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
9. What is the uncertainty in the momentum of the electron? (Recall the uncertainty is given by $\Delta p = \sqrt{\langle p^2 \rangle - \langle p \rangle^2}$.)  You can give your answer in units of $m_e$, $\hbar$, and $b$.
Can you write Python code for it?

# Momentum operator^2
der2 = Wavefunction_normalized.diff(x,2)
Ep_p2= integrate(-h**2*der2*Wavefunction_normalized,(x,-oo,+oo))
dp=sqrt(Ep_p2-Ep_p*2)
print('The uncertainty in the momentum of the electron is ' ,dp)


I am working on the file "Homework/HW4-soln.ipynb".
The first task is:
The normalized wavefunction is:
$$ \frac{e^ \frac{-x^2}{2b^2}} {\pi ^ \frac{1} {4} b ^ \frac{1}{2}}$$
4. Plot $V(x)$ and your normalized $\tilde{\psi}^2(x)$ along the same $x$ axis. (Hint: Plot your answers in units of $b$ length and units of $k$ force constant.)
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

x_d = np.linspace(-2.5,2.5,100) # x_d=x/b which is the dimensionless length
V=1/2*x_d**2 # in unit of kb^2
# V = 1/2*k*x^2 = 1/2*x_d^2 *k*b^2.
# Since k and b are constant, we can consider kb^2 to be the unit of energy.

Wavefunction2_normalized=Wavefunction**2/A
print(Wavefunction2_normalized)
Wavefunction2_normalized=np.exp(-x_d**2)/(sqrt(pi)) # in unit of 1/b
#normalized_wavefunction^2 = exp(-x^2/b^2)/sqrt(pi)/b = exp(-x_d**2)/(sqrt(pi))/b
#Since b is constant, we can consider b to be the unit of length.

fig, ax1 = plt.subplots()
color = 'tab:green'
ax1.set_xlabel('x (b)')
ax1.set_ylabel('V (kb^2)', color=color)
ax1.plot(x_d, V, color=color, label='V(x)')
ax1.tick_params(axis='y', labelcolor=color)

plt.legend(loc='upper left')
ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('Wavefunction2_normalized (1/b)')  # we already handled the x-label with ax1
ax2.plot(x_d, Wavefunction2_normalized,label='Wavefunc2_norm')
plt.legend(loc='lower left')
plt.title('V(x) & Wavefunction2_normalized')


I am working on the file "Homework/HW4/RC_Filters_in_Python.ipynb".
The first task is:
Making Gain Plots
We now can plot the gain of our circuit (actially attenuation since we will find the gain is less than 1) for an input signal versus frequency. Since the function assumes $V_{in} = 1$V, the absolute value (np.abs()) of the output of our function is equal to the attentuation, (since $G = V_{out}/V_{in}$).

For R= 1kΩ and C=1µF,  make a plot of the gain for this circuit versus frequency from 10 Hz to 10kHz. Make this a semi log plot, where the x axis is logarithmic, but the y-axis is linear.
This should look like the plot created with an AC sweep simulation. You can find one here:
Partsim https://www.partsim.com/simulator#66937.
SystemVision: https://www.systemvision.com/groups/mauriks-workspace/designs/passive-low-pass-filter-0
MultiSim Live: https://www.multisim.com/content/PLitYWAZXLxTrrH6zQfsXb/passive-low-pass-filter/open/

Make sure you label your plot, and you label your axes.
Draw a red vertical line for the cutoff frequency for this filter:

$$F_{cut} = \frac{1}{2\pi R C}$$

Also make a plot of the phase of the signal versus frequency (same scale). The phase is equal to the angle of the imaginary number of our function.
Make sure you label your plot, and you label your axes.
Draw a red vertical line for the cutoff frequency for this filter
Can you write Python code for it?

f = np.linspace(10,10000,1000)
R=1000. # 1kOhm
C=1.e-6  # 1µF
#
# Plot the Gain of the filter, and below it plot the phase of the filter.
# Mark with a vertical red line the cutoff frequency of the filter.
#
# Implement your plots in the space below, using f, R and C
#
# Points = 10
#
# Your code goes here:


I am working on the file "Homework/HW4/RC_Filters_in_Python.ipynb".
The first task is:
The plot you get should look like the one you had for the low pass filter in the lab.
High Pass Filter
You now want to repeat this entire calculation, but for a high pass filter. You can copy an paste most of the code that you have for the low pass filter, the only thing you need to change is the filter function, Filter(f, R, C) to be correct for a high pass filter.
Can you write Python code for it?

# Put the code for a High pass filter function below
#
# Points = 10
#
def Filter(f,R,C):
    """Filter function that corresponds to the low pass RC filter."""
    # Input:
    # f the frequency in Hz. (NOT omega, the angular frequency.)
    # R the value for the resistor in Ohm.
    # C the value for the capacitor in Farad.
    #
    # Return:
    # vout the output value of the Filter function.

# Tests for your function by running these statements. Any error indicates your function
# does not have the expected output.
#
assert np.abs(Filter(100., 1000., 1E-9) - (3.947840e-07+0.000628318j)) < 1E-6
assert np.abs(Filter(100.E3, 1000., 1E-9) - (0.28304319967510216+0.45047724336838857j))  < 1E-6

# Put the code for make a Bode plot here.
#
# Points = 10
#

# Put the code for doing the Fourier transform of a square wave, the filter step, and the
# inverse Fourier transform here. Then add the code to plot the result.
#
# Points = 10
#


I am working on the file "Homework/HW4/RC_Filters_in_Python.ipynb".
The first task is:
We can now define the RC circuit as a function of the frequency, where will use $f=\omega/2\pi$, and for simplicity we choose $V_{in}=1$.
Task

Write a function called Filter, that accepts the arguments (f,R,C) and returns the output amplitude for a low pass filter, vout.
Can you write Python code for it?

# Fill in the code for the Filter function for a low pass filter.
#
# Points = 10
#
def Filter(f,R,C):
    """Filter function that corresponds to the low pass RC filter."""
    # Input:
    # f the frequency in Hz. (NOT omega, the angular frequency.)
    # R the value for the resistor in Ohm.
    # C the value for the capacitor in Farad.
    #
    # Returns:
    # vout the (comples) output value of the filter.
#
# Your code goes here:

# Tests for your function by running these statements. Any error indicates your function
# does not have the expected output.
#
assert np.abs(Filter(100., 1000., 1E-9) - (0.99999960-0.000628318j)) < 1E-6
assert np.abs(Filter(10.e3, 2000., 10E-9) - (0.3877266-0.48723166j))  < 1E-6
assert np.abs(np.imag(Filter(10.e3, 2000., 10E-9)) + 0.4872316614323186) < 1E-6


I am working on the file "Homework/HW4/RC_Filters_in_Python.ipynb".
The first task is:
You should note that the FFT you just plotted is a series of spikes at regular intervals, that start strong (at the fundamental frequency of 50 Hz) and then drop off.
To check the FFT math, you will now want to make sure you can recover the original signal with a inverse FFT. This is done with the function ifft().
Task
Plot the result of the real part of the inverse FFT in the same manner as the previous plot of the square wave. Note that you want to plot the real part here (use np.real()) and not the magnitude, which will look quite wrong.
Can you write Python code for it?

# Put the code for plotting the inverse FFT here.
#
# Points = 5
#


I am working on the file "Homework/HW5-soln.ipynb".
The first task is:
12. Based on your answers to questions 10 and 11, what do you expect the vibrational spectrum of an ${}^{14}N={}^{16}O$ molecule to look like? If it has a spectrum, in what region of the spectrum does it absorb (e.g., ultraviolet, x-ray, ...)?
There is only one peak that corresponds to the v0 to v=1 transition. Vibrational frequency is 1904 cm^-1, which is in the IR region.
Two-dimensional harmonic oscillator
Imagine an H atom embedded in a two-dimensional sheet of MoS$_2$.  The H atom vibrates like a two-dimensional harmonic oscillator with mass 1 amu and force constants $k_x$ and $k_y$ in the two directions.
13. Write down the Schrödinger equation for the vibrating H atom. Remember to include any boundary conditions on the solutions.
$-{\frac{\hbar}{2m_e}}{\frac{\partial^2\psi(x,y)}{\partial x^2}}-{\frac{\hbar}{2m_e}}{\frac{\partial^2\psi(x,y)}{\partial y^2}}+{\frac{1}{2}k_xx^2\psi(x，y)}+{\frac{1}{2}k_yy^2\psi(x，y)}=E\psi(x,y) $
$\lim_{x\rightarrow\pm\infty} \psi(x,y)=0\qquad \lim_{y\rightarrow\pm\infty} \psi(x,y)=0$
14. The  Schrödinger equation is seperable, so the wavefunctions are products of one-dimensional wavefunctions and the eigenenergies are sums of corresponding one-dimensional energies.  Derive an expression for the H atom vibrational energy states, assuming $k_x = k_y/4 = k$.
Because it is separable, energies in $x$ and $y$ are additive.
$E = E_x + E_y = (v_x+\frac{1}{2})h\nu_x + (v_x+\frac{1}{2})h\nu_y$
$\nu_x= \frac{1}{2\pi}\sqrt{\frac{k}{m}}\qquad \nu_y= \frac{1}{2\pi}\sqrt{\frac{4k}{m}} = 2\nu_x$
$E = (v_x+\frac{1}{2})hν+ 2(v_y+\frac{1}{2})hν=(v_x+2v_y+\frac{3}{2})hν,ν=\frac{1}{2\pi}\sqrt{\frac{k}{\mu}}$
15. A spectroscopic experiment reveals that the spacing between the first and second energy levels is 0.05 eV. What is $k$, in N/m?
Can you write Python code for it?

import numpy as np
del_E = 0.05*1.60218e-19 #J
h = 6.626e-34 #Planck constant in m^2 kg / s
m = 1.66054e-27 #kg
freq = del_E/h #/s
k = (2*np.pi*freq)**2*m #kg/m/s^2

print('Force constant k is ',round(k,2),'N/m')


I am working on the file "Homework/HW5-soln.ipynb".
The first task is:
3. Butadiene has 4 π electrons, and we will learn later that in its lowest energy state, two of these are in the $n = 1$ and two in the $n = 2$ levels. Compare the wavelength of light (in nm) necessary to promote (“excite”) one electron from either of these levels to the empty $n = 3$ level.
Can you write Python code for it?

import numpy as np
l = 3*1.4e-10 #m, length of the box
hbar = 1.05457e-34 #J*s
me = 9.109e-31 #kg
E13 = ((3**2-1**2)*np.pi**2*hbar**2/2/me/l**2)*6.2415e18
E23 = ((3**2-2**2)*np.pi**2*hbar**2/2/me/l**2)*6.2415e18
lambda13 = 1240/E13 #nm
lambda23 = 1240/E23 #nm
print('From n=1 to n=3, light must have wavelength = {0:.2f}nm. \nFrom n=2 to n=3, light must have wavelength = {1:.2f}nm.'.format(lambda13,lambda23))


I am working on the file "Homework/HW5-soln.ipynb".
The first task is:
4. The probability of an electron jumping between two energy states by emitting or absorbing light is proportional to the square of the “transition dipole,” given by the integral $\lvert\langle\psi_{initial}\lvert \hat{x}\rvert\psi_{final}\rangle\rvert^2$. Contrast the relative probabilities of an electron jumping from $n = 1$ to $n = 3$ and from $n = 2$ to $n = 3$ levels. Can you propose any general rules about “allowed” and "forbidden" jumps?
$|\langle\psi_1|\hat{x}|\psi_3\rangle|^2$ = $(\int_{0}^{L} \frac{sin(\pi x)}{L} * x *  \frac{sin(3\pi x)}{L} dx)^2$
If we assume L = 1 m and integrate, this integral is equal to zero. Therefore, it is "forbidden".
$|\langle\psi_2|\hat{x}|\psi_3\rangle|^2$ = $(\int_{0}^{L} \frac{sin(2\pi x)}{L} * x *  \frac{sin(3\pi x)}{L} dx)^2$
If we assume L = 1 m and integrate, this integral is not equal to zero. Therefore, it is "allowed".
5. Consider the reaction of two ethylene molecules to form butadiene:
<img src="https://github.com/wmfschneider/CHE30324/blob/master/Homework/imgs/HW5-2.png?raw=1"  width="360">
As a very simple estimate, you could take the energy of each molecule as the sum of the energies of its π electrons, allowing only two electrons per energy level. Again taking each C—C bond as 1.4 Å long and treating the π electrons as particles in a box, calculate the total energy of an ethylene and a butadiene molecule within this model (in kJ/mol), and from these calculate the net reaction energy. Compare your results to the experimental reaction enthalpy. How well did the model do?
Can you write Python code for it?

import numpy as np

#Heat of Formatin data from NIST
ethylene = 52.4 #kJ/mol
butadiene = 108.8 #kJ/mol
print('According to NIST, the energy of reaction =', butadiene - 2*ethylene, 'kJ/mol.')

l = 1.4e-10 #m, length of C-C bond
hbar = 1.05457e-34 #J*s
me = 9.109e-31 #kg
ethyl_n = 4*1**2 #4 n1 electrons
buta_n = 2*(1**2+2**2) #2 n1 + 1 n2 electrons

Erxn = (buta_n*np.pi**2*hbar**2)/(2*me*(3*l)**2) - (ethyl_n*np.pi**2*hbar**2)/(2*me*l**2) #J/molecule
E_rxn = Erxn*6.022e23/1000 #kJ/mol
print('Using the particle in a box method, the energy of reaction =',round(E_rxn,1),'kJ/mol. ')
print('This model isn\'t perfect beacause the potential is not zero or infinite in real life, \n and the model ignores interaction between nucleus and electrons.')


I am working on the file "Homework/HW5-soln.ipynb".
The first task is:
6. This particle-in-a-box model has many flaws, not the least of which is that the ends of the polyene “box” are not infinitely high potential walls. In a somewhat better model the π electrons would travel in a finite-depth potential well. State two things that would change from the infinite depth to the finite depth model.
When wall potential drops from infinity to finite value,

Number of bound states/levels will drop from infinite to finite (molecules will eventually escape the box at high enough energy).

It's possible for electrons to tunnel into once forbidden region.

Energies of bound states decreases.

Quantum mechanics of vibrating NO.
The diatomic nitric oxide (NO) is an unusual and important molecule. It has an odd number of electrons, which is a rarity for stable molecule. It acts as a signaling molecule in the body, helping to regulate blood pressure, is a primary pollutant from combustion, and is a key constituent of smog. It exists in several isotopic forms, but the most common, ${}^{14}$N= ${}^{16}$O, has a bond length of 1.15077 Å and vibrational force constant of 1594.8 N/m.
7. Compute the reduced mass $\mu$ (amu), harmonic vibrational frequency (cm$^{-1}$), and zero point vibrational energy (kJ/mol) of  ${}^{14}$N= ${}^{16}$O.  Recall $1/\mu=1/M_\text{N} + 1/M_\text{O}$.
Can you write Python code for it?

import numpy as np

MN = 14 #amu
MO = 16 #amu
k = 1594.8 #N/m
l = 1.15077 #Angstroms
conv = 6.022e26 #amu to kg
h = 6.626e-34 # m^2 kg/s
c = 299792458 #m/s, Speed of Light
N = 6.022e23 #molecules/mole

Mred = 1/(1/MN+1/MO) #amu
print('The reduced mass is',round(Mred,2), 'amu.')

vibfreq = 1/(2*np.pi)*np.sqrt(k/Mred*conv/(c**2)/(100**2)) #cm^-1

print('The harmonic vibrational frequency is',round(vibfreq,2), 'cm^-1.')

E0 = .5*h*vibfreq*c*100*N/1000
print('The zero point vibrational energy is', round(E0,2),'kJ/mol.')


I am working on the file "Homework/HW5-soln.ipynb".
The first task is:
9. The normalized ground vibrational wavefunction of N=O can be written
$$\Psi_{\upsilon=0}(x) = \left ({\frac{1}{\alpha\sqrt{\pi}}}\right )^{1/2}e^{-x^2/2\alpha^2}, \quad x = R-R_{eq}, \quad \alpha = \left ({\frac{\hbar^2}{\mu k}}\right )^{1/4}$$
where $x = R-R_{eq}$.  Calculate the probability for an ${}^{14}N={}^{16}O$ molecule to have a bond length outside the classical limits. This is an example of quantum mechanical tunneling.
Can you write Python code for it?

from sympy import *
a = 1 # in this case, a can be any number
x = Symbol('x')
pi = integrate(1/a/sqrt(pi)*exp(-x**2/a**2),(x,-a,a))
print('The probability of being inside the classical limits is:')
pprint(pi)
print('Therefore, the probability of being outside the classical limits is')
pprint(1-pi)
print('This is equal to 0.1523.')


I am working on the file "Homework/HW6-soln.ipynb".
The first task is:
10. Determine and indicate on your plot $\langle r\rangle$, the expectation value of the distance of the electron from the nucleus.
$\langle r\rangle = \int_{0}^{\infty}rP_{20}dr = \int_{0}^{\infty}\frac{\rho^3}{2}(1-\rho/2)^2e^{-\rho}dr = a_0\int_{0}^{\infty}\frac{\rho^3}{2}(1-\rho/2)^2e^{-\rho}d\rho$
Can you write Python code for it?

from sympy import *
rho = symbols('rho')
I = integrate(rho**3/2*(1-rho/2)**2*exp(-rho),(rho,0,oo))
print('The expectation value of the distance of the electron from the nucleus is',I,"* a0.")


I am working on the file "Homework/HW6-soln.ipynb".
The first task is:
11. Determine and indicate on your plot  $r_{MP}$, the most probable distance of the electron from the nucleus.
Can you write Python code for it?

print("Possible solutions are ", solve(diff(rho**2/2*(1-rho/2)**2*exp(-rho),rho),rho))
print('Comparing these solutions, the universal maximum occurs at sqrt(5) + 3')


I am working on the file "Homework/HW6-soln.ipynb".
The first task is:
12. Determine and indicate on your plot the maximum classical distance of the electron from the nucleus in this orbital.
Classical theory states that orbitals energy must equals to Coulombic energy: $$-\frac{\hbar^2}{2m_ea_o^2}\frac{1}{N^2} = -\frac{e^2}{4\pi\epsilon_0}\frac{1}{r}, where\quad N=2\quad and \quad a_0 = \frac{4\pi\epsilon_0\hbar^2}{m_ee^2}$$
$$r_{max,classic} = 8a_0$$
13. What is the probability of finding the electron beyond the classical distance? (Evaluate the necessary integral numerically.)
Can you write Python code for it?

rho_ = symbols('rho_')
I = integrate(rho_**2/2*(1-rho_/2)**2*exp(-rho_),(rho_,8,oo)) #intrgrate from 8 to infinity
print("Prob = %f"%I)


I am working on the file "Homework/HW6-soln.ipynb".
The first task is:
2. Imagine that the NO molecule is adsorbed flat on a surface upon which it is free to rotate. Plot out the energies of the four lowest-energy rotational quantum states, in units of $\tilde{B}$, being sure to include appropriate quantum numbers and degeneracies. Also indicate the total rotational angular moment of each state, in units of $\hbar$.
Since we are looking at a molecule adsorbed flat on a surface, we will use the 2-D rigid rotor model.
$E_{ml} = \frac{\hbar^2}{2I}m_l^2$
The four lowest-energy rotational quantum states are: $m_l = \pm 0,\pm 1, \pm2, \pm3$

3. Whether light can induce an NO to jump from some rotational level $m_l$ to some other one $m_l^\prime$ is determined by whether the transition dipole moment integral $\langle\psi_{m_l}\lvert x\rvert\psi_{m_l'}\rangle$ is zero or non-zero.  Find the selection rule  on $\Delta m_l$ that make  the integral non-zero.  Recall that $x$ can be written $r \cos\phi$  in polar coordinates.
Wave Function for 2-D rotor model: $\Psi_{m_l}(\phi) = \frac{1}{\sqrt{2\pi}}e^{-im_l\phi}, m_l = 0,\pm1,\pm2,etc$
Transition dipole moment integral: $<\psi_{m_l}|x|\psi_{m_l'}> = \int_{0}^{2\pi}\frac{1}{\sqrt{2\pi}}e^{-im_l\phi}xe^{-im_l'\phi} = \frac{r}{2\pi}\int_{0}^{2\pi}e^{i\Delta m_l\phi}d\phi$
$cos\phi = \frac{1}{2} (e^{-i\phi}+e^\phi)$
$<\psi_{m_l}|x|\psi_{m_l'}> = \int_{0}^{2\pi}\frac{r}{4\pi}e^{i(\Delta m_l-1)\phi}e^{i(\Delta m_l+1)\phi}d\phi $
For an integer $n$, we can have $\int_{0}^{2\pi}e^{ni\phi}d\phi \neq 0$ when n = 0
We can have $<\psi_{m_l}|x|\psi_{m_l'}> \neq 0$ only when $\Delta m_l = \pm1$
4. Use your selection rule to determine the frequencies, in wavenumbers, of the four lowest-energy rotational transitions of an ${}^{14}$N=${}^{16}$O adsorbed flat on a surface.
$\Delta E_{m_{l0}\rightarrow m_{l1}} = B$
$\Delta E_{m_{l1}\rightarrow m_{l2}} = 3B$
$\Delta E_{m_{l2}\rightarrow m_{l3}} = 5B$
$\Delta E_{m_{l3}\rightarrow m_{l4}} = 7B$
Wavenumber
$\tilde{v}{m{l0}\rightarrow m_{l1}} = \frac{B}{hc}$
$\tilde{v}{m{l1}\rightarrow m_{l2}} =...
Can you write Python code for it?


I am working on the file "Homework/HW7-soln.ipynb".
The first task is:
10. Why, qualitatively, do the energies vary as they do?
*There is a big energy decrease as it goes across the series because the electrostatic attraction of the nucleus for electrons increases as the
the number of protons increases.
11. Compare the energies of the highest-energy (valence) electrons compare across the series. Determine the wavelength of light necessary to remove each valence electron. What range of the spectrum is this light in?
Can you write Python code for it?


I am working on the file "Homework/HW7-soln.ipynb".
The first task is:
3. What does the variational principle say about the expectation value of the energy of your guess as you vary a parameter $\gamma$ in your guess, $R_{10}=e^{-\gamma r^2}$?  Suggest a strategy for determining the "best" $\gamma$.
The variational principle says true wavefunction energy is always lower bound on energy of any trial wavefunction.
$$\langle ψ_\text{trial}^λ | \hat{H} | ψ_\text{trial}^λ\rangle =E_\text{trial}^λ \geq E_0$$
We can get the "best" $\gamma$ by optimizing the wavefunction with respect to variational parameter: $$\frac{\partial\langle E\rangle}{\partial\gamma} = 0$$
3.5 Extra credit: Determine the best value of $\gamma$.  Show and carefully justify your work to receive credit.
Normalize $R_{10}$: $\int_{0}^{\infty}r^2C^2e^{-2\gamma r^2}dr = 1$
$$C = \sqrt \frac{1}{\int_{0}^{\infty}e^{-2\gamma r^2}r^2dr}$$
$$\therefore \hat{H} = -\frac{1}{2}\frac{d^2}{dr^2} - \frac{1}{r}\frac{d}{dr}-\frac{1}{r}$$
$$\frac{d(\tilde{R}{10})}{dr}= -2\gamma rCe^{-\gamma r^2} $$
$$\frac{d^2(\tilde{R}{10})}{dr^2}=-2\gamma Ce^{-\gamma r^2}+4\gamma ^2 r^2Ce^{-\gamma r^2}$$
$$\hat{H}\tilde{R}{10}(r) = -\frac{1}{2}\frac{d^2(\tilde{R}{10})}{dr^2} - \frac{1}{r}\frac{d(\tilde{R}{10})}{dr}-\frac{1}{r}(\tilde{R}{10}) = \gamma Ce^{-\gamma r^2}-2\gamma ^2r^2Ce^{- \gamma r^2} +2\gamma Ce^{-\gamma r^2} -\frac{Ce^{-\gamma r^2}}{r} = \frac{Ce^{-\gamma r^2}(-2\gamma ^2r^3+3\gamma r-1)}{r}$$
$\langle E\rangle = \int_{0}^{\infty}\tilde{R}{10}(r)\hat{H}\tilde{R}{10}(r)r^2dr = \int_{0}^{\infty} C^2(-2\gamma^2 r^4+3\gamma r^2-r)e^{-2\gamma r^2} dr$
Can you write Python code for it?

gamma = symbols('gamma',positive=True) # We know the gamma has to be positive, or the R10 would be larger when r increase.
r = symbols("r",positive=True)
C = sqrt(1/integrate(exp(-2*gamma*r**2)*r**2,(r,0,oo)))
E = C**2*integrate((-2*gamma**2*r**4+3*gamma*r**2-r)*exp(-2*gamma*r**2),(r,0,oo)) # expectation value of energy as a function of gamma
gamma_best=solve(diff(E,gamma),gamma)

print("Expectation of energy:");print(E)
print("Best value of gamma is: %s, which equals to %f."% (gammabest,8/(9*np.pi)))

import math
gamma_best = 8/(9*np.pi)
E_best = 8*math.sqrt(2)*gamma_best**(3/2)*(-1/(4*gamma_best) + 3*math.sqrt(2)*math.sqrt(np.pi)/(32*math.sqrt(gamma_best)))/math.sqrt(np.pi)
print("Energy with the best gamma: %0.3f eV."%E_best)

import matplotlib.pyplot as plt

gamma = np.linspace(0.001,1.5,10000)
E = []
for x in gamma:
    E.append(8*math.sqrt(2)*x**(3/2)*(-1/(4*x) + 3*math.sqrt(2)*math.sqrt(np.pi)/(32*math.sqrt(x)))/math.sqrt(np.pi))

plt.plot(gamma,E)
plt.xlabel("Gamma")
plt.ylabel("Energy(eV)")
plt.axvline(x=8/(9*np.pi),color='k',linestyle='--')
plt.axhline(y=E_best,color='k',linestyle='--')
plt.annotate('Lowest energy spot', xy=(8/(9*np.pi), E_best), xytext=(0.5,-0.2), arrowprops=dict(facecolor='black'))
plt.show()


I am working on the file "Homework/HW7-soln.ipynb".
The first task is:
So the normalized 1s wavefunction is $\tilde{R}_{10}(r) = \frac{2}{\sqrt[4]{\pi}} 2^{\frac{3}{4}} e^{-r^2} = (\frac{128}{\pi}) ^ {\frac{1}{4}} e^{-r^2} $.
2. Calculate the expectation value of the energy of your normalized guess.  Is it greater or less than the true value?
$\because$ 1s orbital, n=1,l=0
$$\therefore \hat{H} = -\frac{1}{2}\frac{d^2}{dr^2} - \frac{1}{r}\frac{d}{dr}-\frac{1}{r}$$
$$\frac{d(\tilde{R}{10})}{dr}= -2rCe^{-r^2} $$
$$\frac{d^2(\tilde{R}{10})}{dr^2}=-2Ce^{-r^2}+4r^2Ce^{-r^2}$$
$$\hat{H}\tilde{R}{10}(r) = -\frac{1}{2}\frac{d^2(\tilde{R}{10})}{dr^2} - \frac{1}{r}\frac{d(\tilde{R}{10})}{dr}-\frac{1}{r}(\tilde{R}{10}) = Ce^{-r^2}-2r^2Ce^{-r^2} +2Ce^{-r^2} -\frac{Ce^{-r^2}}{r} = \frac{Ce^{-r^2}(-2r^3+3r-1)}{r}$$
The expectation value of the energy:
$$\langle E\rangle = \int_{0}^{\infty}\tilde{R}{10}(r)\hat{H}\tilde{R}{10}(r)r^2dr = \int_{0}^{\infty} C^2(-2r^4+3r^2-r)e^{-2r^2} dr$$
Can you write Python code for it?

E = C**2*integrate((-2*r**4+3*r**2-r)*exp(-2*r**2),(r,0,oo))
print('Expected value is %0.4f Ha.'%E)

# Hydrogen atom energy equation is given in class notes
n=1
E_true = -1/(2*n**2) # unit Ha
print('The ture value is %0.4f Ha. So the expected value is greater than the true value.' %E_true)


I am working on the file "Homework/HW8-soln.ipynb".
The first task is:
11. Compute the corresponding vibrational spectra.  Could you distinguish these molecules by their spectra?

Log into the Webmo server https://www.webmo.net/demoserver/cgi-bin/webmo/login.cgi using "guest" as your username and password.
Select the job with the optimized geometry and open it.
Use the right arrow at the bottom to proceed to the Computational Engines.
Select Orca
Select "Vibrational frequency," “B3LYP” functional and the default def2-SVP basis set.
Select the right arrow to run the calculation.
From the job manager window choose the completed calculation to view the results.

C2H2

C2H4

C2H6

The vibrational spectra are clearly very different, so these molecules can be distinguished by IR.
12. Compute the structure and energy of H$_2$.   Use it to compare the energies to hydrogenate acetylene to ethylene and ethylene to ethane.  Which is easier to hydrogenate?  Can you see why selective hydrogenation of acetylene to ethylene is difficult to do?
Can you write Python code for it?


I am working on the file "Homework/HW8-soln.ipynb".
The first task is:
9. Use your results to determine the zero-point-corrected bond energy of your molecule. How does this model compare with the experimental value?
Can you write Python code for it?

# Get experimental vibrational zero-point energy from NIST database: https://cccbdb.nist.gov/exp1x.asp
nu_CO_exp = 1084.9 # cm^-1
nu_BN_exp = 760.2 # cm^-1
nu_BeO_exp = 728.5 # cm^-1

print('CO Molecule:')
# Note: E_ZPC = E_min + ZPE_harmonic_oscillator
h = 6.62607e-34
NA = 6.02214e23
J = 1.6022e-19 # eV to J
E_min_CO = (-16.300903*J)*NA/1000 # converted from eV to kJ/mol from problem 8

# Calculations
E0_CO = (0.5*h*nu_CO*100*c)*NA/1000 # kJ/mol, ZPE harmonic oscillator
EB_CO = E_min_CO + E0_CO # kJ/mol, ZPC bond energy
# Experiments
E0_CO_exp = (0.5*h*nu_CO_exp*100*c)*NA/1000
EB_CO_exp = E_min_CO + E0_CO_exp
print('|E_ZPC| = %f kJ/mol < %f kJ/mol.'%(-EB_CO,-EB_CO_exp))

print('BN Molecule:')
# Note: E_ZPC = E_min + ZPE_harmonic_oscillator
h = 6.62607e-34
NA = 6.02214e23
J = 1.6022e-19 # eV to J
E_min_BN = (-4.633537*J)*NA/1000 # converted from eV to kJ/mol from problem 8

# Calculations
E0_BN = (0.5*h*nu_BN*100*c)*NA/1000 # kJ/mol, ZPE harmonic oscillator
EB_BN = E_min_BN + E0_BN # kJ/mol, ZPC bond energy
# Experiments
E0_BN_exp = (0.5*h*nu_BN_exp*100*c)*NA/1000
EB_BN_exp = E_min_BN + E0_BN_exp
print('|E_ZPC| = %f kJ/mol < %f kJ/mol.'%(-EB_BN,-EB_BN_exp))

print('BeO Molecule:')
# Note: E_ZPC = E_min + ZPE_harmonic_oscillator
h = 6.62607e-34
NA = 6.02214e23
J = 1.6022e-19 # eV to J
E_min_BeO = (-5.850784*J)*NA/1000 # converted from eV to kJ/mol from problem 8

# Calculations
E0_BeO = (0.5*h*nu_BeO*100*c)*NA/1000 # kJ/mol, ZPE harmonic oscillator
EB_BeO = E_min_BeO + E0_BeO # kJ/mol, ZPC bond energy
# Experiments
E0_BeO_exp = (0.5*h*nu_BeO_exp*100*c)*NA/1000
EB_BeO_exp = E_min_BeO + E0_BeO_exp
print('|E_ZPC| = %f kJ/mol < %f kJ/mol.'%(-EB_BeO,-EB_BeO_exp))


I am working on the file "Homework/HW9-soln.ipynb".
The first task is:
10. Derive an expression for the entropy $S$ per molecules and plot vs. temperature, again assuming $\theta = 300$ K.
$S = \frac{U-A}{T}= \frac{U}{T} + k_B\ln q = \frac{2\varepsilon e^{-\beta\varepsilon} + 6\varepsilon e^{-2\beta\varepsilon}}{(1 + 2e^{-\beta\varepsilon} + 3e^{-2\beta\varepsilon})T} + k_B\ln(1 + 2e^{-\beta\varepsilon} + 3e^{-2\beta\varepsilon})$
Can you write Python code for it?

S = (U-A)/T

plt.plot(T,S)
plt.xlabel('Temperature (K)')
plt.ylabel('Entropy (J/K)')
plt.title('Three-state system entropy')
plt.show()


I am working on the file "Homework/HW9-soln.ipynb".
The first task is:
4. Suppose two identical such boxes are brought into thermal contact and allowed to come to equilibrium. Calculate the change in internal energy $\Delta U$ and in entropy $\Delta S$ associated with this process.
Can you write Python code for it?

from math import factorial
import numpy as np

k = 1.380649e-23 #J/K
epsilon = 1. # some amount of energy

def Omega(N,q):
    return factorial(N)/(factorial(q)*factorial(N-q))

def S(N,q):
    return k*np.log(Omega(N,q))

def U(N,q):
    return q*epsilon

#2 identical Boxes, separated
N = 4; q = 2

Sseparated = S(N,q)
Useparated = U(N,q)

#2 Boxes, Combined
N2 = N*2
q2 = q*2

Scombined = S(N2,q2)
Ucombined = U(N2,q2)

deltaS = Scombined - 2*Sseparated
deltaU = Ucombined - 2*Useparated
print('The change in entropy is',deltaS,"J/K")
print('The change in energy is',deltaU,"epsilon")
print('The energy of a closed system is constant (first law)')
print('The entropy change in any spontaneous process in a closed system is > 0')


I am working on the file "Homework/HW9-soln.ipynb".
The first task is:
7. Derive an expression for the internal energy $U$ per molecule by summing over the possible microstates weighted by their probabilities. Plot the average energy vs. temperature, assuming  $\theta =300$ K.
$U = 0P(0) + \varepsilon P(\varepsilon) + 2\varepsilon P(2\varepsilon) = \varepsilon\frac{2e^{-\beta\varepsilon}}{q} + 2\varepsilon\frac{3e^{-2\beta\varepsilon}}{q} = \frac{2\varepsilon e^{-\beta\varepsilon} + 6\varepsilon e^{-2\beta\varepsilon}}{q}$
Can you write Python code for it?

epsilon = theta*k # as we needed epsilon in expression
U = (2.*epsilon * np.exp(-theta/T) + 6.*epsilon * np.exp(-2.*theta/T))/ Ptot # average energy J per particle
plt.plot(T,U)
plt.xlabel('Temperature (K)')
plt.ylabel('Average energy (J/particle)')
plt.title('Average energy')
plt.show()


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
(可以跳过阅读)下面这个函数用来保存轮廓图，生成图片，groundtruth，以作对比。
Can you write Python code for it?

from utils import show
def sample_images(dataloader, G, device):
    """Saves a generated sample from the validation set"""
    imgs = next(iter(dataloader))
    real_A = imgs["A"].to(device)
    real_B = imgs["B"].to(device)
    fake_B = G(real_A)
    img_sample = torch.cat((real_A.data, fake_B.data, real_B.data), -2)
    show(torchvision.utils.make_grid(img_sample.cpu().data, nrow=5, normalize=True))


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
visualize_results和run_gan的代码不再详细说明.
Can you write Python code for it?

def visualize_results(G, device, z_dim, class_num, class_result_size=5):
    G.eval()

    z = torch.rand(class_num * class_result_size, z_dim).to(device)

    y = torch.LongTensor([i for i in range(class_num)] * class_result_size)
    y_vec = vecs[y.long()].to(device)
    g_z = G(z, y_vec)

    show(torchvision.utils.make_grid(denorm(g_z.detach().cpu()), nrow=class_num))

def run_gan(trainloader, G, D, G_optimizer, D_optimizer, loss_func, n_epochs, device, latent_dim, class_num):
    d_loss_hist = []
    g_loss_hist = []

    for epoch in range(n_epochs):
        d_loss, g_loss = train(trainloader, G, D, G_optimizer, D_optimizer, loss_func, device,
                               latent_dim, class_num)
        print('Epoch {}: Train D loss: {:.4f}, G loss: {:.4f}'.format(epoch, d_loss, g_loss))

        d_loss_hist.append(d_loss)
        g_loss_hist.append(g_loss)

        if epoch == 0 or (epoch + 1) % 10 == 0:
            visualize_results(G, device, latent_dim, class_num)

    return d_loss_hist, g_loss_hist


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
作业 :
1. 在D中,可以将输入图片和labels分别通过两个不同的卷积层然后在维度1合并(通道上合并),再一起送去接下来的网络结构.网络部分结构已经在DCDiscriminator中写好,请在补充forward函数完成上述功能并再次使用同样的数据集训练CGAN.与之前的结果对比,说说有什么不同?
Can you write Python code for it?

class DCDiscriminator1(nn.Module):
    def __init__(self, image_size=32, input_channel=1, class_num=3, sigmoid=True):
        super().__init__()
        self.image_size = image_size
        self.input_channel = input_channel
        self.class_num = class_num

        self.fc_size = image_size // 8

        #       model : img -> conv1_1
        #               labels -> conv1_2
        #       (img U labels) -> Conv2d(3,2,1) -> BN -> LeakyReLU
        #       Conv2d(3,2,1) -> BN -> LeakyReLU

        self.conv1_1 = nn.Sequential(nn.Conv2d(input_channel, 64, 3, 2, 1),
                                     nn.BatchNorm2d(64))
        self.conv1_2 = nn.Sequential(nn.Conv2d(class_num, 64, 3, 2, 1),
                                     nn.BatchNorm2d(64))

        self.conv = nn.Sequential(
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 256, 3, 2, 1),
            nn.BatchNorm2d(256),
            nn.LeakyReLU(0.2),
            nn.Conv2d(256, 512, 3, 2, 1),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),
        )

        # fc: Linear -> Sigmoid
        self.fc = nn.Sequential(
            nn.Linear(512 * self.fc_size * self.fc_size, 1),
        )
        if sigmoid:
            self.fc.add_module('sigmoid', nn.Sigmoid())
        initialize_weights(self)

    def forward(self, img, labels):
        """
        img : input image
        labels : (batch_size, class_num, image_size, image_size)
                the i-th channel is filled with 1, and others is filled with 0.
        """
        """
        To Do
        """
        input_img = self.conv1_1(img)
        input_labels = self.conv1_2(labels)
        input_ = torch.cat((input_img, input_labels), dim=1)
        out = self.conv(input_)
        out = out.view(out.shape[0], -1)
        out = self.fc(out)

        return out

# hyper params
# device : cpu or cuda:0/1/2/3
device = torch.device('cuda:2')

# G and D model
G = DCGenerator(image_size=image_size, latent_dim=latent_dim,...


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
作业：

只用L1 Loss的情况下训练pix2pix.说说有结果什么不同.
Can you write Python code for it?

# Loss functions
criterion_pixelwise = torch.nn.L1Loss().to(device)

# Initialize generator and discriminator
G = GeneratorUNet().to(device)
D = Discriminator().to(device)
G.apply(weights_init_normal)
D.apply(weights_init_normal)

optimizer_G = torch.optim.Adam(G.parameters(), lr=lr, betas=betas)
optimizer_D = torch.optim.Adam(D.parameters(), lr=lr, betas=betas)

for epoch in range(n_epochs):
    for i, batch in enumerate(dataloader):

        #  G:B -> A
        real_A = batch["A"].to(device)
        real_B = batch["B"].to(device)

        # ------------------
        #  Train Generators
        # ------------------

        optimizer_G.zero_grad()

        # GAN loss
        fake_B = G(real_A)
        # Pixel-wise loss
        loss_pixel = criterion_pixelwise(fake_B, real_B)

        # Total loss
        loss_G = loss_pixel

        loss_G.backward()

        optimizer_G.step()

    # Print log
    print(
        "\r[Epoch %d/%d] [Batch %d/%d] [G loss: %f]"
        % (
            epoch,
            n_epochs,
            i,
            len(dataloader),
            loss_G.item()
        )
    )

    # If at sample interval save image
    if epoch == 0 or (epoch + 1) % 5 == 0:
        sample_images(val_dataloader, G, device)


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
接下来让我们查看一下各个类上真实的手写体数据集的数据吧.(运行一下2个cell的代码,无需理解)
Can you write Python code for it?

def denorm(x):
    # denormalize
    out = (x + 1) / 2
    return out.clamp(0, 1)

from utils import show
"""
you can pass code in this cell
"""
# show mnist real data
train_dataset = load_mnist_data()
images = []
for j in range(5):
    for i in range(10):
        images.append(train_dataset[i * 200 + j][0])
show(torchvision.utils.make_grid(denorm(torch.stack(images)), nrow=10))


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
接着定义一些超参数lambda_pixel
Can you write Python code for it?

# hyper param
n_epochs = 200
batch_size = 2
lr = 0.0002
img_size = 64
channels = 3
device = torch.device('cuda:2')
betas = (0.5, 0.999)
# Loss weight of L1 pixel-wise loss between translated image and real image
lambda_pixel = 1


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
数据集
我们使用我们熟悉的MNIST手写体数据集来训练我们的CGAN,我们同样提供了一个简化版本的数据集来加快我们的训练速度,与上次的数据集不一样的是,这次的数据集包含0到9共10类的手写数字,每类各200张,共2000张.图片同样为28*28的单通道灰度图(我们将其resize到32*32).下面是加载mnist数据集的代码.
Can you write Python code for it?

def load_mnist_data():
    """
    load mnist(0,1,2) dataset
    """

    transform = torchvision.transforms.Compose([
        # transform to 1-channel gray image since we reading image in RGB mode
        transforms.Grayscale(1),
        # resize image from 28 * 28 to 32 * 32
        transforms.Resize(32),
        transforms.ToTensor(),
        # normalize with mean=0.5 std=0.5
        transforms.Normalize(mean=(0.5, ),
                             std=(0.5, ))
        ])

    train_dataset = torchvision.datasets.ImageFolder(root='./data/mnist', transform=transform)

    return train_dataset


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
本次实验使用的是Facade数据集，由于数据集的特殊性，一张图片包括两部分，如下图，左半边为groundtruth，右半边为轮廓，我们需要重写数据集的读取类，下面这个cell是就是用来读取数据集。最终使得我们的模型可以从右边部分的轮廓生成左边的建筑.

(可以跳过阅读)下面是dataset部分代码.
Can you write Python code for it?

import glob
import random
import os
import numpy as np

from torch.utils.data import Dataset
from PIL import Image
import torchvision.transforms as transforms

class ImageDataset(Dataset):
    def __init__(self, root, transforms_=None, mode="train"):
        self.transform = transforms_
        # read image
        self.files = sorted(glob.glob(os.path.join(root, mode) + "/*.*"))

    def __getitem__(self, index):
        # crop image,the left half if groundtruth image, and the right half is outline of groundtruth.
        img = Image.open(self.files[index % len(self.files)])
        w, h = img.size
        img_B = img.crop((0, 0, w / 2, h))
        img_A = img.crop((w / 2, 0, w, h))

        if np.random.random() < 0.5:
            # revese the image by 50%
            img_A = Image.fromarray(np.array(img_A)[:, ::-1, :], "RGB")
            img_B = Image.fromarray(np.array(img_B)[:, ::-1, :], "RGB")

        img_A = self.transform(img_A)
        img_B = self.transform(img_B)

        return {"A": img_A, "B": img_B}

    def __len__(self):
        return len(self.files)


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
生成网络G,一个Encoder-Decoder模型，借鉴了U-Net结构，所谓的U-Net是将第i层拼接到第n-i层，这样做是因为第i层和第n-i层的图像大小是一致的。
判别网络D,Pix2Pix中的D被实现为Patch-D，所谓Patch，是指无论生成的图像有多大，将其切分为多个固定大小的Patch输入进D去判断。
Can you write Python code for it?

import torch.nn as nn
import torch.nn.functional as F
import torch

##############################
#           U-NET
##############################

class UNetDown(nn.Module):
    def __init__(self, in_size, out_size, normalize=True, dropout=0.0):
        super(UNetDown, self).__init__()
        layers = [nn.Conv2d(in_size, out_size, 4, 2, 1, bias=False)]
        if normalize:
            # when baych-size is 1, BN is replaced by instance normalization
            layers.append(nn.InstanceNorm2d(out_size))
        layers.append(nn.LeakyReLU(0.2))
        if dropout:
            layers.append(nn.Dropout(dropout))
        self.model = nn.Sequential(*layers)

    def forward(self, x):
        return self.model(x)

class UNetUp(nn.Module):
    def __init__(self, in_size, out_size, dropout=0.0):
        super(UNetUp, self).__init__()
        layers = [
            nn.ConvTranspose2d(in_size, out_size, 4, 2, 1, bias=False),
            # when baych-size is 1, BN is replaced by instance normalization
            nn.InstanceNorm2d(out_size),
            nn.ReLU(inplace=True),
        ]
        if dropout:
            layers.append(nn.Dropout(dropout))

        self.model = nn.Sequential(*layers)

    def forward(self, x, skip_input):
        x = self.model(x)
        x = torch.cat((x, skip_input), 1)

        return x

class GeneratorUNet(nn.Module):
    def __init__(self, in_channels=3, out_channels=3):
        super(GeneratorUNet, self).__init__()

        self.down1 = UNetDown(in_channels, 64, normalize=False)
        self.down2 = UNetDown(64, 128)
        self.down3 = UNetDown(128, 256)
        self.down4 = UNetDown(256, 256, dropout=0.5)
        self.down5 = UNetDown(256, 256, dropout=0.5)
        self.down6 = UNetDown(256, 256, normalize=False, dropout=0.5)

        self.up1 = UNetUp(256, 256, dropout=0.5)
        self.up2 = UNetUp(512, 256)
        self.up3 = UNetUp(512, 256)
        self.up4 = UNetUp(512, 128)
        self.up5 = UNetUp(256, 64)

        self.final = nn.Sequential(
           ...


I am working on the file "Homework/Principles of Artificial Neural Networks/Week 10 GAN 2/DL_WEEK10.ipynb".
The first task is:
答：
只用L1 loss训练网络的时候，可以观察到网络在一开始并没有像第一次训练得到的结果那样具有各种五颜六色的噪点。一开始的几次迭代可以很迅速地得到建筑的边框痕迹，相对第一次训练的噪点要少很多。但是若干次迭代之后，只用L1 loss的网络生成的假图很模糊，效果比第一次训练的结果差很多。

只用CGAN Loss训练pix2pix(在下面的cell填入对应代码并运行).说说有结果什么不同.
Can you write Python code for it?

# Loss functions
criterion_GAN = torch.nn.MSELoss().to(device)

# Initialize generator and discriminator
G = GeneratorUNet().to(device)
D = Discriminator().to(device)
G.apply(weights_init_normal)
D.apply(weights_init_normal)

optimizer_G = torch.optim.Adam(G.parameters(), lr=lr, betas=betas)
optimizer_D = torch.optim.Adam(D.parameters(), lr=lr, betas=betas)

for epoch in range(n_epochs):
    for i, batch in enumerate(dataloader):
        """
        To Do
        """
        #  G:B -> A
        real_A = batch["A"].to(device)
        real_B = batch["B"].to(device)

        # Adversarial ground truths
        real_label = torch.ones((real_A.size(0), *patch)).to(device)
        fake_label = torch.zeros((real_A.size(0), *patch)).to(device)

        # ------------------
        #  Train Generators
        # ------------------

        optimizer_G.zero_grad()

        # GAN loss
        fake_B = G(real_A)
        pred_fake = D(fake_B, real_A)
        loss_G = criterion_GAN(pred_fake, real_label)

        loss_G.backward()

        optimizer_G.step()

        # ---------------------
        #  Train Discriminator
        # ---------------------

        optimizer_D.zero_grad()

        # Real loss
        pred_real = D(real_B, real_A)
        loss_real = criterion_GAN(pred_real, real_label)

        # Fake loss
        pred_fake = D(fake_B.detach(), real_A)
        loss_fake = criterion_GAN(pred_fake, fake_label)

        # Total loss
        loss_D = 0.5 * (loss_real + loss_fake)

        loss_D.backward()
        optimizer_D.step()

    # Print log
    print(
        "\r[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]"
        % (
            epoch,
            n_epochs,
            i,
            len(dataloader),
            loss_D.item(),
            loss_G.item()
        )
    )

    # If at sample interval save image
    if epoch == 0 or (epoch + 1) % 5 == 0:
        sample_images(val_dataloader, G, device)