I am working on the file "EZGAN.ipynb".
The first task is:
We want to eventually reach a point where the discriminator correctly classifies nearly all real MNIST images as MNIST images, and classifies generated images as MNIST images about 50% of the time. There are several failure modes that we need to avoid:
* Discriminator losses approach zero: this leaves practically no gradients for the generator's optimizer.
* Discriminator losses rise unbounded on generated images: similarly, this leaves practically no gradient for the discriminator to improve, and the generator's training stalls, too, since the gradients it's reading suggest that it has achieved perfect performance.
* Divergent discriminator accuracy: the discriminator learns a shortcut by either classifying everything as real or everything as generated. You can detect this by checking the discriminator's losses on generated images against the discriminator's losses on real images.
To stay balanced between these, we use a controller in the training loop that runs each of the three training operations depending on their losses. Qualitatively speaking, the most rapid improvements in output come when the generator and discriminator are evenly matched; the controller avoids running a training operation when its network shows signs of overpowering the others.
Here's our training loop. You'll need a writable directory in your current working directory called tensorboard for TensorBoard logs, and another one called models to store the five most recent checkpoints.
Recognizable results should begin to appear before 10,000 cycles, and will improve after that. On a fast GPU machine, you can make it to 10,000 cycles in less than 10 minutes. It could take around 10 times as long to run on a desktop CPU. There are lots of random numbers involved, so you'll get different results every time you run this. In particular, it's likely to stall for upwards of 2,000 cycles at a time early on, but it should recover on its own.
Can you write Python code for it?

saver = tf.train.Saver()

sess.run(tf.global_variables_initializer())

gLoss = 0
dLossFake, dLossReal = 1, 1
d_real_count, d_fake_count, g_count = 0, 0, 0
for i in range(50000):
    real_image_batch = mnist.train.next_batch(batch_size)[0].reshape([batch_size, 28, 28, 1])
    if dLossFake > 0.6:
        # Train discriminator on generated images
        _, dLossReal, dLossFake, gLoss = sess.run([d_trainer_fake, d_loss_real, d_loss_fake, g_loss],
                                                    {x_placeholder: real_image_batch})
        d_fake_count += 1

    if gLoss > 0.5:
        # Train the generator
        _, dLossReal, dLossFake, gLoss = sess.run([g_trainer, d_loss_real, d_loss_fake, g_loss],
                                                    {x_placeholder: real_image_batch})
        g_count += 1

    if dLossReal > 0.45:
        # If the discriminator classifies real images as fake,
        # train discriminator on real values
        _, dLossReal, dLossFake, gLoss = sess.run([d_trainer_real, d_loss_real, d_loss_fake, g_loss],
                                                    {x_placeholder: real_image_batch})
        d_real_count += 1

    if i % 10 == 0:
        real_image_batch = mnist.validation.next_batch(batch_size)[0].reshape([batch_size, 28, 28, 1])
        summary = sess.run(merged, {x_placeholder: real_image_batch, d_real_count_ph: d_real_count,
                                    d_fake_count_ph: d_fake_count, g_count_ph: g_count})
        writer.add_summary(summary, i)
        d_real_count, d_fake_count, g_count = 0, 0, 0

    if i % 1000 == 0:
        # Periodically display a sample image in the notebook
        # (These are also being sent to TensorBoard every 10 iterations)
        images = sess.run(generator(3, z_dimensions))
        d_result = sess.run(discriminator(x_placeholder), {x_placeholder: images})
        print("TRAINING STEP", i, "AT", datetime.datetime.now())
        for j in range(3):
            print("Discriminator classification", d_result[j])
            im =...


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
#### 3.3. Posterior distributions

[3.5] Plot the posterior probabilities for each hour slot
Can you write Python code for it?

# <SOL>
s = np.linspace(1, 50, 1000)

sMAP24 = K24 / (z24 + 1)
plt.figure()
for h in np.arange(0, 24, 4):
    plt.plot(s, PP(s, z24[h], K24[h]), label='h = {}'.format(h))
    plt.plot(sMAP24[h], PP(sMAP24[h], z24[h], K24[h]),'*r')
    plt.plot(sMSE24[h], PP(sMSE24[h], z24[h], K24[h]),'*g')
#plt.plot(s, np.exp(-s), label='Prior $p_{S}(s)$')
plt.xlim((s[0], s[-1]))
plt.ylim((0, plt.ylim()[1]))
plt.legend()
plt.show()
# </SOL>


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
1. Time between calls
Let's look at the data to give us an idea of the typical activity for a given time period.

[1.1] Plot the histogram of the timestamps and look at the behaviour of the data.
Can you write Python code for it?

# Histograms of call times
# <SOL>
plt.hist(t, bins=100)
plt.xlabel('Time (hours)')
plt.ylabel('No. of incoming calls')
plt.xlim([0, n_days*H])
plt.show()
# </SOL>


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
2. Parameter estimation.
The company has decided to build a statistical model to characterize the activity in the hosted call centers. Inspection of the histogram suggests that the time between incoming calls follows an exponential distribution:
$$
p_{X|S}(x|s) = s \exp(−s x), \qquad x > 0
$$
where random variable $X$ represents the time before a new call arrives, and $s$ is the parameter of the exponential distribution. Thus, we will use the dataset to estimate parameter $s$.
2.1. Maximum likelihood
Our first approach will be to find a Maximum Likelihood estimation of $s$.

[2.1]. Obtain the maximum likelihood estimator or $S$ based on the observations in x_all, and save it in variable sML. You will need to compute two variables that will be used several times along this section:
$K$: The number of observations in x_all
$z = \sum_{k=0}^{K-1} x^{(k)}$, where $x^{(k)}$ are the components of x_all.
Can you write Python code for it?

# z = <FILL IN>
z = np.sum(x_all)
# K = <FILL IN>
K = len(x_all)
# sML = <FILL IN>
sML = K / z
javascript(url=url)
Math(r'\hat{s}_\text{ML} = ' + str(sML))


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
3.1. Hour-dependent model
According to this, we can make a different model for each time of the day. To do so, we will keep the asumption that the time between incoming calls follows an exponential distribution
$$
p_{X|S,}(x \mid s) = s \exp(−s x), \qquad x > 0
$$
However, we will now assume that parameter $s$ can take a different value from hour to hour. Therefore, we must estimate a different parameter $S$ for every hour.
To do so, we will need to split the data in 24 groups, one per hour, and compute specific variables $z$ and $K$ for each group.

[3.2] Split the dataset in 24 groups, assigning the data to each group depending on the hour of the starting time. Then, compute parameters $z$ and $K$ for each group, storing them in numpy arrays z24 and K24.
Can you write Python code for it?

# <SOL>
z24 = np.zeros(24)
K24 = np.zeros(24).astype(int)

h2 = np.fix(t) % 24
hx = list(zip(h2, x_all))

for h in range(24):
    x24 = np.array([u[1] for u in hx if u[0] == h])
    z24[h] = np.sum(x24)
    K24[h] = x24.shape[0]

# </SOL>
# Check if your variables are ok.
# (Note that his is not a full test. Passing it does not
# guarantee that variables have been correctly computed)
if np.sum(K24) == len(x_all):
    print("Test for variable K passed.")
else:
    print("Error in variable K.")
if np.sum(z24) == np.sum(x_all):
    print("Test for variable z passed.")
else:
    print("Error in variable z.")

for h in range(24):
    x24 = x_all[h==h2[:-1]]
    z24[h] = np.sum(x24)
    K24[h] = x24.shape[0]

# </SOL>
# Check if your variables are ok.
# (Note that his is not a full test. Passing it does not
# guarantee that variables have been correctly computed)
if np.sum(K24) == len(x_all):
    print("Test for variable K passed.")
else:
    print("Error in variable K.")
if np.sum(z24) == np.sum(x_all):
    print("Test for variable z passed.")
else:
    print("Error in variable z.")


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
However, you can visually verify that the posterior distributions for $h=0$ and $h=8$ have less variance than that for $h=16$, why? This is because the prior distribution is in agreement with the data for $h=0$ and $h=8$ (in borth cases, $\hat{s}_\text{MSE}$ is smaller than 5). The larger variance for $h=16$ is a consequence of the higher uncertainty about $s$ created by the discrepancy between the prior and the observations.
In any case, for any value of $h$, more data is always better than less data. We can observe that, for any value of $h$, the variance of the posterior distribution tends to decrease when more data are used.

[3.6] Take $h$=16. For $d=1,...,5$, compute the variance of the posterior distribution of $s$ given only the data at hour $h$ up to day $d$. Plot the minimum MSE as a function of $d$
Can you write Python code for it?

# <SOL>
tx = list(zip(t, x_all))
h0 = 16

z5 = np.zeros(n_days)
K5 = np.zeros(n_days).astype(int)

for d in range(5):
    x5 = np.array([u[1] for u in tx if u[0] < 24*(d+1) and np.fix(u[0]) % 24 == h0])
    z5[d] = np.sum(x5)
    K5[d] = x5.shape[0]

mmse5 = (K5+1)/(z5+1)**2

plt.figure()
plt.stem(mmse5)
plt.ylim(0, plt.ylim()[1])
plt.show()
# </SOL>


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
Incidentally, note that, since $\hat{s}_\text{MSE}$ is the posterior mean, the conditional MSE, which is given by,
$$
   \mathbb{E}\left{(S-\hat{s}_\text{MSE})^2| {\bf z}\right}
   $$
is equal to the variance of the posterior distribution.

[2.7.] [OPTIONAL] Compute the probability that the true parameter was not further than two standard deviations from the posterior mean, that is

$$
   P\left{\hat{s}\text{MSE} - 2 \sqrt{v\text{MSE}} \le S \le
           \hat{s}\text{MSE} + 2 \sqrt{v\text{MSE}}\mid \mathbf{z}\right}
   $$
   Save it in variable p
Can you write Python code for it?

from scipy.stats import gamma
# <SOL>
sc = 1/(z+1)
upper = sMSE + 2*np.sqrt(mMSE)
lower = sMSE - 2*np.sqrt(mMSE)
p = 1 - (gamma.cdf(upper, K+1, scale=sc) - gamma.cdf(lower, K+1, scale=sc))

# </SOL>

javascript(url=url)
Math(r'P\left\{\hat{s}_\text{MSE} - 2 \sqrt{v_\text{MSE}} \le S \le ' +
             r'\hat{s}_\text{MSE} + 2 \sqrt{v_\text{MSE}}\right\} = ' + str(p) )


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
You should observe that, as expected, each posterior distribution is centered around its respective estimate $\hat{s}_\text{MSE}$, (i.e. around sMSE24[0], sMSE24[8] and sMSE24[16].
Can you write Python code for it?


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
[2.2]. Plot the log of the likelihood as a function of $s$ (in the appropriate range of $s$) and verify that the ML estimate reaches the maximum.
Can you write Python code for it?

# <SOL>
s = np.linspace(1, 50, 101)

def Lp(s, z, K):
    return K*np.log(s) - s*z

Lmax = Lp(sML, z, K)
Ls = Lp(s, z, K)

plt.plot(s, Ls)
plt.stem([sML], [Lmax])
plt.xlim((s[0], s[-1]))
plt.ylim([np.min(Ls), plt.ylim()[1]])
plt.xlabel('$s$')
plt.ylabel('Log-likelihood')
plt.show()
# </SOL>

# <FILL IN>


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
[3.3] Compute the ML and the MSE estimates for each hour. Store them in vectors sML24 and sMSE24 and plot them as a function of the hour in the day.
Can you write Python code for it?

# <SOL>
sML24 = K24 / z24
sMSE24 = (K24+1) / (z24+1)

plt.plot(sML24, ':.', label='sML')
plt.plot(sMSE24, ':.', c='red', label='sMSE')
plt.xlabel('Hour')
plt.ylabel('s')
plt.xlim(0, 23)
plt.legend(loc='upper left')
plt.show()
# </SOL>


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
[3.4] One may wonder if spliting the data in segments provides a better model for the time between calls. The joint data likelihood is a useful way to get a first quantitative evaluation of the new model.
Compute the maximum log-likelihood for the joint model, and save it in variable L24max. Compare the result with the value of Lmax computed in [2.2].
To compute the maximum log-likelihood of the joint model, take into account that the observations are independent, so that L24max is the sum of the values of the maximum log-likelihood computed for every hour.
Can you write Python code for it?

# <SOL>
# Maximum log-likelihood per each hour
Lp24 = [Lp(sML24[h], z24[h], K24[h]) for h in range(24)]
# Overall maximum likelihood
Lmax24 = np.sum(Lp24)
# </SOL>

print('Maximum log-likelihood of the simple model: {}'.format(Lmax))
print('Maximum log-likelihood of the hour-dependent model: {}'.format(Lmax24))


I am working on the file "E_lab1_Estimation/Pract_Estimation_professor.ipynb".
The first task is:
[3.7] [OPTIONAL] Show, in the same plot, the posterior distribution of parameter $s$ given only the data at hour $h$ and for all days up to $d$, for $d=1,\ldots, 5$
Can you write Python code for it?

# <SOL>
tx = list(zip(t, x_all))
h0 = 16

plt.figure()
for d in range(n_days):
    plt.plot(s, PP(s, z5[d], K5[d]), label='d = {}'.format(d))

plt.xlim((s[0], s[-1]))
plt.ylim((0, plt.ylim()[1]))
plt.legend()
plt.show()
# </SOL>


I am working on the file "Easy/PokerRuleInduction/PokerRuleInduction.ipynb".
The first task is:
I've decided to use K Nearest Neighbour and Random Forest according to the recommendation and the benchmark of the problem. Above, I've created instances from the Random Forest and K Nearest Neighbour modules, then get the score of each one to help me to decide which one is better.
Can you write Python code for it?

if __name__ == '__main__':
    trainingData = getTrainingData()
    labels = trainingData['hand']
    features = trainingData.drop(['id', 'hand'], axis=1)

    KNN, RF = kFoldCrossValidation(5)
    classifier = None

    if KNN > RF:
        classifier = KNeighborsClassifier(n_neighbors=100)
    else:
        classifier = RandomForestClassifier(n_estimators=10, n_jobs=-1)

    testData, result = getTestData()

    print("Classification in progress ...\n")

    classifier.fit(features, labels)
    result.insert(1, 'hand', classifier.predict(testData))
    result.to_csv("./results.csv", index=False)

    print("Classification Ends ...\n")


I am working on the file "Easy/PokerRuleInduction/PokerRuleInduction.ipynb".
The first task is:
Second, We need to extract the features and the label from the table
Can you write Python code for it?

trainingData = getTrainingData()
labels = trainingData['hand']
features = trainingData.drop(['id', 'hand'], axis=1)


I am working on the file "Easy/PokerRuleInduction/PokerRuleInduction.ipynb".
The first task is:
Using the awesome Panda library, we can parse the .csv file of the training set and hold the data in a table
Can you write Python code for it?

def getTrainingData():
    print("Get training data ...\n")

    trainingData = pnd.read_csv("./train.csv")
    trainingData['id'] = range(1, len(trainingData) + 1) #For 1-base index

    return trainingData


I am working on the file "Easy/PokerRuleInduction/PokerRuleInduction.ipynb".
The first task is:
When dealing with Machine Learning algorithms, you need to calculate the effiency of the algorithm with the data, this could be done using several techniques such as K-Fold cross validation https://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation and Precision and recall https://en.wikipedia.org/wiki/Precision_and_recall.
I've used K-fold cross validation for this problem.
Can you write Python code for it?

def kFoldCrossValidation(kFold):
    trainingData = getTrainingData()
    label = trainingData['hand']
    features = trainingData.drop(['id'], axis=1)
    crossValidationResult = dict()

    print("Start Cross Validation ...\n")

    randomForest = RandomForestClassifier(n_estimators=100)
    kNearestNeighbour = KNeighborsClassifier(n_neighbors=100)
    crossValidationResult['RF'] = cross_val_score(randomForest, trainingData, label, cv=kFold).mean()
    crossValidationResult['KNN'] = cross_val_score(kNearestNeighbour, trainingData, label, cv=kFold).mean()

    print("KNN: %s\n" % str(crossValidationResult['KNN']))
    print("RF: %s\n" % str(crossValidationResult['RF']))
    print("\n")

    return crossValidationResult['KNN'], crossValidationResult['RF']


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
1. Setup
First, let us setup the working area.
Can you write Python code for it?

#This would be the size of each grid cell (X is the spatial coordinate, T is two-way time)
xstep=5
tstep=5

#size of the whole grid
xmax = 320
tmax = 220

#that's the arrays of x and t
xarray = np.arange(0, xmax, xstep).astype(float)
tarray = np.arange(0, tmax, tstep).astype(float)

#now fimally we created a 2D array img, which is now all zeros, but later we will add some amplitudes there
img=np.zeros((len(xarray), len(tarray)))


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
2. Main class definition
What we are now going to do is create a class named Hyperbola
Each object of this class is capable of computing traveltimes to a certain subsurface point (diffractor) and plotting this point response (hyperbola) on a grid
How? to more clearly define a class? probably change to a function?
Can you write Python code for it?

class Hyperbola:
    def __init__(self, xarray, tarray, x0, t0, v=2):
        ###input parameters define a difractor's position (x0,t0), P-wave velocity of homogeneous subsurface, and x- and t-arrays to compute traveltimes on.
        ###

        self.x=xarray
        self.x0=x0
        self.t0=t0
        self.v=v

        #compute traveltimes
        self.t=sqrt(t0**2 + (2*(xarray-x0)/v)**2)

        #obtain some grid parameters
        xstep=xarray[1]-xarray[0]
        tbegin=tarray[0]
        tend=tarray[-1]
        tstep=tarray[1]-tarray[0]

        #delete t's and x's for samples where t exceeds maxt
        self.x=self.x[ (self.t>=tbegin) & (self.t <= tend) ]
        self.t=self.t[ (self.t>=tbegin) & (self.t <= tend) ]
        self.imgind=((self.x-xarray[0])/xstep).astype(int)

        #compute amplitudes' fading according to geometrical spreading

        self.amp = 1/(self.t/self.t0)

        self.grid_resample(xarray, tarray)

    def grid_resample(self, xarray, tarray):
    # that's a function that computes at which 'cells' of image should we place the hyperbola

        tend=tarray[-1]
        tstep=tarray[1]-tarray[0]

        self.xind=((self.x-xarray[0])/xstep).astype(int)  #X cells numbers

        self.tind=np.round((self.t-tarray[0])/tstep).astype(int) #T cells numbers
        self.tind=self.tind[self.tind*tstep<=tarray[-1]] #delete T's exceeding max.T

        self.tgrid=tarray[self.tind] # get 'gridded' T-values

        self.coord=np.vstack((self.xind,tarray[self.tind]))

    def add_to_img(self, img, wavelet):
    # puts the hyperbola into the right cells of image with a given wavelet
        maxind=np.size(img,1)
        wavlen=np.floor(len(wavelet)/2).astype(int)

        self.imgind=self.imgind[self.tind < maxind-wavlen-1]
        self.amp = self.amp[self.tind < maxind-wavlen-1]
        self.tind=self.tind[self.tind <...


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
3. Creating the model and 'forward modelling'
OK, now let's define a subsurface model. For the sake of simplicity, the model will consist of two types of objects:
1. Point diffractor in a homogeneous medium
  * defined by their coordinates $(x_0, t_0)$ in data domain.
2. Plane reflecting surface
  * defined by their end points $(x_1, t_1)$ and $(x_2, t_2)$, also in data domain.
We will be able to add any number of these objects to image.
Let's start by adding three point diffractors:
Can you write Python code for it?

point_diff_x0 = [100, 150, 210]
point_diff_t0 = [100, 50, 70]

plt.scatter(point_diff_x0,point_diff_t0, c='r',s=70)
plt.xlim(0, xmax)
plt.ylim(tmax, 0)
plt.gca().set_xlabel('X, m')
plt.gca().set_ylabel('T, ms')
plt.gca().xaxis.set_ticks_position('top')
plt.gca().xaxis.set_label_position('top')
plt.gca().grid(True, alpha = 0.1, ls='-',lw=.5)


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
5. Migration application
Can you write Python code for it?

vmig = 2
aper = 200
res = migrate(img, vmig, aper, xarray, tarray)

plt.imshow(res.T,interpolation='none',vmin=-2,vmax=2,cmap=cm.Greys, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
#plt.imshow(res.T,cmap=cm.Greys,vmin=-2,vmax=2, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])

#f_migv = plt.figure()

def migshow(vmig_i, aper_i, gain_i, interp):
    res_i = migrate(img, vmig_i, aper_i, xarray, tarray)
    if interp:
        interp_style = 'bilinear'
    else:
        interp_style = 'none'

    plt.imshow(res_i.T,interpolation=interp_style,vmin=-gain_i,vmax=gain_i,cmap=cm.Greys, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
    plt.title('Vmig = '+str(vmig_i))
    plt.show()

interact(migshow, vmig_i = widgets.FloatSlider(min = 1.0,max = 3.0, step = 0.01, value=2.0,continuous_update=False,description='Migration velocity: '),
         aper_i = widgets.IntSlider(min = 10,max = 500, step = 1, value=200,continuous_update=False,description='Migration aperture: '),
         gain_i = widgets.FloatSlider(min = 0.0,max = 5.0, step = 0.1, value=2.0,continuous_update=False,description='Gain: '),
         interp = widgets.Checkbox(value=True, description='interpolate'))

#interact(migrate, img=fixed(img), v = widgets.IntSlider(min = 1.0,max = 3.0, step = 0.1, value=2), aper=fixed(aper), xarray=fixed(xarray), tarray=fixed(tarray))


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
Create a line and add it to image
Can you write Python code for it?

line1=Line(100,250,50,150,xarray,tarray)
img=line1.add_to_img(img, [-1,2,-1])
line2=Line(40,270,175,100,xarray,tarray)
img=line2.add_to_img(img, [-1,2,-1])

plt.imshow(img.T,interpolation='none',cmap=cm.Greys, vmin=-2,vmax=2, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
plt.gca().xaxis.set_ticks_position('top')
plt.gca().grid(ls=':', alpha=0.25, lw=1, c='w' )


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
Excellent. The image now is pretty messy, so we need to migrate it and see what we can achieve
4. Migration definition
Can you write Python code for it?

def migrate(img,v,aper,xarray,tarray):
    imgmig=np.zeros_like(img)
    xstep=xarray[1]-xarray[0]
#    print 'начинаем миграцию'
#    print 'апертура {0}, скорость {1},'.format(aper, v)
#    print '\n xarray: от {0} до {1} с шагом {2},'.format(xarray[0], xarray[-1], xstep)
#    print '\n tarray: от {0} до {1} с шагом {2},'.format(tarray[0], tarray[-1], tarray[1]-tarray[0])

#    for x0 in xarray[(xarray>xarray[0]+aper) & (xarray<xarray[-1]-aper)]:
    for x0 in xarray:
        for t0 in tarray[1:-1]:
#            print "t0 = {0}, x0 = {1}".format(t0,x0)

            xmig=xarray[(x0-aper<=xarray) & (xarray<=x0+aper)]

#            print 'xmig = от', xmig[0],' до ', xmig[-1], ' отсчётов ', len(xmig)
            hi=Hyperbola(xmig,tarray,x0,t0,v)

#            print 'hi.x: от ', hi.x[0], ' до ', hi.x[-1]

            migind_start = hi.x[0]/xstep
            migind_stop = (hi.x[-1]+xstep)/xstep

            hi.imgind=np.arange(migind_start, migind_stop).astype(int)
#            si=np.sum(img[hi.imgind,hi.tind])
            si=np.mean(img[hi.imgind,hi.tind]*hi.amp)
#            si=np.mean(img[hi.imgind,hi.tind])
            imgmig[(x0/xstep).astype(int),(t0/tstep).astype(int)]=si

#            if ( (t0==3 and x0==10) or (t0==7 and x0==17) or (t0==11 and x0==12)  ):
#            if ( (t0==8 and x0==20)):
#                ax_data.plot(hi.x,hi.t,c='m',lw=3,alpha=0.8)
#                ax_data.plot(hi.x0,hi.t0,marker='H', mfc='r', mec='m',ms=5)
#                for xi in xmig:
#                    ax_data.plot([xi,hi.x0],[0,hi.t0],c='#AFFF94',lw=1.5,alpha=1)
#
    return imgmig


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
Let's show our all-zero image
Can you write Python code for it?

plt.imshow(img.T,interpolation='none',cmap=cm.Greys, vmin=-2,vmax=2, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
Next step is computing traveltimes for these subsurface diffractors. This is done by creating an instance of Hyperbola class for every diffractor.
Can you write Python code for it?

hyps=[]
for x0,t0 in zip(point_diff_x0,point_diff_t0):
    hyp_i = Hyperbola(xarray, tarray, x0, t0, v=2)
    hyps.append(hyp_i)


I am working on the file "EasyMig_v3-interact2.ipynb".
The first task is:
~~Next step is computing Green's functions for these subsurface diffractors. To do this, we need to setup a wavelet.~~
Of course, we are going to create an extremely simple wavelet.
Can you write Python code for it?

wav1 = np.array([-1,2,-1])

with plt.xkcd():
    plt.axhline(0,c='k')
    plt.stem((np.arange(len(wav1))-np.floor(len(wav1)/2)).astype(int) ,wav1)
    plt.gca().set_xlim(-2*len(wav1), 2*len(wav1))
    plt.gca().set_ylim(np.min(wav1)-1, np.max(wav1)+1)

for hyp_i in hyps:
    hyp_i.add_to_img(img,wav1)

plt.imshow(img.T,interpolation='none',cmap=cm.Greys, vmin=-2,vmax=2, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
plt.gca().xaxis.set_ticks_position('top')
plt.gca().grid(ls=':', alpha=0.25, lw=1, c='w' )


I am working on the file "EasyMig_v3.ipynb".
The first task is:
First, let us setup the working area.
Can you write Python code for it?

#This would be the size of each grid cell (X is the spatial coordinate, T is two-way time)
xstep=10
tstep=10

#size of the whole grid
xmax = 301
tmax = 201

#that's the arrays of x and t
xarray=np.arange(0, xmax, xstep)
tarray=np.arange(0, tmax, tstep)

#now fimally we created a 2D array img, which is now all zeros, but later we will add some amplitudes there
img=np.zeros((len(xarray), len(tarray)))


I am working on the file "EasyMig_v3.ipynb".
The first task is:
For testing purposes, let's create an object named Hyp_test and view its parameters
Can you write Python code for it?

Hyp_test = Hyperbola(xarray, tarray, x0 = 100, t0 = 30, v = 2)

#Create a fugure and add axes to it
fgr_test1 = plt.figure(figsize=(7,5), facecolor='w')
ax_test1 = fgr_test1.add_subplot(111)

#Now plot Hyp_test's parameters: X vs T
ax_test1.plot(Hyp_test.x, Hyp_test.t, 'r', lw = 2)
#and their 'gridded' equivalents
ax_test1.plot(Hyp_test.x, Hyp_test.tgrid, ls='none', marker='o', ms=6, mfc=[0,0.5,1],mec='none')

#Some commands to add gridlines, change the directon of T axis and move x axis to top
ax_test1.set_ylim(tarray[-1],tarray[0])
ax_test1.xaxis.set_ticks_position('top')
ax_test1.grid(True, alpha = 0.1, ls='-',lw=.5)

ax_test1.set_xlabel('X, m')
ax_test1.set_ylabel('T, ms')
ax_test1.xaxis.set_label_position('top')

plt.show()


I am working on the file "EasyMig_v3.ipynb".
The first task is:
Let's show our all-zero image
Can you write Python code for it?


I am working on the file "EasyMig_v3.ipynb".
The first task is:
What we are now going to do is create a class named Hyperbola
Each object of this class is capable of computing traveltimes to a certain subsurface point (diffractor) and plotting this point response on a grid
Can you write Python code for it?

class Hyperbola:
    def __init__(self, xarray, tarray, x0, v, t0):
        ###input parameters define a difractor's position (x0,t0), P-wave velocity of homogeneous subsurface, and x- and t-arrays to compute traveltimes on.
        ###

        self.x=xarray
        self.x0=x0
        self.t0=t0
        self.v=v

        #compute traveltimes
        self.t=sqrt(t0**2 + (2*(xarray-x0)/v)**2)

        #obtain some grid parameters
        xstep=xarray[1]-xarray[0]
        tbegin=tarray[0]
        tend=tarray[-1]
        tstep=tarray[1]-tarray[0]

        #delete t's and x's for samples where t exceeds maxt
        self.x=self.x[ (self.t>=tbegin) & (self.t <= tend) ]
        self.t=self.t[ (self.t>=tbegin) & (self.t <= tend) ]
        self.imgind=((self.x-xarray[0])/xstep).astype(int)

        #compute amplitudes' fading according to geometrical spreading
        self.amp = 1/(self.t/self.t0)

        self.grid_resample(xarray, tarray)

    def grid_resample(self, xarray, tarray):
    # that's a function that computes at which 'cells' of image should we place the hyperbola

        tend=tarray[-1]
        tstep=tarray[1]-tarray[0]

        self.xind=((self.x-xarray[0])/xstep).astype(int)  #X cells numbers

        self.tind=np.round((self.t-tarray[0])/tstep).astype(int) #T cells numbers
        self.tind=self.tind[self.tind*tstep<=tarray[-1]] #delete T's exceeding max.T

        self.tgrid=tarray[self.tind] # get 'gridded' T-values

        self.coord=np.vstack((self.xind,tarray[self.tind]))

    def add_to_img(self, img, wavelet):
    # puts the hyperbola into the right cells of image with a given wavelet
        maxind=np.size(img,1)
        wavlen=np.floor(len(wavelet)/2).astype(int)

        self.imgind=self.imgind[self.tind < maxind-1]
        self.tind=self.tind[self.tind < maxind-1]
        ind_begin=self.tind-wavlen
       ...


I am working on the file "EasyMig_v4-interact3.ipynb".
The first task is:
3. Creating the model and 'forward modelling'
OK, now let's define a subsurface model. For the sake of simplicity, the model will consist of two types of objects:
1. Point diffractor in a homogeneous medium
  * defined by their coordinates $(x_0, t_0)$ in data domain.
2. Plane reflecting surface
  * defined by their end points $(x_1, t_1)$ and $(x_2, t_2)$, also in data domain.
We will be able to add any number of these objects to image.
Let's start by adding three point diffractors:
Can you write Python code for it?


I am working on the file "EasyMig_v4-interact3.ipynb".
The first task is:
Create a line and add it to image
Can you write Python code for it?

line1=Line(100,250,50,150,xarray,tarray)
img=line1.add_to_img(img, wav1)
line2=Line(40,270,175,100,xarray,tarray)
img=line2.add_to_img(img, wav1

plt.imshow(img.T, interpolation='none', cmap=cm.Greys, vmin=-2, vmax=2,
           extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
plt.gca().xaxis.set_ticks_position('top')
plt.gca().grid(ls=':', alpha=0.25, lw=1, c='w' )


I am working on the file "EasyMig_v4-interact3.ipynb".
The first task is:
Excellent. The image now is pretty messy, so we need to migrate it and see what we can achieve
4. Migration definition
Can you write Python code for it?

def migrate(img, v, aper, xarray, tarray):
    imgmig=np.zeros_like(img)
    xstep=xarray[1]-xarray[0]

    for x0 in xarray:
        for t0 in tarray[1:-1]:
            #only a region between (x0-aper) and (x0+aper) should be taken into account
            xmig=xarray[(x0-aper <= xarray) & (xarray <= x0+aper)]

            hi = Hyperbola(xmig,tarray,x0,t0,v)

            migind_start = hi.x[0]/xstep
            migind_stop = (hi.x[-1]+xstep)/xstep

            hi.imgind=np.arange(migind_start, migind_stop).astype(int)
            #Sum (in fact, count the mean value of) all the amplitudes on current hyperbola hi
            si = np.mean(img[hi.imgind,hi.tind]*hi.amp)
            imgmig[(x0/xstep).astype(int),(t0/tstep).astype(int)] = si

    return imgmig


I am working on the file "EasyMig_v4-interact3.ipynb".
The first task is:
Next step is computing traveltimes for these subsurface diffractors. This is done by creating an instance of Hyperbola class for every diffractor.
Can you write Python code for it?


I am working on the file "EasyMig_v4-interact3.ipynb".
The first task is:
~~Next step is computing Green's functions for these subsurface diffractors. To do this, we need to setup a wavelet.~~
Of course, we are going to create an extremely simple wavelet.
Can you write Python code for it?

wav1 = np.array([-1,2,-1])

plt.axhline(0,c='k')
markerline, stemlines, baseline = plt.stem((np.arange(len(wav1)) - np.floor(len(wav1)/2)).astype(int), wav1)
plt.gca().set_xlim(-2*len(wav1), 2*len(wav1))
plt.gca().set_ylim(np.min(wav1)-1, np.max(wav1)+1)

for hyp_i in hyps:
    hyp_i.add_to_img(img,wav1)

plt.imshow(img.T,interpolation='none',cmap=cm.Greys, vmin=-2,vmax=2, extent=[xarray[0]-xstep/2, xarray[-1]+xstep/2, tarray[-1]+tstep/2, tarray[0]-tstep/2])
plt.gca().xaxis.set_ticks_position('top')
plt.gca().grid(ls=':', alpha=0.25, lw=1, c='w' )


I am working on the file "Easygen.ipynb".
The first task is:
2. Download pre-trained neural network models
2.1 Download GPT-2 and StyleGan models
Download the GPT-2 small 117M model. Will save to models/117M directory.
Can you write Python code for it?


I am working on the file "Easygen.ipynb".
The first task is:
3. Run the GUI
Run the cell below. This will load a default example program that generate new, fictional paint names. Use the "clear" button to clear it and make your own.
When done, name the program and press the "save" button. You should see your file appear in the file listing in the left panel.
Can you write Python code for it?

%%html
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

text

  text
  <input id="inp_val" />
  <button onmouseup="do_input_button_up()">ok</button>

Make New Module

  <select id="module_select"></select>
  <button onmouseup="do_make_module_button_up()">Add Module</button>

Save Program

  <input id="inp_save" />
  <button onmouseup="save_program()">Save</button>

Load Program

  <input id="inp_load" />
  <button onmouseup="load_program()">Load</button>

Clear Program

  <button onmouseup="clear_program()">Clear</button>


I am working on the file "Easygen.ipynb".
The first task is:
4. Run Your Program
This will run a default example program that will generate new, fictional paint names. If you don't want to run that program, skip to the next cell.
Can you write Python code for it?

program_file_name = 'easygen/examples/make_new_colors'
easygen.main(program_file_name)


I am working on the file "Easygen.ipynb".
The first task is:
5. View Your Output Files
Run the cell below to launch a file manager so you can view your text and image files.
You can use the panel to the left to download any files written to disk.
Can you write Python code for it?

%%html

Manage Files

/content		/content

<select multiple id="file_list1"></select>
<button id="copy_button" onmouseup="do_copy_mouse_up()">Copy --></button>

<button id="move_button" onmouseup="do_move_mouse_up()">Move --></button>
	<select multiple id="file_list2"></select>

<button id="open_text_button" onmouseup="do_open_text_mouse_up()">Open Text</button>
<button id="open_image_button" onmouseup="do_open_image_mouse_up()">Open Image</button>
<button id="open_text_button" onmouseup="do_trash_mouse_up()">Send to trash</button>

Make Directories

<input id="mkdir_input" /><button onmouseup="do_mkdir_mouse_up()">Make directory</button>


I am working on the file "Easygen.ipynb".
The first task is:
Create backend hooks for saving and loading programs
Can you write Python code for it?

import IPython
from google.colab import output

def python_save_hook(file_text, filename):
  import easygen
  import hooks
  status = hooks.python_save_hook_aux(file_text, filename)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_load_hook(filename):
  import easygen
  import hooks
  result = hooks.python_load_hook_aux(filename)
  return IPython.display.JSON({'result': result})

def python_cwd_hook(dir):
  import easygen
  import hooks
  result = hooks.python_cwd_hook_aux(dir)
  return IPython.display.JSON({'result': result})

def python_copy_hook(path1, path2):
  import easygen
  import hooks
  status = hooks.python_copy_hook_aux(path1, path2)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_move_hook(path1, path2):
  import easygen
  import hooks
  status = hooks.python_move_hook_aux(path1, path2)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_open_text_hook(path):
  import easygen
  import hooks
  status = hooks.python_open_text_hook_aux(path)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_open_image_hook(path):
  import easygen
  import hooks
  status = hooks.python_open_image_hook_aux(path)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_mkdir_hook(path, dir_name):
  import easygen
  import hooks
  status = hooks.python_mkdir_hook_aux(path, dir_name)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_trash_hook(path):
  import easygen
  import hooks
  status = hooks.python_trash_hook_aux(path)
  ret_status = 'true' if status else 'false'
  return IPython.display.JSON({'result': ret_status})

def python_run_hook(path):
  import easygen
  program_file_name = path
  easygen.main(program_file_name)
  return...


I am working on the file "Easygen.ipynb".
The first task is:
Download GPT-2
Can you write Python code for it?


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

!git clone https://github.com/NVlabs/stylegan.git
!cp easygen/stylegan_runner.py stylegan


I am working on the file "Easygen.ipynb".
The first task is:
Download the GPT-2 medium 345M model. Will save to models/345M directory.
Can you write Python code for it?


I am working on the file "Easygen.ipynb".
The first task is:
Download the StyleGAN cats model (256x256). Will save as "cats256x256.pkl" in the home directory.
Can you write Python code for it?

!wget -O cats256x256.pkl https://www.dropbox.com/s/1w97383h0nrj4ea/karras2019stylegan-cats-256x256.pkl?dl=0


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

import sys
sys.path.insert(0, 'easygen')
import easygen


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

!apt-get update
!apt-get install chromium-chromedriver
!pip install -r easygen/requirements.txt


I am working on the file "EbisuHowto.ipynb".
The first task is:
After learning the second fact, at 0900, what does Ebisu expect each fact’s probability of recall to be, for each of the facts?
Can you write Python code for it?

oneHour = timedelta(hours=1)

now = date0 + timedelta(hours=11.1)
print("On {},".format(now))
for row in database:
    recall = ebisu.predictRecall(row['model'],
                                 (now - row['lastTest']) / oneHour,
                                 exact=True)
    print("Fact #{} probability of recall: {:0.1f}%".format(row['factID'], recall * 100))


I am working on the file "EbisuHowto.ipynb".
The first task is:
Ebisu—this is what we’re here to learn about!
Ebisu is a library that’s expected to be embedded inside quiz apps, to help schedule quizzes intelligently. It uses Bayesian statistics to let the app predict what the recall probability is for any fact that the student has learned, and to update that prediction based onthe results of a quiz.
Ebisu uses three numbers to describe its belief about the time-evolution of each fact’s recall probability. Its API consumes them as a 3-tuple, and they are:

the first we call “alpha” and must be ≥ 2 (well, technically, ≥1 is the raw minimum but unless you’re a professor of statistics, keep it more than two);
the second is “beta” and also must be ≥ 2. These two numbers encode our belief about the distribution of recall probabilities at
the third element, which here is a half-life. This has units of time, and for this example, we’ll assume it’s in hours. It can be any positive float, but we choose the nice round number of 24 hours.

For the nerds: alpha and beta parameterize a Beta distribution to describe our prior belief of the recall probability one half-life (one day) after a fact’s most recent quiz.
For the rest of us: these three numbers mean we expect the recall probability for a newly-learned fact to be 50% after one day, but allow uncertainty: the recall probability after a day is “around” 42% to 58% (±1 standard deviation).

Now. Let’s create a mock database of facts. Say a student has learned two facts, one on the 19th at 2200 hours and another the next morning at 0900 hours.
Can you write Python code for it?

from datetime import datetime, timedelta
date0 = datetime(2017, 4, 19, 22, 0, 0)

database = [dict(factID=1, model=defaultModel, lastTest=date0),
            dict(factID=2, model=defaultModel, lastTest=date0 + timedelta(hours=11))]


I am working on the file "EbisuHowto.ipynb".
The first task is:
If the user was worried that this flashcard was shown too infrequently, and wanted to see it three times as often, you might pass in 1/3 as the second argument.
This short notebook shows the major functions in the Ebisu API:
- ebisu.predictRecall to find out the expected recall probability for a fact right now, and
- ebisu.updateRecall to update those expectations when a new quiz result is available.
- ebisu.modelToPercentileDecay to find the time when the recall probability reaches a certain value.
- ebisu.rescaleHalflife to adjust the halflife up and down without a quiz.
For more advanced functionality, including non-binary fuzzy quizzes, do consult the Ebisu website, which links to the API’s docstrings and explains how this all works in greater detail.
Adanced topics
Speeding up predictRecall
Above, we used predictRecall with the exact=True keyword argument to have it return true probabilities. We can reduce runtime if we use the following:
Can you write Python code for it?

# As above: a bit slow to get exact probabilities
%timeit ebisu.predictRecall(database[0]['model'], 100., exact=True)

# A bit faster alternative: get log-probabilities (this is the defalt)
%timeit ebisu.predictRecall(database[0]['model'], 100., exact=False)


I am working on the file "EbisuHowto.ipynb".
The first task is:
Note how the half-life (the time between quizzes for expected recall probability to drop to 50%) for the first question increased from 24 to 29 hours after the student got it right, while it decreased to 20 hours for the second when she got it wrong. Ebisu has incorporated the fact that the second fact had been learned not that long ago and should have been strong, and uses the surprising quiz result to strongly adjust its belief about its recall probability.

Suppose the user is tired of reviewing the first fact so often because it’s something they know very well. You could allow the user to delete this flashcard, add it again with a longer initial halflife. But Ebisu gives you a function that will explicitly rescale the halflife of the card as is: ebisu.rescaleHalflife, which takes a positive number to act as the halflife scale. In this case, the new halflife is two times the old halflife.
Can you write Python code for it?

database[0]['model'] = ebisu.rescaleHalflife(database[0]['model'], 2.0)

for row in database:
    meanHalflife = ebisu.modelToPercentileDecay(row['model'])
    print("Fact #{} has half-life of ≈{:0.1f} hours".format(row['factID'], meanHalflife))


I am working on the file "EbisuHowto.ipynb".
The first task is:
Observe how ebisu.updateRecall takes
- the current model,
- the quiz result, and
- the time elapsed since the last quiz,
and returns a new model (the new 3-tuple of “alpha”, “beta” and time). We put the new model and the current timestamp into the database.
Now. Suppose the student asks to review another fact—fact 2. It was learned just earlier that morning, and its recall probability is expected to be around 63%, but suppose the student fails this quiz, as sometimes happens.
Can you write Python code for it?

row = database[1] # review SECOND question

result = 0
newModel = ebisu.updateRecall(row['model'],
                              result,
                              total,
                              (now - row['lastTest']) / oneHour)
print('New model for fact #2:', newModel)
row['model'] = newModel
row['lastTest'] = now


I am working on the file "Edit distance.ipynb".
The first task is:
Alternate formulation
Instead of keeeping an explicit table for cost and parent, we could instead employ a dictionary.
Can you write Python code for it?

def _calc_distance(s1, s2, i, j, match_cost, insert_cost, delete_cost, cache={}):
    if (i, j) in cache:
        return cache[(i, j)]
    result = edit_distance(s1, s2, i, j, match_cost, insert_cost, delete_cost, cache)

    cache[(i, j)] = result
    return result

def edit_distance(s1, s2, i, j, match_cost, insert_cost, delete_cost, cache={}):
    # s1 ran out, delete the rest of the string
    if i == 0: return j*delete_cost(" ")

    # s2 ran out, insert until we match s1
    if j == 0: return i*insert_cost(" ")

    match_op = _calc_distance(s1, s2, i-1, j-1, match_cost, insert_cost, delete_cost, cache) \
        + match_cost(s1[i-1], s2[j-1])

    insert_op = _calc_distance(s1, s2, i, j-1, match_cost, insert_cost, delete_cost, cache) \
        + insert_cost(s2[j-1])

    delete_op = _calc_distance(s1, s2, i-1, j, match_cost, insert_cost, delete_cost, cache) \
        + delete_cost(s1[i-1])

    ops = [match_op, insert_op, delete_op]

    return min(ops)

s1 = "you should not"
s2 = "thou shalt not"
print(edit_distance(s1, s2, len(s1), len(s2),
                   lambda c1, c2: 0 if c1 == c2 else 1,
                   lambda c: 1,
                   lambda c: 1))


I am working on the file "Edit distance.ipynb".
The first task is:
Naive approach
The naive approach to calculate the edit distance is to first define three possible operations allowed: ${ \text{substitution}, \text{insert}, \text{delete}}$. We maintain the index to $s_1$ with $i$ and the index to $s_2$ with $j$.

Both $i$ and $j$ are set to the end of their respective strings
for each op a cost is estimated (recursively)
insertion ops decrement $j$ (which is equivalent to incrementing $i$)
deletion ops decrement $i$
match/substitution decrement both $i$ and $j$
Can you write Python code for it?

def edit_distance(s1, s2, i, j, match_cost, insert_cost, delete_cost):
    if i == 0: return j*delete_cost(" ")
    if j == 0: return i*insert_cost(" ")

    match_op = edit_distance(s1, s2, i-1, j-1, match_cost, insert_cost, delete_cost) \
        + match_cost(s1[i], s2[j])

    insert_op = edit_distance(s1, s2, i, j-1, match_cost, insert_cost, delete_cost) \
        + insert_cost(s2[j])

    delete_op = edit_distance(s1, s2, i-1, j, match_cost, insert_cost, delete_cost) \
        + delete_cost(s1[i])

    ops = [match_op, insert_op, delete_op]

    return min(ops)

s1 = "abc"
s2 = "xaxbxc"
print(edit_distance(s1, s2, len(s1)-1, len(s2)-1,
                   lambda c1, c2: 0 if c1 == c2 else 1,
                   lambda c: 1,
                   lambda c: 1))


I am working on the file "Edit distance.ipynb".
The first task is:
Our new function calc_distance doesn't return the final desired value. Instead we can use reconstruct_path on the parent matrix given a starting location.
Can you write Python code for it?

def reconstruct_path(parent, s1, s2, i, j, on_match=None, on_insert=None, on_delete=None):
    if parent[i, j] == -1: return

    if parent[i, j] == 0:
        reconstruct_path(parent, s1, s2, i-1, j-1, on_match, on_insert, on_delete)
        if on_match: on_match(s1[i-1], s2[j-1])
    elif parent[i, j] == 1:
        reconstruct_path(parent, s1, s2, i, j-1, on_match, on_insert, on_delete)
        if on_insert: on_insert(s1[i-1], s2[j-1])
    elif parent[i, j] == 2:
        reconstruct_path(parent, s1, s2, i-1, j, on_match, on_insert, on_delete)
        if on_delete: on_delete(s1[i-1], s2[j-1])

def edit_distance(s1, s2):
    cost = np.zeros((len(s1)+1, len(s2)+1), dtype=np.uint8)
    parent = np.zeros((len(s1)+1, len(s2)+1), dtype=np.int8)

    cost[0, 0] = 0
    parent[0, 0] = -1

    # deletion (s1[i] == s2[i-k])
    cost[1:, 0] = range(1, len(s1)+1)
    parent[1:, 0] = 2

    # insertion (s1[i+k] == s2[i])
    cost[0, 1:] = range(1, len(s2)+1)
    parent[0, 1:] = 1

    cost, parent = calc_distance(cost, parent, s1, s2,
                                 lambda c1, c2: 0 if c1 == c2 else 1,
                                 lambda c: 1,
                                 lambda c: 1)

    result = []
    reconstruct_path(parent, s1, s2, len(s1), len(s2),
                     lambda c1, c2: result.append("M") if c1 == c2 else result.append("S"),
                     lambda c1, c2: result.append("I"),
                     lambda c1, v2: result.append("D"))
    return cost[len(s1), len(s2)], result

s1 = "thou shalt not"
s2 = "you should not"
cost, result = edit_distance(s1, s2)
result = "".join(result)

print(cost)
correct = "DSMMMMMISMSMMMM"
print(result == correct)

def match_substring(s1, s2):
    cost = np.zeros((len(s1)+1, len(s2)+1), dtype=np.uint8)
    parent = np.zeros((len(s1)+1, len(s2)+1), dtype=np.int8)

    cost[0, 0] = 0
    parent[0, 0] = -1

    cost[1:, 0] = range(1, len(s1)+1)
    parent[1:, 0] = 2

    cost[0, 1:] = range(1, len(s2)+1)
   ...


I am working on the file "Edit distance.ipynb".
The first task is:
The function can only be used on very small strings due to the fact that it branches for each operation. The best case scenario (where $i$ and $j$ are both decremented) it has a $O(3^n)$. However, we can observe that many of the calculations are duplicated. Each branching of the tree does not share information with the other branches, and necessarily overlap the portions of the string they process. Because the function detereministic and is parameterized by $i$ and $j$, there can only be $|s_1|*|s_2|$ possible calls made, and thus should have a $O(mn)$.
We can use dynamic programming to solve this for us. The function still behaves in a similar fashion, except we now keep two matrices. The cost matrix keeps a running tally of the total cost to reach $(i, j)$. The parent matrix keeps track of which operation was selectd to reach $(i, j)$. For both matrices, its assumed that the minimum cost was always selected.
One thing to note is that the matrices are indexed with +1 from the previous code. This is because the $0$th indices of the matrices refer to $1$ before the first character of the string.
Can you write Python code for it?

def calc_distance(cost, parent, s1, s2, match_cost, insert_cost, delete_cost):
    for i, c1 in enumerate(s1):
        for j, c2 in enumerate(s2):
            match_op = cost[i, j] + match_cost(c1, c2)
            insert_op = cost[i+1, j] + insert_cost(c1)
            delete_op = cost[i, j+1] + delete_cost(c2)

            # determine which operation is cheapest
            ops = [match_op, insert_op, delete_op]
            idx = np.argmin(ops)

            # cost for (i, j) is determined by whichever op is cheapest
            # to perform.
            cost[i+1, j+1] = ops[idx]
            parent[i+1, j+1] = idx

    return (cost, parent)


I am working on the file "EduMLvsRuleBased.ipynb".
The first task is:
Determine if the student undermatched-or-was-properly matched
Can you write Python code for it?

avg_gpas = stud_df.groupby('college').gpa.mean()
def isUndermatched(student):
    if student.gpa >= (avg_gpas[student.college] + .50):
        return True
    else:
        return False

stud_df['undermatch_status'] = stud_df.apply(isUndermatched, axis =1 )
#stud_df.groupby('race').undermatch_status.value_counts()


I am working on the file "EduMLvsRuleBased.ipynb".
The first task is:
Machine Learning Model

Simple Logisitic Regression
Can you write Python code for it?

from sklearn import linear_model
feature_cols = ['psat', 'gpa', 'honors']
X = train[feature_cols]
y = train['undermatch_status']

# instantiate, fit
lm = linear_model.LogisticRegression()
lm.fit(X, y)

# The coefficients
print('Coefficients: \n', lm.coef_)
# The mean square error
print("Residual sum of squares: %.2f"
      % np.mean((lm.predict(test[feature_cols]) - test['undermatch_status']) ** 2))
# Explained variance score: 1 is perfect prediction
lm.predict(train[feature_cols])

sns.lmplot(x='psat', y='undermatch_status', data=test, logistic=True)


I am working on the file "Education.ipynb".
The first task is:
Dar es salaam leads with 121 schools and Katavi is the last with 7
Can you write Python code for it?


I am working on the file "Education.ipynb".
The first task is:
Lets group 100% pass rate by region
Can you write Python code for it?

grouped = df[df.PASS_RATE == 100 ].groupby(df['REGION'])
passed_per_region = grouped.count()
passed_per_region.NAME


I am working on the file "Education.ipynb".
The first task is:
Lets play with the numbers now
Lets look and see summary of the Pass Rate, Avarage Mark and  Change compared to previous year
Can you write Python code for it?


I am working on the file "Education.ipynb".
The first task is:
Lets plot a pie chat to visualize the data
Can you write Python code for it?

government_schools =sum(df.OWNERSHIP=='GOVERNMENT') #Government schools
nongovernment_schools =sum(df.OWNERSHIP=='NON GOVERNMENT') #nongovernment schools
unknown = sum(df.OWNERSHIP.isnull()) #number of shools with unknown ownership
schl=df.shape[0] #number of schools

Labels =['Govenment', 'Non Government','Unknown']
fractions =[float(government_schools)/schl, float(nongovernment_schools)/schl, float(unknown)/schl] #percentage
colors = ['yellowgreen', 'gold', 'lightskyblue'] #colors for pie chart
explode = (0, 0, 0) #only explode the first slice

plt.pie(fractions, explode=explode, labels=Labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()


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

df = pd.read_csv('PrimarySchoolsPerfomanceAndLocation-2014.csv')
df.shape

df.columns

col =['NAME','REGION','DISTRICT','OWNERSHIP','PASS_RATE','AVG_MARK','CHANGE_PREVIOUS_YEAR','RANK']
for c in df.columns:
    if c not in col:
        df=df.drop(c,axis=1)

df.shape

df.OWNERSHIP.unique()

df.head(10)


I am working on the file "Education.ipynb".
The first task is:
MBEYA is leading by having 1046
We can visulize our data more by using seaborn
Can you write Python code for it?

sns.set_context("notebook")
#lets get mean Pass Rate
mean_pass = df.PASS_RATE.mean()
print mean_pass, df.PASS_RATE.median()

with sns.axes_style("whitegrid"):
    df.PASS_RATE.hist(bins=30, alpha=0.4);
    plt.axvline(mean_pass, 0, 0.75, color='r', label='Mean')
    plt.xlabel("Pass Rate")
    plt.ylabel("Counts")
    plt.title("Passing Rate Hisyogram")
    plt.legend()
    sns.despine()

with sns.axes_style("whitegrid"):
    df.CHANGE_PREVIOUS_YEAR.hist(bins=15, alpha=0.6, color='r');
    plt.xlabel("change of passing rate comapred to 2013")
    plt.ylabel("school number")
    plt.title("Change of passing rate Hisyogram")

with sns.axes_style("whitegrid"):
    df.AVG_MARK.hist(bins=40,alpha=0.6, color='g')
    plt.xlabel("Avarage mark per school")
    plt.ylabel("school number")
    plt.title("Avarage Marks Hisyogram")
    plt.legend()


I am working on the file "Education.ipynb".
The first task is:
Sample of school which ownership is empty
Can you write Python code for it?


I am working on the file "Education.ipynb".
The first task is:
There about 15866 schools
Ownership of the School
can be seen below schools are grouped either Government or Non Government schools and there are about 2833 schools which have no type
Can you write Python code for it?


I am working on the file "Education.ipynb".
The first task is:
We need to know number of primary school which did standard seven exam year 2014
Can you write Python code for it?


I am working on the file "Education.ipynb".
The first task is:
how many do not have type or they are empty?
Can you write Python code for it?


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
An efficient generator using the inverse transform method

We start by computing the binomial coefficients and then the probability $\mathbb{P}(X=k)$ for $k\in{0,\dots,n}$, if $X\sim Bin(n, p)$, and,
Then use this to write a generator of Binomial-distributed random values.
This function is then simplified to inline all computations.
We propose a fast and simple Cython implementation, to be as efficient as possible, and hopefully comparably efficient when compared against the implementation in Numpy.

Explicit computation of the probabilities
Can you write Python code for it?

def binomial_coefficient(n: int, k: int) -> int:
    """From https://en.wikipedia.org/wiki/Binomial_coefficient#Binomial_coefficient_in_programming_languages"""
    if k < 0 or k > n:
        return 0
    if k == 0 or k == n:
        return 1
    k = min(k, n - k) # take advantage of symmetry
    c = 1
    for i in range(k):
        c = (c * (n - i)) / (i + 1)
    return c

def proba_binomial(n: int, p: float, k: int) -> float:
    """Compute {n \choose k} p^k (1-p)^(n-k)"""
    q = 1.0 - p
    return binomial_coefficient(n, k) * p**k * q**(n-k)


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
First function using the inversion method
This first function is a generic implementation of the discrete inverse transform method.
For more details, see the Wikipedia page.

Inverse transformation sampling takes uniform samples of a number $u$ between $0$ and $1$, interpreted as a probability, and then returns the largest number $x$ from the domain of the distribution $\mathbb{P}(X)$ such that $\mathbb{P}(-\infty <X<x)\leq u$.
Can you write Python code for it?

# a generic function
from typing import Callable

def inversion_method(compute_proba: Callable[[int], int], xmax: int, xmin: int =0) -> int:
    probas = [ compute_proba(x) for x in range(xmin, xmax + 1) ]
    result = xmin
    current_proba = 0
    one_uniform_sample = uniform_01()
    while current_proba <= one_uniform_sample:
        current_proba += probas[result]
        result += 1
    return result - 1

def first_inversion_binomial(n: int, p: float) -> int:
    def compute_proba(x):
        return proba_binomial(n, p, x)
    xmax = n
    xmin = 0
    return inversion_method(compute_proba, xmax, xmin=xmin)


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

%load_ext cython

%%cython --annotate

import random

def cython_inversion_binomial(int n, double p) -> int:
    if p <= 1e-9:
        return 0
    if p >= 1 - 1e-9:
        return n
    if p > 0.5:  # speed up by computing for q and then substracting
        return n - cython_inversion_binomial(n, 1.0 - p)
    cdef int result = 0
    cdef double q = 1.0 - p
    cdef double current_proba = q**n
    cdef double cum_proba = current_proba
    cdef double one_uniform_sample = random.random()
    while cum_proba < one_uniform_sample:
        current_proba *= (p * (n - result)) / (q * (result + 1))
        cum_proba += current_proba
        result += 1
    return result


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
It seems to work as wanted!
And now the storage is indeed $O(1)$, and the computation time is $O(x)$ if the return value is $x$, so the mean computation time is $O(np)$.
Note that if $p=1/2$, then $O(np) = O(n/2) = O(n)$, and thus this improved method using the inversion method is (asymptotically) as costly as the naive method (the first method which consists of summing $n$ iid samples from a Bernoulli of mean $p$).
Let's plot this out also.
Can you write Python code for it?

m = 1000
n = 10
p = 0.12345
X = [ inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

m = 1000
n = 10
p = 0.5
X = [ inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

m = 1000
n = 10
p = 0.98765
X = [ inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
It seems to work as wanted!
Let's plot this out also.
Can you write Python code for it?

m = 1000
n = 10
p = 0.12345
X = [ cython_inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

m = 1000
n = 10
p = 0.5
X = [ cython_inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

inversion_binomialm = 1000
n = 10
p = 0.98765
X = [ cython_inversion_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
It's quite awesome to see that our inversion-based method is more efficient that the numpy function, both in the pure-Python and the Cython versions!
But it's weird, as the numpy function is... based on the inversion method, and itself written in C!

See the source code, numpy/distributions.c line 426 (on the 28th February 2019, commit 7c41164).

But the trick is that the implementation in numpy uses the inversion method (running in $\Omega(np)$) if $pn < 30$, and a method denoted "BTPE" otherwise.
I need to work on this method! The BTPE algorithm is much more complicated, and it is described in the following paper:

Kachitvichyanukul, V.; Schmeiser, B. W. (1988). "Binomial random variate generation". Communications of the ACM. 31 (2): 216–222. doi:10.1145/42372.42381.
See the source code, numpy/distributions.c line 263 (on the 28th February 2019, commit 7c41164).

Checking that sampling from $Bin(n,p)$ requires a time $\Omega(n)$.
Can you write Python code for it?

n = 100
%timeit naive_binomial(n, random.random())
%timeit inversion_binomial(n, random.random())
%timeit cython_inversion_binomial(n, random.random())
%timeit numpy_binomial(n, random.random())

n = 1000
%timeit naive_binomial(n, random.random())
%timeit inversion_binomial(n, random.random())
%timeit cython_inversion_binomial(n, random.random())
%timeit numpy_binomial(n, random.random())

n = 10000
%timeit naive_binomial(n, random.random())
%timeit inversion_binomial(n, random.random())
%timeit cython_inversion_binomial(n, random.random())
%timeit numpy_binomial(n, random.random())


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
It's very quick now:
Can you write Python code for it?

def bernoulli(p: float) -> int:
    return 1 if uniform_01() <= p else 0

[ bernoulli(0) for _ in range(5) ]

[ bernoulli(0.12345) for _ in range(5) ]

[ bernoulli(1) for _ in range(5) ]


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
Let's try out.
Can you write Python code for it?

[ cython_inversion_binomial(10, 0.1) for _ in range(5) ]

[ cython_inversion_binomial(10, 0.5) for _ in range(5) ]

[ cython_inversion_binomial(10, 0.9) for _ in range(5) ]


[ first_inversion_binomial(10, 0.1) for _ in range(5) ]

[ first_inversion_binomial(10, 0.5) for _ in range(5) ]

[ first_inversion_binomial(10, 0.9) for _ in range(5) ]


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
Let's try this out:
Can you write Python code for it?

[ numpy_binomial(10, 0.1) for _ in range(5) ]

[ numpy_binomial(10, 0.5) for _ in range(5) ]

[ numpy_binomial(10, 0.9) for _ in range(5) ]


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
The generator included in numpy.random
Can you write Python code for it?

def numpy_binomial(n: int, p: float) -> int:
    return np.random.binomial(n, p)


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
We can quickly illustrate the generated distribution, to check it has the correct "shape":
Can you write Python code for it?

m = 1000
n = 10
p = 0.12345
X = [ naive_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

m = 1000
n = 10
p = 0.5
X = [ naive_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()

m = 1000
n = 10
p = 0.98765
X = [ naive_binomial(n, p) for _ in range(m) ]
plt.figure()
plt.hist(X)
plt.title(f"{m} samples from a Binomial distribution with n = {n} and p = {p}.")
plt.show()


I am working on the file "Efficient_sampling_from_a_Binomial_distribution.ipynb".
The first task is:
We can use the %timeit magic to check the (mean) computation time of all the previously mentioned functions:
Can you write Python code for it?

%timeit naive_binomial(n, 0.123456)
%timeit first_inversion_binomial(n, 0.123456)
%timeit inversion_binomial(n, 0.123456)
%timeit cython_inversion_binomial(n, 0.123456)
%timeit numpy_binomial(n, 0.123456)


I am working on the file "Eigenfunctions-Laplace-snowflake.ipynb".
The first task is:
Compute the K smalllest eigenvalues and eigenfunctions of the Laplace operator, https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigs.html,  with shift-invert mode corresponding to sigma=0.
In this case the transformed eigenvalues are eigvals'=1/(eigvals-sigma)=1/eigvals.
With the option which='LM' we get the k largest eigvals', i.e.  the smallest
eigenvalues of the original problem.
Laplace.todense() is a symmetric positive matrix of dimension $n^2 \times n^2$. The eigenvalues of the Laplace matrix  are ordered as follows:
$$0\leq\lambda_0\leq \lambda_1 \leq \cdots \lambda_{n^2-1}$$
with $\lambda_0>0$ for Dirichlet boundary condition.
Can you write Python code for it?

def Laplace_spectrum(Laplace, K):
    return  scipy.sparse.linalg.eigsh(Laplace, K, which='LM', sigma=0) #eigvals, u

def get_plotly_contour(u, bimg,   I, size=0.1, colorscale = 'RdBu', reversescale=False):
    # u: eigenfunction to be plotted
    # bimg: binary array representing the bounded domain on which the Laplace spectrum is computed image
    # I: index of the eigenvalue whose eigenfunction is plotted
    # size:  step for  contour lines
    if I >= u.shape[1]:
        raise ValueError(f'You must compute first at least {I+1} eigenvalues and eigenfunctions')
    n = bimg.shape[0]
    uu = u[:, I].reshape((n, n)) #reshape the I^th eigenvector to create a contour trace from it
    uu = uu / np.max(np.fabs(uu)) # normalize the image representing the eigenfunction u[:,I]
    uu[bimg==1] = np.nan
    comin, comax = np.nanmin(uu), np.nanmax(uu)
    lim = max([abs(comin), comax])  #-lim, lim are the  start, and end values for the contour lines
    return go.Contour(
                    z=uu.tolist(),
                    colorscale=colorscale,
                    reversescale=reversescale,
                    colorbar=dict(thickness=20),
                    contours=dict(start=-lim, end=lim, size=size),
                    line=dict(width=0.5, color='rgb(200,200,200)'))

pl_RdYlBu = [[0.0, 'rgb(49, 54, 149)'],
            [0.1, 'rgb(68, 115, 179)'],
            [0.2, 'rgb(116, 173, 209)'],
            [0.3, 'rgb(169, 216, 232)'],
            [0.4, 'rgb(224, 243, 248)'],
            [0.5, 'rgb(254, 254, 190)'],
            [0.6, 'rgb(254, 224, 144)'],
            [0.7, 'rgb(252, 172, 96)'],
            [0.8, 'rgb(244, 109, 67)'],
            [0.9, 'rgb(214, 47, 38)'],
            [1.0, 'rgb(165, 0, 38)']]

layout = go.Layout(title='',
                   font=dict(family='Balto',
                             size=12),
                   width=600, height=600,
                   xaxis=dict(visible=False),
                   yaxis=dict(visible=False),
                   plot_bgcolor='rgb(0, 101, 93)')


I am working on the file "Ejemplo 1 Hipérbola - rotación negativa.ipynb".
The first task is:
El ángulo de rotación $\theta$ (en radianes)
Can you write Python code for it?

theta = -np.arccos(float(b / LA.norm(v1)))
theta


I am working on the file "Ejemplo 1 Hipérbola - rotación negativa.ipynb".
The first task is:
aquí la ecuación introducida fue
$$
    3x^2 + 10xy + 3y^2 - 2x - 14y + 5 = 0,
$$
cuyo orden es el acostumbrado, sin embargo el resultado de la función coeffs corresponde a los coeficientes polinómio con todos los términos en $x$ ordenados al incio del polinomio, i.e
$$
    3x^2 + 10xy - 2x + 3y^2 - 14y + 5 = 0,
$$
con lo anterior, para continuar con el desarrollo expresado en Cónicas rotadas se asignan los correspondientes índices del arreglo Coefs como sigue
Can you write Python code for it?

a = Coefs[0]
b = Coefs[1]
c = Coefs[3]
d = Coefs[2]
e = Coefs[4]
f = Coefs[5]


I am working on the file "Ejemplo 1 Hipérbola - rotación negativa.ipynb".
The first task is:
con $\lambda_1 = -2$ y $T_1 = -5 \neq f$ la ecuación dada corresponde a una hipérbola
Las coordenadas $(u, v)$ del centro transformadas al plano $x,\;\; y$ (las coordenadas $(h, k)$)
Can you write Python code for it?


I am working on the file "Ejemplo 1 Hipérbola - rotación negativa.ipynb".
The first task is:
el determinante de la matriz $M$
Can you write Python code for it?


I am working on the file "Ejemplo 1 Hipérbola - rotación negativa.ipynb".
The first task is:
y se construye la matriz $M$
Can you write Python code for it?

M = sp.matrix([[a, b / 2], [b / 2, c]], dtype = float)
M


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Cálculo de la profundidad total medida (MD, measure depth)
Cálculo del desplazamiento en el plano XY
A través del teorema de Pitágoras calculamos la hipotenusa del plano horizontal (XY) y el plano vertical.
Can you write Python code for it?

delta_xoffset = np.diff(tr.XOFFSET) #Diferencia del desplazamiento de X-OFFSET
delta_yoffset = np.diff(tr.YOFFSET) #Diferencia del desplazamiento de Y-OFFSET
deltaz_tvd = np.diff(tr.TVD) #Diferencia de la TVD

delta_xy=np.sqrt(pow(delta_xoffset, 2)+pow(delta_yoffset,2)) #Hipotenusa en el plano XY
delta_z_xy = np.sqrt(pow(delta_xy,2)+pow(deltaz_tvd,2)) #Hipotenusa en el plano Z-XY

MD = np.round (np.cumsum(delta_z_xy),3)   #Cálculo de la suma acumulada de las diferencias en el plano Z-XY


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Escalar el "dataframe" tr
Can you write Python code for it?

tr_md = tr.iloc[ 1 : 112 , :]

print (len(tr_md)) ; print (len(MD))


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Exportar la tabla en formato CSV
Can you write Python code for it?


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Gráfica 2D
Can you write Python code for it?

################################
f1 = plt.figure(figsize = [15,10])
plt.style.use('bmh')

#Plano XZ

fig1 = f1.add_axes([0, 0, 0.2,0.7])
fig1.plot(tr.XOFFSET, tr.TVD,'r', alpha=1, lw=3)
fig1.set_title('Plano XZ', fontsize='14')
fig1.set_ylabel('Profundidad ' + '[m]', fontsize = '11' )
fig1.set_xlabel('Desplazamiento en X '+ '[m]', fontsize = '11')
fig1.set_yticks(np.linspace (min(tr.TVD),max(tr.TVD),15) )
fig1.set_xticks( np.linspace (min(tr.XOFFSET), 800, 5))
fig1.invert_yaxis()
fig1.grid(True, alpha=1)

#Plano YZ

fig2 = f1.add_axes([0.25, 0, 0.2,0.7])
fig2.plot(tr.YOFFSET, tr.TVD,'r', alpha=1, lw=3)
fig2.set_title('Plano YZ', fontsize='14')
fig2.set_xlabel('Desplazamiento en Y '+ '[m]', fontsize = '11')
fig2.set_yticks(np.linspace (min(tr.TVD),max(tr.TVD),15) )
fig2.set_xticks( np.linspace (min(tr.XOFFSET), 800, 5))
fig2.invert_yaxis()
fig2.grid(True, alpha=1)

#Plano XY

fig3 = f1.add_axes([0.50, 0.2, 0.25,0.3])
fig3.plot(tr.YOFFSET, tr.XOFFSET,'r', alpha=1, lw=3)
fig3.set_title('Plano XY', fontsize='14')
fig3.set_ylabel('Desplazamiento en Y ' + '[m]', fontsize = '11' )
fig3.set_xlabel('Desplazamiento en X '+ '[m]', fontsize = '11')
fig3.grid(True, alpha=1)

plt.show()


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Gráfica 3D
Can you write Python code for it?

fig = plt.figure(figsize=[8, 14])
mpl.rcParams['legend.fontsize'] = 10
fig4 = fig.gca(projection='3d')

fig4.plot(tr.XOFFSET/1000,tr.YOFFSET/1000,tr.TVD/1000,  'r', lw=4)
fig4.set_title("Pozo Zanahoria \n Coordendas XY-Desplazamiento", color= "K",fontsize= 12)
fig4.invert_zaxis()
fig4.invert_xaxis()
fig4.invert_yaxis()
fig4.set_xlabel('X Desplazamiento [km]' , fontsize=11)
fig4.set_ylabel('Y desplazamiento [km]' , fontsize=11)
fig4.set_zlabel('Profundidad [km]', fontsize=11)

fig4.view_init(elev=5, azim=-125)

#plt.savefig('survey3D.png', transparent=True, dpi=600, bbox_inches="tight" )

plt.show()


I am working on the file "Ejercicio01-Cálculo de la profundidad medida.ipynb".
The first task is:
Integrar los datos calculados en la tabla de datos original
Can you write Python code for it?

tr_tot = tr_md.assign(XABS=XABS, YABS=YABS, MD=MD)

print(tr_tot)


I am working on the file "Ejercicios 1.1 -  Graphs, Paths & Components.ipynb".
The first task is:
Cree un grafo de N nodos con el máximo diámetro posible
Cree un grafo de N nodos con el mínimo diámetro posible
Cree un grafo de N nodos que sea un ciclo simple
Ejercicio - Pregunta "real"
Una aerolínea tiene las siguientes rutas desde las ciudades a las que sirve (cada par tiene servicio en ambas direcciones).
Can you write Python code for it?

routemap =  [('St. Louis', 'Miami'),
             ('St. Louis', 'San Diego'),
             ('St. Louis', 'Chicago'),
             ('San Diego', 'Chicago'),
             ('San Diego', 'San Francisco'),
             ('San Diego', 'Minneapolis'),
             ('San Diego', 'Boston'),
             ('San Diego', 'Portland'),
             ('San Diego', 'Seattle'),
             ('Tulsa', 'New York'),
             ('Tulsa', 'Dallas'),
             ('Phoenix', 'Cleveland'),
             ('Phoenix', 'Denver'),
             ('Phoenix', 'Dallas'),
             ('Chicago', 'New York'),
             ('Chicago', 'Los Angeles'),
             ('Miami', 'New York'),
             ('Miami', 'Philadelphia'),
             ('Miami', 'Denver'),
             ('Boston', 'Atlanta'),
             ('Dallas', 'Cleveland'),
             ('Dallas', 'Albuquerque'),
             ('Philadelphia', 'Atlanta'),
             ('Denver', 'Minneapolis'),
             ('Denver', 'Cleveland'),
             ('Albuquerque', 'Atlanta'),
             ('Minneapolis', 'Portland'),
             ('Los Angeles', 'Seattle'),
             ('San Francisco', 'Portland'),
             ('San Francisco', 'Seattle'),
             ('San Francisco', 'Cleveland'),
             ('Seattle', 'Portland')]


I am working on the file "Ejercicios/El problema de los matrimonios estables/matrimonios_estables.ipynb".
The first task is:
Nota: Este ejercicio sigue la nomenclatura y la estructura clásicas de este problema para que resulte intuitivo y fácil de seguir, no pretende ser un modelo real de comportamiento. Desde la organización de la PyConEs y nosotros mismos, queremos fomentar y apoyar la diversidad y la tolerancia en todas las facetas de la sociedad, y respetamos por igual todas las identidades de género y sexualidad.
Can you write Python code for it?

import numpy as np
import random as random

class Woman (object):
    ''' Este es el elemento estático, quien recibe propuestas y elige al mejor'''
    def __init__(self, name):

        self.name = name
        self.preferences = {}
        self.preferences_inv = {}
        self.boyfriend = []
        self.candidates = []

    def engage(self, man):
            self.boyfriend = man
            man.girlfriend = self

    def breakup(self, man):
            self.boyfriend = []
            man.girlfriend = []

class Man (object):
    '''Este es el elemento dinámico, que busca a su mejores opciones y se propone'''

    def __init__(self, name):

        self.name = name
        self.preferences = {}
        self.preferences_inv = {}
        self.girlfriend = []
        self.number_of_proposals = 1

    def propose(self, woman):
        woman.candidates += [self]
        self.number_of_proposals += 1


I am working on the file "Ejercicios/El vecindario racista/El vecindario racista.ipynb".
The first task is:
Aquí podemos ver un pequeño vecindario, con vecinos azules y rojos. También hay espacios libres que no están ocupados por nadie.
Cada vecino se ve afectado por las 8 casillas que tiene a su alrededor. En principio, no le molesta la presencia de vecinos de un color diferente, pero si la proporción de vecinos de su mismo color es de sólo 1/3 o menos, se sentirá incomodado y deseará marcharse.
En el gráfico superior, los vecinos incomodados tienen unas esquinas grises, mientras que los vecinos confortables no.
Estos vecinos que se sienten incómodos se mudarán en cuanto puedan. Para representar esto, repasaremos la lista de vecinos, detectando a los que quieren mudarse, y cambiarán de sitio a una casilla nueva aleatoria que esté vacía.
Esto representa un 'step'.
Can you write Python code for it?

n = vc.step_mudanza(mundo, colores, 1, 10)


I am working on the file "Ejercicios/El vecindario racista/El vecindario racista.ipynb".
The first task is:
Extendiendo el algoritmo
Ahora que ya hemos visto cómo trabaja este modelo, vamos a jugar un poco con sus parámetros. ¿Te atreves a predecir cómo influirán estos números en un vecindario de tres colores?
Can you write Python code for it?

dim = 50 #Tamaño del lado de la matriz
vacios = 10 #Porcentaje de huecos
colors = 3 #Número de colores
prop = [0.33, 0.33]
n = 0
intolerance = 33 #Porcentaje mínimo de vecinos iguales
intom = 100 #Porcentaje máximo de vecinos iguales
rad = 1 # Radio en el que el color de los vecinos se comprueba
historia_felicidad = [] # Aquí vamos a almacenar la felicidad del grupo en cada step
historia_segregacion = []# Y aquí, el valor de la segregación.

#Veamos cómo comienza la simulación, con los vecinos repartidos aleatoriamente.
par, datacolor = vc.crear_mundo(dim, colors= colors, prop= prop, vacios = vacios,
                             intolerance=intolerance, intom= intom, rad = rad,
                            h_fel = historia_felicidad, h_seg = historia_segregacion)

vc.vecin_print(par, datacolor, dim, n)

#Qué pasará dentro de 50 steps?
n = vc.step_multiple(par, datacolor, n, dim,
           historia_felicidad, historia_segregacion, 50)


I am working on the file "Ejercicios/El vecindario racista/El vecindario racista.ipynb".
The first task is:
Podemos comprobar que aunque los individuos no prefieren ningún tipo de segregación, y su única condición es que al menos 1/3 de sus vecinos sean del mismo color que ellos, al cabo de unos pocos steps la segregación en grupos homogéneos ha aparecido como propiedad emergente.
Can you write Python code for it?

n = vc.step_multiple(mundo, colores, n, 10)


I am working on the file "Ejercicios/El vecindario racista/El vecindario racista.ipynb".
The first task is:
Supongamos que tenemos un vecindario. Este vecindario es una matriz o casillero, en el que cada vecino puede ocupar una casilla.
Can you write Python code for it?

mundo, colores = vc.crear_mundo()
vc.vecin_print(mundo, colores,  10, 0)


I am working on the file "Ejercicios/El vecindario racista/El vecindario racista.ipynb".
The first task is:
¿Qué crees que pasará en un vecindario igual pero más concienciado?
Can you write Python code for it?

intom = 90 #Porcentaje máximo de vecinos iguales
n = 0 #Vamos a comenzar de 0
historia_felicidad = [] # Aquí vamos a almacenar la felicidad del grupo en cada step
historia_segregacion = []# Y aquí, el valor de la segregación.

#Veamos cómo comienza la simulación, con los vecinos repartidos aleatoriamente.
par, datacolor = vc.crear_mundo(dim, colors= colors, prop= prop, vacios = vacios,
                             intolerance=intolerance, intom= intom, rad = rad,
                            h_fel = historia_felicidad, h_seg = historia_segregacion)

vc.vecin_print(par, datacolor, dim, n)

#Qué pasará dentro de 50 steps?
n = vc.step_multiple(par, datacolor, n, dim,
           historia_felicidad, historia_segregacion, 50)

vc.evolucion(historia_felicidad, historia_segregacion)


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
El algoritmo podría haber encontrado una ruta mejor, comprobémoslo:
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Empecemos a mover a nuestras hormigas!
Para que la primera generación de hormigas recorra el mapa llamaremos a la función swarm_generation():
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Lo primero que vamos a hacer es crear un mapa que contenga nuestras ciudades. Como primer argumento le pasamos el número de ciudades, y como segundo, el tamaño del mapa. Al ser creado, el mapa generará automáticamente las ciudades en posiciones aleatorias.
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Para poder encontrar una buena ruta, necesitaremos que pasen unas cuantras generaciones más... Pongamos que 50
Can you write Python code for it?

for i in range(50):
    print(i, end = '·')
    map1.swarm_generation()
map1.show_feromones_matrix()
map1.draw_feromones()


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Podemos borrar las feromonas y empezar de nuevo el algoritmo, para ver si siempre llegan a la misma solución. No te preocupes, al algoritmo no borrará la mejor ruta encontrada.
Can you write Python code for it?

for j in range(3):
    map1.feromone_reset()
    print()
    print('Ejecución', j+1, ', generación: ')
    for i in range(50):
        print(i+1, end = '·')
        map1.swarm_generation()
    map1.draw_feromones()


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Podemos comprobar fácilmente que la matriz de distancias es simétrica, y que la matriz de feromonas aún está vacía:
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Podemos observar cómo han ido variando las longitudes máxima, mínima y media de los caminos de las hormigas en cada generación, y compararlas con la del mejor camino encontrado:
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Podemos ver el mapa con las ciudades unidas por líneas cuyo grosor depende de la distancia entre ellas:
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
Si queremos ver dónde se encuentran nuestras hormigas en un momento dado, podemos hacerlo:
Can you write Python code for it?


I am working on the file "Ejercicios/Hormiguero/Hormiguero.ipynb".
The first task is:
También podemos dibujar las longitudes mínimas de cada ejecución del algoritmo:
Can you write Python code for it?


I am working on the file "Ejercicios/Laberinto/Laberinto.ipynb".
The first task is:
Pintemos el laberinto!
Can you write Python code for it?


I am working on the file "Ejercicios/Laberinto/Laberinto.ipynb".
The first task is:
Resultados
Llegados a este punto, lo más probable es que el algoritmo haya encontrado un bucle o una salida. Si no, puedes volver a ejecutar la celda superior para avanzar unas generaciones más.
Todos los caminos de la última generación están representados como líneas rojas semitransparentes, de modo que las casillas más atravesadas van acumulando capas de rojo. Además, el mejor camino encontrado se muestra destacado en azul.
También puedes correr el algoritmo desde el principio si añades "mapa1 = lab.Map()" antes de "lab.avanzar(mapa1)".
Si pruebas a ejecutarlo varias veces, observarás lo antes comentado, cuando alcanza la salida, todo genial, pero si llega a un bucle, ¿Qué podemos hacer para sacarlo de ahí?
La respuesta es, obviamente, añadir Neurotoxinas Letales al laberinto. Pero no de cualquier manera!
Añadiendo Feedback
Supongamos que cada persona que va recorriendo el laberinto a dejando a su paso un olor fétido que hace que todos los demás prefieran no tener que pasar por allí. ¿Cómo crees que eso afectaría a los bucles?
La manera de implementar este efecto es añadir al mapa una capa de profundidad, una matriz adicional que expresa la cantidad de veneno, feromona negativa o mal olor que hay en cada casilla. Después, al analizar nuestro camino, contaremos también la cantidad de veneno que hemos atravesado para puntuar la calidad del camino dentro del algoritmo.
Comprobémoslo!
Ejecuta de nuevo el algoritmo, pero ahora añadiendo veneno. Ejecútalo varias veces! ¿Aparecen bucles con la misma frecuencia?
Can you write Python code for it?

mapa2 = lab.Map(veneno=1)
lab.avanzar(mapa2)
lab.draw_all(mapa2)


I am working on the file "Ejercicios/Laberinto/Laberinto.ipynb".
The first task is:
Sin embargo, abusar de las neurotoxinas letales también puede tener problemas, ¡Quién lo hubiera adivinado!
¡Prueba con la configuración siguiente!
Can you write Python code for it?

mapa2 = lab.Map(veneno=100)
lab.avanzar(mapa2)
lab.draw_all(mapa2)


I am working on the file "Ejercicios/Laberinto/Laberinto.ipynb".
The first task is:
Un viajero que intentara seguir estas indicaciones, estaría en un buen apuro. ¡Incluso algunas flechas apuntan a las paredes! Necesitaremos ser un poco flexibles para recorrerlo:

Si la dirección de la casilla le dice que intente atravesar una pared, el viajero intentará otra dirección aleatoria.

El viajero tendrá una cantidad limitada de pasos.

Probémoslo!
Can you write Python code for it?


I am working on the file "Ejercicios/Laberinto/Laberinto.ipynb".
The first task is:
Ya tenemos un valor numérico, lancemos el algoritmo!
Can you write Python code for it?


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
A continuación crearemos un diccionario de genes. En él iremos almacenando los nombres de los parámetros y la cantidad de bits que usaremos para definirlos. Cuantos más bits, más resolución
Ej: 1 bit : 2 valores, 2 bit : 4 valores, 10 bit : 1024 valores
Can you write Python code for it?

#Completa este diccionario con las variables que hayas elegido y los bits que usarás

dict_genes = {
    'omega' : 10,
    'R': 10,
    'b': 2
}


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Ahora podemos crear nuestra sociedad:
Can you write Python code for it?

society = []
immigration (society, 12, dict_genes) #12 por ejemplo, pueden ser los que sean

#Veamos qué pinta tienen los genes de la población
plt.matshow([individual.genome for individual in society], cmap=plt.cm.gray)


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Ahora, crearemos una función que rellene estos genomas con datos aleatorios:
Can you write Python code for it?

def generate_genome (dict_genes):

    #Calculamos el número total de bits con un bucle que recorra el diccionario

    n_bits = ?

    #Generamos un array aletorio de 1 y 0 de esa longitud con numpy
    genome = np.random.randint(0, 2, nbits)

    #Transformamos el array en una lista antes de devolverlo
    return list(genome)

# Podemos probar a usar nuestra función, para ver qué pinta tiene el ADN de un rotor:
generate_genome(dict_genes)


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Empecemos echando un ojo a la función del rotor, para ver qué vamos a necesitar y con qué parámetros vamos a trabajar.
Can you write Python code for it?


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Podemos trazar unas cuantas curvas para observar qué pinta va a tener lo que saquemos. Por ejemplo, cómo cambian las características de la hélice dependiendo de la velocidad de vuelo, para una hélice de ejemplo que gira a uyna velocidad dada.
Can you write Python code for it?

vel = np.linspace(0, 30, 100)
efic = np.zeros_like(vel)
T = np.zeros_like(vel)
P = np.zeros_like(vel)
mach = np.zeros_like(vel)
for i in range(len(vel)):
    T[i], P[i], efic[i], mach[i] = calcular_rotor(130, vel[i], 0.5, 3)

plt.plot(vel, T)
plt.title('Tracción de la hélice')

plt.plot(vel, P)
plt.title('Potencia consumida')

plt.plot(vel, efic)
plt.title('Eficiencia de la hélice')

plt.plot(vel, mach)
plt.title('Mach en la punta de las palas')


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Trabajando con el individuo
Ahora necesitamos una función que transforme esos genes a valores con sentido. Cada gen es un número binario cuyo valor estará entre 0 y 2 ^ n, siendo n el número de bits que hayamos escogido. Estas variables traducidas las guardaremos en otro diccionario, ya con su valor. Estos genes no están volando por ahí sueltos, sino que estarán guardados en el interior del individuo al que pertenezcan, por lo que la función deberá estar preparada para extraerlos del individuo, y guardar los resultados a su vez en el interior del individuo.
Can you write Python code for it?

def calculate_traits (individual, dict_genes):

    genome = individual.genome

    integer_temporal_list = []

    for gen in dict_genes: #Recorremos el diccionario de genes para ir traduciendo del binario

        ??? #Buscamos los bits que se corresponden al bit en cuestión

        ??? #Pasamos de lista binaria a número entero

        integer_temporal_list.append(??) #Añadimos el entero a la lista

    # Transformamos cada entero en una variable con sentido físico:
    # Por ejemplo, si el entero de la variable Omega está entre 0 y 1023 (10bits),
    # pero la variable Omega real estará entre 0 y 200 radianes por segundo:
    omega = integer_temporal_list[0] * 200 / 1023

    #del mismo modo, para R:
    R =  0.1 + integer_temporal_list[1] * 1.9 / 1023 #Obtendremos un radio entre 0.1 y 2 metros

    #El número de palas debe ser un entero, hay que tener cuidado:
    b = integer_temporal_list[2] + 2 #(entre 2 y 5 palas)

    #Continúa con el resto de variables que hayas elegido!

    dict_traits = {     #Aquí iremos guardando los traits, o parámetros
        'omega' : omega,
        'R': R
    }
    individual.traits = dict_traits #Por último, guardamos los traits en el individuo


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Ya tenemos nuestra pequeña sociedad, aumentémosla un poco más mezclando entre sí a los ciudadanos con mejores fitness! Vamos a extender nuestra población mezclando los genomas de otros individuos. Los individuos con mejor fitness es más probable que se reproduzcan. Además, en los nuevos individuos produciremos ligeras mutaciones aleatorias.
Can you write Python code for it?

#This function was taken from Eli Bendersky's website
#It returns an index of a list called "weights",
#where the content of each element in "weights" is the probability of this index to be returned.
#For this function to be as fast as possible we need to pass it a list of weights in descending order.
def weighted_choice_sub(weights):

    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        rnd -= w
        if rnd < 0:
            return i

def crossover (society, reproduction_rate, mutation_rate):

    #First we create a list with the fitness values of every individual in the society
    fitness_list = [individual.fitness for individual in society]

    #We sort the individuals in the society in descending order of fitness.
    society_sorted = [x for (y, x) in sorted(zip(fitness_list, society), key=lambda x: x[0], reverse=True)]

    #We then create a list of relative probabilities in descending order,
    #so that the fittest individual in the society has N times more chances to reproduce than the least fit,
    #where N is the number of individuals in the society.
    probability = [i for i in reversed(range(1,len(society_sorted)+1))]

    #We create a list of weights with the probabilities of non-mutation and mutation
    mutation = [1 - mutation_rate, mutation_rate]

    #For every new individual to be created through reproduction:
    for i in range (int(len(society) * reproduction_rate)):

        #We select two parents randomly, using the list of probabilities in "probability".
        father, mother = society_sorted[weighted_choice_sub(probability)], society_sorted[weighted_choice_sub(probability)]

        #We randomly select two cutting points for the genome.
        a, b = random.randrange(0, len(father.genome)), random.randrange(0, len(father.genome))

        #And we create the genome of the child putting together the genome slices of the parents in the cutting points.
        child_genome =...


I am working on the file "Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb".
The first task is:
Ya tenemos nuestro algoritmo prácticamente terminado!
Can you write Python code for it?

society = []
fitness_max = []

for generation in range(30):

    immigration (society, 100, dict_genes) #Añade individuos aleatorios a la sociedad hasta tener 100
    fitness_max += [max([individual.fitness for individual in society])]

    tournament (society, 15) #Los hace competir hasta que quedan 15
    crossover(society, 5, 0.05) #Los ganadores se reproducen hasta tener 75

plt.plot(fitness_max)
plt.title('Evolución del valor de fitness')

tournament (society, 1) #Buscamos el mejor de todos
winner = society[0]

print(winner.traits) #Comprobamos sus características
print(winner.performances)


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
Aquí podemos ver un pequeño vecindario, con vecinos azules y rojos. También hay espacios libres que no están ocupados por nadie.
Cada vecino se ve afectado por las 8 casillas que tiene a su alrededor. En principio, no le molesta la presencia de vecinos de un color diferente, pero si la proporción de vecinos de su mismo color es de sólo 1/3 o menos, se sentirá incomodado y deseará marcharse.
En el gráfico superior, los vecinos incomodados tienen unas esquinas grises, mientras que los vecinos confortables no.
Estos vecinos que se sienten incómodos se mudarán en cuanto puedan. Para representar esto, repasaremos la lista de vecinos, detectando a los que quieren mudarse, y cambiarán de sitio a una casilla nueva aleatoria que esté vacía.
Esto representa un 'step'.
Can you write Python code for it?


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
Cómo podemos evitar esta situación?
Existe una sencilla manera de evitarlo: que los individuos activamente trabajen para evitar la segregación. La manera de implementar esto es muy sencilla: basta con que también se sientan incómodos si más del 90% de sus vecinos son iguales a ellos para obtener cambios sustanciales en la segregación del grupo.
Can you write Python code for it?

mundo, colores = vc.crear_mundo(intom = 90)
n = vc.step_multiple(mundo, colores, 0, 10, numsteps=100)


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
Extendiendo el algoritmo
Ahora que ya hemos visto cómo trabaja este modelo, vamos a jugar un poco con sus parámetros. ¿Te atreves a predecir cómo influirán estos números en un vecindario de tres colores?
Can you write Python code for it?


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
Podemos comprobar que aunque los individuos no prefieren ningún tipo de segregación, y su única condición es que al menos 1/3 de sus vecinos sean del mismo color que ellos, al cabo de unos pocos steps la segregación en grupos homogéneos ha aparecido como propiedad emergente.
Can you write Python code for it?


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
Supongamos que tenemos un vecindario. Este vecindario es una matriz o casillero, en el que cada vecino puede ocupar una casilla.
Can you write Python code for it?


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
¡Sorpresa! ¿Esperabas esto?
También podemos observar cómo han ido evolucionando:
Can you write Python code for it?


I am working on the file "El vecindario racista - Modelo de segregacion de Schelling/El vecindario racista.ipynb".
The first task is:
¿Qué crees que pasará en un vecindario igual pero más concienciado?
Can you write Python code for it?


I am working on the file "ElCuadernillo/20160214_TensorFlowTutorialBasico/TensorFlow_Interactivo_IPython.ipynb".
The first task is:
De esta manera lanzar una sesion interactiva, util cuando queremos probar metodos
Can you write Python code for it?

sess = tf.InteractiveSession()

x = tf.Variable([[2.0, 3.0],[4.0, 12.0]])


I am working on the file "ElCuadernillo/20160214_TensorFlowTutorialBasico/TensorFlow_Interactivo_IPython.ipynb".
The first task is:
Probamos la funcion que nos reduce un tensor por medio de medias
Can you write Python code for it?

x.initializer.run()
tf.reduce_mean(x).eval()

tf.reduce_mean(x,1).eval()

tf.reduce_mean(x,0).eval()


I am working on the file "ElCuadernillo/20160220_TensorFlowRegresionMultiple/tensorflow_regresion_multiple_gradiente_descendente.ipynb".
The first task is:
Mostramos la curva de error por iteracion
Solución 2: Por medio stochastic gradient descent
Mucho mas rápido para grandes volumenes de datos
Can you write Python code for it?