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

import brian2 as br

### Define the rhodopsin model
nStates = '6'
origParams = modelFits[nStates]['ChR2'] # Load from pre-fit models
# Alternatively uncomment the line below to use fitted params from above
#origParams = loadData('fitted{}sParams'.format(nStates))
RhO = models[nStates](origParams)

### Define the stimulation protocol
Prot = protocols['step']()
Prot.phis = [1e18]
Prot.Vs = [None]
Prot.cycles = [[150, 100], [200, 75]]

### Define network parameters
from brian2.units import Mohm
from brian2.units.stdunits import ms, mV
N = 80
pConnect = 0.2
psp = 'v_post += 1.5*mV'
delay = 3*ms
netParams = {'tau_m':10*ms, 'R_m':70*Mohm, 'E_m':-70*mV, 'v_t0':-50*mV, 'sigma':10*mV, 't_ref':4*ms}

### Define neuron model
eqRhO = '''dv/dt = ((-I*R_m)+E_m-v)/tau_m + sigma*xi*tau_m**-0.5 : volt''' + RhO.brian_phi_t
eqLIF = '''dv/dt = (E_m-v)/tau_m + sigma*xi*tau_m**-0.5 : volt'''

### Create neuron groups - use Euler-Maruyama method for stochasticity
G0 = br.NeuronGroup(N, eqRhO, threshold='v>v_t0', reset='v=E_m', refractory='t_ref',
                    namespace=netParams, name='Inputs', method='euler')
G0.v = 'rand()*(v_t0-E_m)+E_m'
G1 = br.NeuronGroup(N/2, eqLIF, threshold='v>v_t0', reset='v=E_m', refractory='t_ref',
                    namespace=netParams, method='euler')
G1.v = 'rand()*(v_t0-E_m)+E_m'
G2 = br.NeuronGroup(N/4, eqLIF, threshold='v>v_t0', reset='v=E_m', refractory='t_ref',
                    namespace=netParams, method='euler')
G2.v = 'rand()*(v_t0-E_m)+E_m'

### Create synapses
S1 = br.Synapses(G0, G1, on_pre=psp, delay=delay)
S1.connect(True, p=pConnect)
S2 = br.Synapses(G1, G2, on_pre=psp, delay=delay)
S2.connect(True, p=pConnect)

### Create monitors
monitors = {'states' : br.StateMonitor(G0, RhO.brianStateVars, record=0),   # Record states
            'I'      : br.StateMonitor(G0, 'I', record=0),                  # Record current
            'V'      : br.StateMonitor(G0, 'v', record=0),                  # Record voltage
            'spikes' : [br.SpikeMonitor(G0, name='Retina'),           ...


I am working on the file "Prometheus.ipynb".
The first task is:
Model fitting process
N.B. Model-fitting is optional.
Fitting the three-state model takes approximately 30 seconds and the six-state model takes around 15 minutes.
Can you write Python code for it?

# Three-state model parameter fitting
initParams = Parameters()
initParams.add_many(
                # Name   Value   Vary    Min     Max     Expr
                ('g0',   1e5,    True,   0.001,  1e6,    None),
                ('phi_m',1e18,   True,   1e15,   1e19,   None),
                ('k_a',  5,      True,   0.001,  1000,   None),
                ('k_r',  0.1,    True,   0.001,  1000,   None),
                ('p',    0.8,    True,   0.1,    5,      None),
                ('q',    0.25,   True,   0.1,    5,      None),
                ('Gd',   0.1,    True,   0.0001, 1,      None),
                ('Gr0',  0.0002, True,   0.0001, 0.1,    None),
                ('E',    0,      True,   -1000,  1000,   None),
                ('v0',   43,     True,   -1e15,  1e15,   None),
                ('v1',   17.1,   True,   -1e15,  1e15,   None))
saveData(initParams, 'initParams')
from pyrho.datasets import *
ChR2data = loadChR2()
fitParams = fitModels(ChR2data, nStates=3, params=initParams, postFitOpt=True, relaxFact=2)
# Parameters automatically saved as 'fitted{}sParams'.format(nStates)

# Six-state model parameter fitting. N.B. fitting the six-state model takes around 15 minutes.
initParams = Parameters()
initParams.add_many(
                # Name   Value   Vary    Min     Max     Expr
                ('g0',   2.5e4,  True,   0.0,    1e15,   None),
                ('gam',  0.05,   True,   0.00,   1,      None),
                ('phi_m',3.5e17, True,   1e15,   1e19,   None),
                ('k1',   10,     True,   0.0,    1000,   None),
                ('k2',   3,      True,   0.0,    1000,   None),
                ('p',    1,      True,   0.1,    5,      None),
                ('Gf0',  0.04,   True,   0.0,    1000,   None),
                ('k_f',  0.1,    True,   0.0,    1000,   None),
                ('Gb0',  0.02,   True,   0.0,    1000,   None),
                ('k_b',  0.15,   True,   0.0,    1000,   None),
                ('q',    1,      True,   0.1,    5,      None),
   ...


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Analysis of results
Create analysis grid
Can you write Python code for it?

dx = 0.02
dy = 0.02
dz = 0.02

post_x_ = np.arange(-1, 1 + dx, dx)
post_y_ = np.arange(-1, 1 + dy, dy)
post_z_ = np.arange(-1, 1 + dz, dz)

post_x, post_y, post_z = np.meshgrid(
    post_x_, post_y_, post_z_)
post_x = np.ravel(post_x)
post_y = np.ravel(post_y)
post_z = np.ravel(post_z)

post_calculate_exposure = create_calculate_exposure(
    relevant_dwell_positions, x_new=post_x_, y_new=post_y_, z_new=post_z_)

post_exposure = post_calculate_exposure(dwell_times)


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Bounds
Can you write Python code for it?

bounds = ((0, None),)*num_relevant_dwells


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create a custom resolution exposure calculation function for post analysis
Can you write Python code for it?

def create_calculate_exposure(dwell_positions,
                              x_new=None, y_new=None, z_new=None):
    x, y, z = np.meshgrid(
        x_new, y_new, z_new)
    x = np.ravel(x)
    y = np.ravel(y)
    z = np.ravel(z)

    distance_to_dwell_pos = np.array([
        np.sqrt(
            (x[i] - dwell_positions[:,0])**2 +
            (y[i] - dwell_positions[:,1])**2 +
            (z[i] - dwell_positions[:,2])**2
        )
        for i in range(len(x))
    ])

    exposure_per_unit_time = 1 / distance_to_dwell_pos**2

    def calculate_exposure(dwell_times, reshape=False):
        exposure = np.sum(dwell_times * exposure_per_unit_time, axis=1)
        if reshape:
            exposure = np.reshape(exposure, (
                len(x_new), len(y_new), len(z_new)))
        return exposure

    return calculate_exposure

dx = 0.01; dy = 0.01; dz = 0.1

contour_x_ = np.arange(-1, 1 + dx, dx)
contour_y_ = np.arange(-1, 1 + dy, dy)
contour_z_ = z_ #np.arange(-0.7, 0.7 + dz, dz)

contour_calculate_exposure = create_calculate_exposure(
    relevant_dwell_positions, x_new=contour_x_, y_new=contour_y_, z_new=contour_z_)

contour_exposure_init = contour_calculate_exposure(dwell_times, reshape=True)

vmin = 0
vmax = 200
num_contours = 41

fig = plt.figure(figsize=(10,0.3))
cbar_ax = fig.add_subplot(1,1,1)

bounds = np.linspace(vmin, vmax, num_contours)
norm = BoundaryNorm(bounds, green_cm.N)

cb = ColorbarBase(
    cbar_ax, norm=norm, cmap=green_cm,
    orientation='horizontal')

cb.ax.xaxis.set_ticks_position('top')
cb.ax.xaxis.set_label_position('top')

cb.set_clim([vmin, vmax])

contour_exposure = contour_exposure_init.copy()
contour_exposure[contour_exposure > vmax] = vmax

for i, z_value in enumerate(contour_z_):
    plt.figure(figsize=(6,6))

    c = plt.contourf(contour_x_, contour_y_,
        contour_exposure[:, :, i], num_contours,
        vmin=vmin, vmax=vmax, cmap=green_cm)

    reference = z[target_cube] == z_value
    x_target = x[target_cube][reference]
    y_target =...


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create function to display the results of the optimisation as it is being calculated.
Can you write Python code for it?

def display_results(dwell_times):
    dwell_times = np.reshape(dwell_times, (1, num_relevant_dwells))
    exposure = calculate_exposure(dwell_times)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    reference = exposure > 25
    colour = exposure[reference]
    colour[colour > 100] = 100

    small = exposure[reference] < 50
    large = ~small

    ax.scatter(
        x[reference][small], y[reference][small], z[reference][small],
        alpha=0.2, s=3, c=colour[small], cmap=green_cm)

    ax.scatter(
        x[reference][large], y[reference][large], z[reference][large],
        alpha=0.4, s=20, c=colour[large], cmap=green_cm)

    ax.set_xlim([np.min(x_), np.max(x_)])
    ax.set_ylim([np.min(y_), np.max(y_)])
    ax.set_zlim([np.min(z_), np.max(z_)])

    cost_function(dwell_times, debug=True)

    plt.show()


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create initial conditions
Can you write Python code for it?

num_relevant_dwells

initial_conditions = np.ones(num_relevant_dwells)*0.1


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create initial equidistant parrallel lines to represent catheters. Inbuild a slight random skew to emulate what occurs physically
Can you write Python code for it?

number_of_lines = 16 # Was 16, reduced to 9 for testing

line_start = np.meshgrid(
    [-0.39, -0.13, 0.13, 0.39],
    [-0.39, -0.13, 0.13, 0.39],
    [1])

line_finish = np.array([
    line_start[0] + np.random.normal(scale=0.02, size=[4, 4, 1]),
    line_start[1] + np.random.normal(scale=0.02, size=[4, 4, 1]),
    -line_start[2]])

line_start = np.array([np.ravel(mesh) for mesh in line_start])
line_finish = np.array([np.ravel(mesh) for mesh in line_finish])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create the calculation grid
Can you write Python code for it?

grid_spacing = 0.1 # Was 0.1, using 0.2 to speed up for testing

x_ = np.arange(-0.5, 0.5 + grid_spacing, grid_spacing)
y_ = np.arange(-0.5, 0.5 + grid_spacing, grid_spacing)
z_ = np.arange(-0.5, 0.5 + grid_spacing, grid_spacing)

x, y, z = np.meshgrid(x_, y_, z_)
x = np.ravel(x)
y = np.ravel(y)
z = np.ravel(z)


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Create the optimisation cost function
The maximum exposure to a grid position not within the target is aimed to be less than 100. This cost function aims to achieve this.
Can you write Python code for it?

def hot_exterior_cost_function(max_target_exterior):
    return ((max_target_exterior)/50)**4

testx = np.linspace(0, 120)
testy = hot_exterior_cost_function(testx)
plt.plot(testx, testy)

plt.ylim([0, 20])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Define structures on new finer grid
Can you write Python code for it?

post_target_cube = target(post_x, post_y, post_z)
post_avoid_cube = avoid(post_x, post_y, post_z)


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Define the target and avoid cubes
Can you write Python code for it?


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Display the target and avoid cubes
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(
    x[target_cube], y[target_cube], z[target_cube],
    alpha=0.2, s=2, color='blue')
ax.scatter(
    x[avoid_cube], y[avoid_cube], z[avoid_cube],
    alpha=0.2, s=2, color='red')

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])

ax.view_init(azim=-90, elev=90)
fig


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Find all the dwell positions that are on the grid
Can you write Python code for it?

dwell_positions = np.array([
    [
        find_dwell_coords(
            line_num=line_num, dwell_num=dwell_num)
        for dwell_num in range(number_of_dwells)]
 for line_num in range(number_of_lines)])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Give overview of dwell times segmented by catheter
Can you write Python code for it?

for line_num in range(number_of_lines):

    print("Line number %d" % (line_num))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    ax.scatter(
        x[target_cube], y[target_cube], z[target_cube],
        alpha=0.2, s=2, color='blue')
    ax.scatter(
        x[avoid_cube], y[avoid_cube], z[avoid_cube],
        alpha=0.2, s=2, color='red')

    ref = line_number_index == line_num
    ax.scatter(*np.transpose(relevant_dwell_positions[ref]),
               c=line_colours[line_num], alpha=0.7)

    ax.set_xlim([np.min(x_), np.max(x_)])
    ax.set_ylim([np.min(y_), np.max(y_)])
    ax.set_zlim([np.min(z_), np.max(z_)])

    plt.show()

    plt.scatter(np.arange(np.sum(ref)), optimisation.result[ref],
               c=line_colours[line_num])
    plt.xlabel("Dwell number")
    plt.ylabel("Units of dwell time")

    plt.ylim(bottom=0)
    plt.show()


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Make a function to plot DVHs given a reference
Can you write Python code for it?

def create_dvh(reference, exposure, ax=None):
    if ax is None:
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)

    results = exposure[reference]
    results[results>150] = 150
    hist = np.histogram(results, 100)

    freq = hist[0]
    bin_edge = hist[1]
    bin_mid = (bin_edge[1::] + bin_edge[:-1:])/2

    cumulative = np.cumsum(freq[::-1])
    cumulative = cumulative[::-1]
    bin_mid = np.append([0], bin_mid)

    cumulative = np.append(cumulative[0], cumulative)
    percent_cumulative = cumulative / cumulative[0] * 100

    ax.plot(bin_mid, percent_cumulative)


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
No grid point within the target is to be less than about 50. This cost function aims to achieve this.
Can you write Python code for it?

def cold_target_cost_function(min_target):
    return ((min_target-80)/15)**4

testx = np.linspace(0, 120)
testy = cold_target_cost_function(testx)
plt.plot(testx, testy)

plt.ylim([0, 20])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Pick dwell positons starting at a random position along the line
Can you write Python code for it?

dwell_spacing = 0.1 # Was 0.1, increased to 0.3 for testing
dwell_distances_from_initial = np.arange(0, 2, dwell_spacing)
number_of_dwells = len(dwell_distances_from_initial)

inital_dwell_position = np.random.uniform(
    low=0, high=dwell_spacing, size=number_of_lines)
inital_dwell_position

dwell_distances = np.reshape(inital_dwell_position, (-1, 1)) + np.reshape(dwell_distances_from_initial, (1, -1))

def find_dwell_coords(line_num=None, dwell_num=None):
    distance = dwell_distances[line_num, dwell_num]

    coords = find_distance_coords(
        line_num=line_num, distance=distance)

    return coords


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Plotting of relevant DVHs
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_target_cube, post_exposure, ax=ax)
create_dvh(post_avoid_cube, post_exposure, ax=ax)
create_dvh(~post_target_cube, post_exposure, ax=ax)

plt.legend(["Target", "Avoid", "Patient"])

plt.xlim([0, 150])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Presentation of results
Can you write Python code for it?


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Run a test of arbitrary dwell times
Can you write Python code for it?

num_relevant_dwells = len(relevant_dwell_positions)

random_pick = np.random.uniform(
    size=2, high=num_relevant_dwells, low=0).astype(int)

dwell_times = np.zeros([1, num_relevant_dwells])
dwell_times[0, random_pick] = 10

exposure = calculate_exposure(dwell_times)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

reference = exposure > 80
colour = exposure[reference]
colour[colour > 200] = 200

ax.scatter(
    x[reference], y[reference], z[reference],
    alpha=0.2, s=20, c=colour, cmap=green_cm)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Run the optimiser
Can you write Python code for it?

optimisation = BasinhoppingWrapper(
    to_minimise=cost_function,
    initial=initial_conditions,
    step_noise=step_noise,
    basinhopping_confidence=5,
    optimiser_confidence=0.0001,
    n=5,
    debug=display_results,
    bounds=bounds
)


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Select the dwell positions that fall withing the target region. Only use these dwell positions.
Can you write Python code for it?

dwell_positions_to_be_filtered = np.reshape(dwell_positions, (-1, 3))

distance_to_dwell_pos_initial = np.array([
    np.sqrt(
        (x[i] - dwell_positions_to_be_filtered[:,0])**2 +
        (y[i] - dwell_positions_to_be_filtered[:,1])**2 +
        (z[i] - dwell_positions_to_be_filtered[:,2])**2
    )
    for i in range(len(x))
])

closest_voxel_to_dwell = np.reshape(np.argmin(distance_to_dwell_pos_initial, axis=0), [1, -1])
target_cube_voxels = np.reshape(np.where(target_cube)[0], [-1, 1])
is_dwell_closest_to_target = np.any(closest_voxel_to_dwell == target_cube_voxels, axis=0)

relevant_dwell_positions = dwell_positions_to_be_filtered[is_dwell_closest_to_target]

line_number_index = np.reshape(np.arange(number_of_lines), (number_of_lines, 1))
line_number_index = np.ones([number_of_lines, number_of_dwells]) * line_number_index
line_number_index = np.ravel(line_number_index)[is_dwell_closest_to_target]
line_number_index = line_number_index.astype(int)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(
    x[target_cube], y[target_cube], z[target_cube],
    alpha=0.2, s=2, color='blue')

ax.scatter(
    x[avoid_cube], y[avoid_cube], z[avoid_cube],
    alpha=0.2, s=2, color='red')

for line_num in range(number_of_lines):
    ref = line_number_index == line_num
    ax.scatter(*np.transpose(relevant_dwell_positions[ref]),
               c=line_colours[line_num], alpha=0.7)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
Step noise
Can you write Python code for it?

step_noise = np.ones(num_relevant_dwells) * 0.3


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
The avoid cost function aims to make no point within the avoid structure more than 45.
Can you write Python code for it?

def hot_avoid_cost_function(max_avoid):
    return ((max_avoid)/25)**4

testx = np.linspace(0, 120)
testy = hot_avoid_cost_function(testx)
plt.plot(testx, testy)

plt.ylim([0, 20])


I am working on the file "Proof of concept minimise cold probability.ipynb".
The first task is:
With the shift the change in the DVH is the following. For the optimisation given here there is very little change in DVH.
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_target_cube, post_exposure, ax=ax)
create_dvh(post_target_cube, shifted_exposure, ax=ax)

plt.legend(["Original", "With position error"], loc='lower left')

plt.xlim([0, 110])
# plt.ylim([95, 100])

np.min(shifted_exposure[post_target_cube])

np.min(post_exposure[post_target_cube])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_avoid_cube, post_exposure, ax=ax)
create_dvh(post_avoid_cube, shifted_exposure, ax=ax)

plt.legend(["Original", "With position error"], loc='upper right')

plt.xlim([0, 110])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Add a random shift to each catheter, see the effect it has on target DVH.
Can you write Python code for it?

relevant_dwell_distances = np.ravel(dwell_distances)[is_dwell_closest_to_target]
shift_uncertainty = 0.05

line_displacement = np.random.normal(scale=shift_uncertainty, size=number_of_lines)

shifted_dwell_positions = np.array([
    find_distance_coords(
        distance=relevant_dwell_distances[i] + line_displacement[line_number_index[i]],
        line_num=line_number_index[i])
    for i in range(len(relevant_dwell_distances))
])

shifted_calculate_exposure = create_calculate_exposure(
    shifted_dwell_positions, x_new=post_x_, y_new=post_y_, z_new=post_z_)

shifted_exposure = shifted_calculate_exposure(dwell_times)


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Analysis of results
Create analysis grid
Can you write Python code for it?

dx = 0.02
dy = 0.02
dz = 0.02

post_x_ = np.arange(np.min(x_), np.max(x_) + dx, dx)
post_y_ = np.arange(np.min(y_), np.max(y_) + dy, dy)
post_z_ = np.arange(np.min(z_), np.max(z_) + dz, dz)

post_x, post_y, post_z = np.meshgrid(
    post_x_, post_y_, post_z_)
post_x = np.ravel(post_x)
post_y = np.ravel(post_y)
post_z = np.ravel(post_z)

post_calculate_exposure = create_calculate_exposure(
    relevant_dwell_positions, x_new=post_x_, y_new=post_y_, z_new=post_z_)

post_exposure = post_calculate_exposure(dwell_times)


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Convert result into column vector for post analysis
Can you write Python code for it?

dwell_times = np.reshape(optimisation.result, (1, num_relevant_dwells))


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create a custom resolution exposure calculation function for post analysis
Can you write Python code for it?

def create_calculate_exposure(dwell_positions,
                              x_new=None, y_new=None, z_new=None):
    x, y, z = np.meshgrid(
        x_new, y_new, z_new)
    x = np.ravel(x)
    y = np.ravel(y)
    z = np.ravel(z)

    distance_to_dwell_pos = np.array([
        np.sqrt(
            (x[i] - dwell_positions[:,0])**2 +
            (y[i] - dwell_positions[:,1])**2 +
            (z[i] - dwell_positions[:,2])**2
        )
        for i in range(len(x))
    ])

    exposure_per_unit_time = 1 / distance_to_dwell_pos**2

    def calculate_exposure(dwell_times, reshape=False):
        exposure = np.sum(dwell_times * exposure_per_unit_time, axis=1)
        if reshape:
            exposure = np.reshape(exposure, (
                len(x_new), len(y_new), len(z_new)))
        return exposure

    return calculate_exposure

dx = 0.01; dy = 0.01

contour_x_ = np.arange(np.min(x_), np.max(x_) + dx, dx)
contout_y_ = np.arange(np.min(y_), np.max(y_) + dy, dy)
contout_z_ = z_

contour_calculate_exposure = create_calculate_exposure(
    relevant_dwell_positions, x_new=contour_x_, y_new=contout_y_, z_new=contout_z_)

contour_exposure = contour_calculate_exposure(dwell_times, reshape=True)
contour_exposure[contour_exposure > 250] = 250

for i, z_value in enumerate(z_):
    plt.figure(figsize=(6,6))

    c = plt.contourf(contour_x_, contout_y_,
        contour_exposure[:, :, i], 250,
        vmin=0, vmax=100, cmap=green_cm)

    reference = z[target_cube] == z_value
    x_target = x[target_cube][reference]
    y_target = y[target_cube][reference]
    plt.scatter(x_target, y_target, alpha=0.3, color='blue')

    reference = z[avoid_cube] == z_value
    x_avoid = x[avoid_cube][reference]
    y_avoid = y[avoid_cube][reference]
    plt.scatter(x_avoid, y_avoid, alpha=0.3, color='red')

    plt.title("Slice z = %0.1f" % (z_value))
#     plt.colorbar(c)
    plt.xlim([np.min(x_), np.max(x_)])
    plt.ylim([np.min(y_), np.max(y_)])
    plt.show()


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create a function to return x, y, z coords when a distance along a line is requested
Can you write Python code for it?

diff = (line_finish - line_start)
line_length = np.sqrt(diff[0]**2 + diff[1]**2 + diff[2]**2)

def find_distance_coords(line_num=None, distance=None):
    relative_dist = distance / line_length[line_num]

    if (relative_dist > 1) | (relative_dist < 0):
        return np.array([np.nan]*3)

    x = (
        line_start[0][line_num] * (1 - relative_dist) +
        line_finish[0][line_num] * relative_dist)

    y = (
        line_start[1][line_num] * (1 - relative_dist) +
        line_finish[1][line_num] * relative_dist)

    z = (
        line_start[2][line_num] * (1 - relative_dist) +
        line_finish[2][line_num] * relative_dist)

    coords = np.array([x, y, z])

    return coords


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create function to display the results of the optimisation as it is being calculated.
Can you write Python code for it?

def display_results(dwell_times):
    dwell_times = np.reshape(dwell_times, (1, num_relevant_dwells))
    exposure = calculate_exposure(dwell_times)

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    reference = exposure > 25
    colour = exposure[reference]
    colour[colour > 100] = 100

    small = exposure[reference] < 50
    large = ~small

    ax.scatter(
        x[reference][small], y[reference][small], z[reference][small],
        alpha=0.2, s=3, c=colour[small], cmap=green_cm)

    ax.scatter(
        x[reference][large], y[reference][large], z[reference][large],
        alpha=0.4, s=20, c=colour[large], cmap=green_cm)

    ax.set_xlim([np.min(x_), np.max(x_)])
    ax.set_ylim([np.min(y_), np.max(y_)])
    ax.set_zlim([np.min(z_), np.max(z_)])

    cost_function(dwell_times, debug=True)

    plt.show()


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create initial conditions
Can you write Python code for it?

num_relevant_dwells

initial_conditions = np.ones(num_relevant_dwells)*0.1


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create initial equidistant parrallel lines to represent catheters. Inbuild a slight random skew to emulate what occurs physically
Can you write Python code for it?

number_of_lines = 16 # Was 16, reduced to 9 for testing

line_start = np.meshgrid(
    [-0.39, -0.13, 0.13, 0.39],
    [-0.39, -0.13, 0.13, 0.39],
    [1])

line_finish = np.array([
    line_start[0] + np.random.normal(scale=0.02, size=[4, 4, 1]),
    line_start[1] + np.random.normal(scale=0.02, size=[4, 4, 1]),
    -line_start[2]])

line_start = np.array([np.ravel(mesh) for mesh in line_start])
line_finish = np.array([np.ravel(mesh) for mesh in line_finish])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Create the cost function to be used by the optimiser
Can you write Python code for it?

def cost_function(dwell_times, debug=False):
    dwell_times = np.reshape(dwell_times, (1, num_relevant_dwells))
    exposure = calculate_exposure(dwell_times)

    min_target = np.min(exposure[target_cube])
    max_avoid = np.max(exposure[avoid_cube])
    max_target_exterior = np.max(exposure[~target_cube])

    cold_target_cost = cold_target_cost_function(min_target)
    hot_exterior_cost = hot_exterior_cost_function(max_target_exterior)
    hot_avoid_cost = hot_avoid_cost_function(max_avoid)

    total_cost = hot_exterior_cost + cold_target_cost + hot_avoid_cost

    if debug:
        print("Minimum target = %0.4f, resulting cost = %0.4f" %
              (min_target, cold_target_cost))
        print("Maximum exterior = %0.4f, resulting cost = %0.4f" %
              (max_target_exterior, hot_exterior_cost))
        print("Maximum avoid = %0.4f, resulting cost = %0.4f" %
              (max_avoid, hot_avoid_cost))
        print("Total cost = %0.4f" % (total_cost))

    return total_cost


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Define structures on new finer grid
Can you write Python code for it?

post_target_cube = target(post_x, post_y, post_z)
post_avoid_cube = avoid(post_x, post_y, post_z)


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Define the target and avoid cubes
Can you write Python code for it?


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Display the lines overlayed
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(
    x[target_cube], y[target_cube], z[target_cube],
    alpha=0.2, s=2, color='blue')
ax.scatter(
    x[avoid_cube], y[avoid_cube], z[avoid_cube],
    alpha=0.2, s=2, color='red')
ax.scatter(*line_start)
ax.scatter(*line_finish)

for i in range(len(line_start[0])):
    plt_coords = [
        [line_start[j][i], line_finish[j][i]]
        for j in range(len(line_start))]
    ax.plot(*plt_coords, color='black', alpha=0.5)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Find all the dwell positions that are on the grid
Can you write Python code for it?

dwell_positions = np.array([
    [
        find_dwell_coords(
            line_num=line_num, dwell_num=dwell_num)
        for dwell_num in range(number_of_dwells)]
 for line_num in range(number_of_lines)])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
No grid point within the target is to be less than about 50. This cost function aims to achieve this.
Can you write Python code for it?

def cold_target_cost_function(min_target):
    return ((min_target-80)/15)**4

testx = np.linspace(0, 120)
testy = cold_target_cost_function(testx)
plt.plot(testx, testy)

plt.ylim([0, 20])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Pick dwell positons starting at a random position along the line
Can you write Python code for it?

dwell_spacing = 0.1 # Was 0.1, increased to 0.3 for testing
dwell_distances_from_initial = np.arange(0, 2, dwell_spacing)
number_of_dwells = len(dwell_distances_from_initial)

inital_dwell_position = np.random.uniform(
    low=0, high=dwell_spacing, size=number_of_lines)
inital_dwell_position

dwell_distances = np.reshape(inital_dwell_position, (-1, 1)) + np.reshape(dwell_distances_from_initial, (1, -1))

def find_dwell_coords(line_num=None, dwell_num=None):
    distance = dwell_distances[line_num, dwell_num]

    coords = find_distance_coords(
        line_num=line_num, distance=distance)

    return coords


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Plot the dwell positions
Can you write Python code for it?

line_colours = np.random.uniform(size=(number_of_lines,3))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(
    x[target_cube], y[target_cube], z[target_cube],
    alpha=0.2, s=2, color='blue')
ax.scatter(
    x[avoid_cube], y[avoid_cube], z[avoid_cube],
    alpha=0.2, s=2, color='red')

for line_num in range(number_of_lines):
    ax.scatter(*np.transpose(dwell_positions[line_num]),
               c=line_colours[line_num], alpha=0.7)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Plotting of relevant DVHs
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_target_cube, post_exposure, ax=ax)
create_dvh(post_avoid_cube, post_exposure, ax=ax)
create_dvh(~post_target_cube, post_exposure, ax=ax)

plt.legend(["Target", "Avoid", "Patient"])

plt.xlim([0, 150])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Presentation of results
Can you write Python code for it?


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Run a test of arbitrary dwell times
Can you write Python code for it?

num_relevant_dwells = len(relevant_dwell_positions)

random_pick = np.random.uniform(
    size=2, high=num_relevant_dwells, low=0).astype(int)

dwell_times = np.zeros([1, num_relevant_dwells])
dwell_times[0, random_pick] = 10

exposure = calculate_exposure(dwell_times)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

reference = exposure > 80
colour = exposure[reference]
colour[colour > 200] = 200

ax.scatter(
    x[reference], y[reference], z[reference],
    alpha=0.2, s=1, c=colour, cmap=cm.jet)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Run the optimiser
Can you write Python code for it?

optimisation = BasinhoppingWrapper(
    to_minimise=cost_function,
    initial=initial_conditions,
    step_noise=step_noise,
    basinhopping_confidence=2,
    optimiser_confidence=0.0001,
    n=5,
    debug=display_results,
    bounds=bounds
)


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Select the dwell positions that fall withing the target region. Only use these dwell positions.
Can you write Python code for it?

dwell_positions_to_be_filtered = np.reshape(dwell_positions, (-1, 3))

distance_to_dwell_pos_initial = np.array([
    np.sqrt(
        (x[i] - dwell_positions_to_be_filtered[:,0])**2 +
        (y[i] - dwell_positions_to_be_filtered[:,1])**2 +
        (z[i] - dwell_positions_to_be_filtered[:,2])**2
    )
    for i in range(len(x))
])

closest_voxel_to_dwell = np.reshape(np.argmin(distance_to_dwell_pos_initial, axis=0), [1, -1])
target_cube_voxels = np.reshape(np.where(target_cube)[0], [-1, 1])
is_dwell_closest_to_target = np.any(closest_voxel_to_dwell == target_cube_voxels, axis=0)

relevant_dwell_positions = dwell_positions_to_be_filtered[is_dwell_closest_to_target]

line_number_index = np.reshape(np.arange(number_of_lines), (number_of_lines, 1))
line_number_index = np.ones([number_of_lines, number_of_dwells]) * line_number_index
line_number_index = np.ravel(line_number_index)[is_dwell_closest_to_target]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(
    x[target_cube], y[target_cube], z[target_cube],
    alpha=0.2, s=2, color='blue')

ax.scatter(
    x[avoid_cube], y[avoid_cube], z[avoid_cube],
    alpha=0.2, s=2, color='red')

for line_num in range(number_of_lines):
    ref = line_number_index == line_num
    ax.scatter(*np.transpose(relevant_dwell_positions[ref]),
               c=line_colours[line_num], alpha=0.7)

ax.set_xlim([np.min(x_), np.max(x_)])
ax.set_ylim([np.min(y_), np.max(y_)])
ax.set_zlim([np.min(z_), np.max(z_)])


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
Step noise
Can you write Python code for it?

step_noise = np.ones(num_relevant_dwells) * 0.3


I am working on the file "Proof of concept with probability minimisation.ipynb".
The first task is:
With the shift the change in the DVH is the following. For the optimisation given here there is very little change in DVH.
Can you write Python code for it?

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_target_cube, post_exposure, ax=ax)
create_dvh(post_target_cube, shifted_exposure, ax=ax)

plt.legend(["Original", "With position error"], loc='lower left')

plt.xlim([0, 110])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

create_dvh(post_avoid_cube, post_exposure, ax=ax)
create_dvh(post_avoid_cube, shifted_exposure, ax=ax)

plt.legend(["Original", "With position error"], loc='upper right')

plt.xlim([0, 110])


I am working on the file "Propagation_of_uncertainty/Examples-pymc3.ipynb".
The first task is:
Example 2
Example: a bird flies a distance d = 120 ± 3 m during a time t = 20.0 ± 1.2 s. The average speed of
the bird is v = d/t = 6 m/s. What is the uncertainty of v?
0.39 m/s.
Can you write Python code for it?

with pm.Model() as model:
    d = pm.Normal('d', 123, tau=(3)**-2)
    t = pm.Normal('t', 20.0, tau=(1.2)**-2)
    v = pm.Deterministic('v', d/t)
    trace = pm.sample(40000, chains=4)

with model:
    print(pm.summary(trace).round(3))

with model:
    pm.traceplot(trace, combined=False, lines=[('d', {}, 123), ('t', {}, 20), ('v', {}, 6)])
    print("MCMC gives {0:.2f}, analytic gives {1}".format(trace['v'].std(), 0.39))


I am working on the file "Propagation_of_uncertainty/Examples-pymc3.ipynb".
The first task is:
Example 3
Example: the period of an oscillation is measured to be T = 0.20 ± 0.01 s. Thus the frequency is
f = 1/T = 5 Hz. What is the uncertainty in f? Answer: the percent uncertainty in T was 0.01/0.20 = 5%.
Thus the percent uncertainty in f is also 5%, which means that δf = 0.25 Hz. So f = 5.0 ± 0.3 Hz (after
rounding).
f = 5.0 ± 0.3 Hz
Can you write Python code for it?

with pm.Model() as model:
    T = pm.Normal('T', 0.20, tau=(0.01)**-2)

    pm.Deterministic('1/T', 1/T)

    trace = pm.sample(10000, tune=1000)

pm.traceplot(trace, combined=False)

pm.summary(trace).round(3)

print("MCMC gives {0:.1f} +/- {1:.1f}, analytic gives {2} +/- {3}".format(np.mean(trace['1/T']),
                                                                          np.std(trace['1/T']),
                                                                          5.0, 0.3))


I am working on the file "Propagation_of_uncertainty/Examples-pymc3.ipynb".
The first task is:
Example 4
Example: a ball is tossed straight up into the air with initial speed v0 = 4.0 ± 0.2 m/s. After a time
t = 0.60±0.06 s, the height of the ball is y = v0t−
1
2
gt2 = 0.636 m. What is the uncertainty of y? Assume
g = 9.80 m/s2
(no uncertainty in g).
Thus y would be properly reported as 0.6 ± 0.4 m.
Can you write Python code for it?

with pm.Model() as model:
    g = 9.80
    t = pm.Normal('t', 0.60, tau=(0.06)**-2)
    v0 = pm.Normal('v0', 4.0, tau=(0.2)**-2)

    h = pm.Deterministic('h', v0*t - 0.5*g*t**2)

    trace = pm.sample(10000)

pm.traceplot(trace, combined=False)

pm.summary(trace).round(3)

print("MCMC gives {0:.1f} +/- {1:.1f}, analytic gives {2} +/- {3}".format(np.mean(trace['h']),
                                                                          np.std(trace['h']),
                                                                          0.6, 0.4))


I am working on the file "Propagation_of_uncertainty/Examples-pymc3.ipynb".
The first task is:
This version uses prior distributions to do all the work. H and h are both informative priors that then drive the solution to the right answer.
Can you write Python code for it?

with pm.Model() as model:

    H = pm.Normal('H', 2.00, sigma=0.03)
    h = pm.Normal('h', 0.88, sigma=0.04)
    Q = pm.Deterministic('Q', H-h)
    trace = pm.sample(10000)

with model:
    print(pm.summary(trace).round(3))

with model:
    pm.traceplot(trace, combined=False)
    print("MCMC gives {:.2f} +/- {:.2f}, analytic gives {} +/- {}".format(trace['Q'].mean(),
                                                                          trace['Q'].std(), 1.12, 0.05))

with model:
    pm.plot_posterior(trace)


I am working on the file "Propagation_of_uncertainty/Examples.ipynb".
The first task is:
Example 2
Example: a bird flies a distance d = 120 ± 3 m during a time t = 20.0 ± 1.2 s. The average speed of
the bird is v = d/t = 6 m/s. What is the uncertainty of v?
0.39 m/s.
Can you write Python code for it?

d = mc.Normal('d', 123, (3)**-2)
t = mc.Normal('t', 20.0, (1.2)**-2)

@mc.deterministic()
def v(d=d, t=t):
    return d/t

model = mc.MCMC((d, t, v))

model.sample(1e5, burn=1000, burn_till_tuned=True)
print(v.summary())
print("MCMC gives {0:.2f}, analytic gives {1}".format(np.std(v.trace()), 0.39))


I am working on the file "Propagation_of_uncertainty/Examples.ipynb".
The first task is:
Example 3
Example: the period of an oscillation is measured to be T = 0.20 ± 0.01 s. Thus the frequency is
f = 1/T = 5 Hz. What is the uncertainty in f? Answer: the percent uncertainty in T was 0.01/0.20 = 5%.
Thus the percent uncertainty in f is also 5%, which means that δf = 0.25 Hz. So f = 5.0 ± 0.3 Hz (after
rounding).
f = 5.0 ± 0.3 Hz
Can you write Python code for it?

T = mc.Normal('T', 0.20, (0.01)**-2)

@mc.deterministic()
def f(T=T):
    return 1/T

model = mc.MCMC((T, f))

model.sample(1e4, burn=100, burn_till_tuned=True)

print(f.summary())
print("MCMC gives {0:.1f} +/- {1:.1f}, analytic gives {2} +/- {3}".format(np.mean(f.trace()), np.std(f.trace()),
                                                                          5.0, 0.3))


I am working on the file "Propagation_of_uncertainty/Examples.ipynb".
The first task is:
Example 4
Example: a ball is tossed straight up into the air with initial speed v0 = 4.0 ± 0.2 m/s. After a time
t = 0.60±0.06 s, the height of the ball is y = v0t−
1
2
gt2 = 0.636 m. What is the uncertainty of y? Assume
g = 9.80 m/s2
(no uncertainty in g).
Thus y would be properly reported as 0.6 ± 0.4 m.
Can you write Python code for it?

g = 9.80
t = mc.Normal('t', 0.60, (0.06)**-2)
v0 = mc.Normal('v0', 4.0, (0.2)**-2)

@mc.deterministic()
def h(t=t, v0=v0):
    return v0*t - 0.5*g*t**2

model = mc.MCMC((t, v0, h))

model.sample(1e5, burn=100, burn_till_tuned=True)

print(h.summary())
print("MCMC gives {0:.1f} +/- {1:.1f}, analytic gives {2} +/- {3}".format(np.mean(h.trace()), np.std(h.trace()),
                                                                          0.6, 0.4))


I am working on the file "Propagation_of_uncertainty/Examples.ipynb".
The first task is:
Example 5
For example, suppose Ann and Billy both measure the speed of a moving ball. Ann measures 3.6±0.2 m/s
and Billy gets 3.3 ± 0.3 m/s. Do the two measurements agree?
D = 0.3 ± 0.4 m/s  so 0 is in the range, they do agree.
Can you write Python code for it?

A = mc.Normal('A', 3.6, (0.2)**-2)
B = mc.Normal('B', 3.3, (0.3)**-2)

@mc.deterministic()
def D(A=A, B=B):
    return A-B

model = mc.MCMC((A, B, D))

model.sample(1e5, burn=100, burn_till_tuned=True)

print(D.summary())
print("MCMC gives {0:.1f} +/- {1:.1f}, analytic gives {2} +/- {3}".format(np.mean(D.trace()), np.std(D.trace()),
                                                                          0.3, 0.4))
# mc.Matplot.plot(model)

# https://www.lhup.edu/~dsimanek/scenario/errorman/propagat.htm


I am working on the file "Propagation_of_uncertainty/Examples.ipynb".
The first task is:
Example 6
Example: An angle is measured to be 30° ±0.5°. What is the error in the sine of this angle?
Solution: Use your electronic calculator. The sine of 30° is 0.5; the sine of 30.5° is 0.508; the sine of 29.5° is 0.492. So if the angle is one half degree too large the sine becomes 0.008 larger, and if it were half a degree too small the sine becomes 0.008 smaller. (The change happens to be nearly the same size in both cases.) So the error in the sine would be written ±0.008.
The size of the error in trigonometric functions depends not only on the size of the error in the angle, but also on the size of the angle. A one half degree error in an angle of 90° would give an error of only 0.00004 in the sine.
Can you write Python code for it?

a = mc.Normal('a', 30.00, (0.5)**-2)

@mc.deterministic()
def sina(a=a):
    return np.sin(np.deg2rad(a))

model = mc.MCMC((a, sina))

model.sample(1e5, burn=5000, burn_till_tuned=False)
# mc.Matplot.plot(model)
# mc.Matplot.plot(Q)
print(sina.summary())
print("MCMC gives {0:.3f} +/- {1:.3f}, analytic gives {2} +/- {3}".format(np.mean(sina.trace()), np.std(sina.trace()), 0.5, 0.008))

for i in range(4):
    model.sample(1e5, burn=5000, burn_till_tuned=False)

mc.Matplot.summary_plot(sina)


I am working on the file "Propagation_of_uncertainty/Sullivan1971_GF.ipynb".
The first task is:
Just thickness
Stack up five colimator discs to compute G
Can you write Python code for it?

Sullivan(4, 5, 10)

R1 = 0.5
R2 = 0.5
l = np.linspace(2, 20, 100)
fig, ax = plt.subplots(ncols=2, figsize=(8,4))
ax[0].plot(l, Sullivan(R1, R2, l), lw=2)
ax[0].set_xlabel('Distance between [$cm$]')
ax[0].set_ylabel('GF [$cm^2sr$]');

ax[1].loglog(l, Sullivan(R1, R2, l), lw=2)
ax[1].set_xlabel('Distance between [$cm$]');

ax[0].grid(True, which='both')
ax[1.grid(True, which='both')

with pm.Model() as model1:
    T1 = pm.Normal('T1', 1.0, 0.1e-2)  # 1cm +/- 0.1mm
    T2 = pm.Normal('T2', 1.0, 0.1e-2)  # 1cm +/- 0.1mm
    T3 = pm.Normal('T3', 1.0, 0.1e-2)  # 1cm +/- 0.1mm
    T4 = pm.Normal('T4', 1.0, 0.1e-2)  # 1cm +/- 0.1mm
    T5 = pm.Normal('T5', 1.0, 0.1e-2)  # 1cm +/- 0.1mm
    R1 = 0.5
    R2 = 0.5
    R3 = 0.5
    G = pm.Deterministic('G', Sullivan(R1, R3, T1+T2+T3+T4+T5))
    Gbound = pm.Deterministic('Gbound', Sullivan_Bound(R1, R3, T1+T2+T3+T4+T5))
    trace = pm.sample(1000, chains=4, target_accept=0.9)

pm.summary(trace).round(3)

pm.traceplot(trace, combined=False);

gf = frac_bounds(trace['G'])
gbf = frac_bounds(trace['Gbound'])
print("G={:.5f} +/- {:.2f}%".format(gf[0], gf[1]))
print("Gbound={:.5f} +/- {:.2f}%".format(gbf[0], gbf[1]))


I am working on the file "PropertiesofStars.ipynb".
The first task is:
Choose a Constellation from the list above and insert the 3 letter code below in the " ", for example "Vir".
Can you write Python code for it?

# This shows just one constellation
data_con = data.query('con == "Vir"')

# This plots where the brightest 10 stars are in the sky
data_con = data_con.sort_values('mag').head(10)
plt.scatter(data_con.ra,data_con.dec)
plt.gca().invert_xaxis()
plt.title("A constellation in the sky")
plt.xlabel('Right Ascension (degrees)')
plt.ylabel('Declination (Hours)')


I am working on the file "PropertiesofStars.ipynb".
The first task is:
Links for Question #9
Can we see your constellation now?
Which types of stars make up your constellation?
Can you write Python code for it?

# format the points on the graph
transparency = 0.2
size = 1

# draws a scatter plot
fig = plt.figure(figsize=(6, 4.5))
plt.scatter(data.temp, data.absmag, s=size, edgecolors='none', alpha=transparency)
plt.scatter(data_con.temp, data_con.absmag, color='red', edgecolors='none')
plt.xlim(17000,2000)
plt.ylim(18,-18)
plt.title("Types of stars in a constellation")
plt.ylabel("Absolute Magnitude")
plt.xlabel("Temperature (K)")


I am working on the file "PropertiesofStars.ipynb".
The first task is:
PART 2: Relationships Between Two Properties
Can you write Python code for it?

# format the points on the graph
transparency = 1
size = 1

# draws a scatter plot
fig = plt.figure(figsize=(20, 4.5))
plt.scatter(data.temp, data.lum, s=size, edgecolors='none', alpha=transparency)
plt.xlim(2000,15000)
plt.ylim(0,1000)
plt.title("Does hotter mean brighter?")
plt.ylabel("Luminosity")
plt.xlabel("Temperature (K)")

Image(url= 'http://hmxearthscience.com/Galaxies%20and%20Stars/HR%20Lab%202.jpg')


I am working on the file "PropertiesofStars.ipynb".
The first task is:
PART 3: Constellations and Star Properties
Can you write Python code for it?

# These are the abbreviations for all the constellations
data.sort_values('con').con.unique()


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
And output would be:
Can you write Python code for it?


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Apparently using $XOR$ can save a lot of space!
Validate
ValidateInput method is used to validate given clause in string format. It can be used to roughly check that parentheses and literals are correctly formed. Then it is safer to use parseInput and evaluateInput functions.
Can you write Python code for it?

from pyPLCParser import validateInput

# input has extra )
print (validateInput('(A or B))'))
# input should be ok
print (validateInput('(A or B)'))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
But say, you have a more complex nested clause in your hands, what is the outcome?
Can you write Python code for it?

i = "(A or (B and (!C and (D xor E))))"
parseInput(i)


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Deformat
Of cource it is good to have a method to deformat native list structure back to the string clause representation.
With an optional argument, one can use special character abbreviations for logic operators. By default formal keywords are used on output. Operator representation types are: word, char and math:
Can you write Python code for it?

from pyPLCParser import PLCParser
c = PLCParser()
# set input (A and B)
i = ['A', -2, 'B']
print(c.deformat(i, operator_type="word"))
print(c.deformat(i, operator_type="char"))
print(c.deformat(i, operator_type="math"))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Evaluate
EvaluateInput function takes propositional logic clause in string or array format and evaluates it. Usually, if everything is correct on input, output is either true or false.
Can you write Python code for it?

from pyPLCParser import evaluateInput

i = "(1 or 0)"
o = evaluateInput(i)
print("%s => %s" % (i, o))

i = "(1 and 0)"
o = evaluateInput(i)
print("%s => %s" % (i, o))

i = "(true and false)"
o = evaluateInput(i)
print("%s => %s" % (i, o))

i = "(p and q)"
truth_table = {'p': True, 'q': False}
o = evaluateInput(i, truth_table)
print("%s => %s" % (i, o))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
From the output (['1', -2, '2']) we can notice that negative number -2 is used to mark $AND$ operator. You could also input: (1 & 2) or (1 ∧ 2) to get the same result. $AND$ keyword is case insensitive so use what ever format you like: AnD, and, anD, and so forth.
For an operator you can use either $AND, OR, NOT, XOR$ keywords or single ascii characters on the clause:  $\&$, $|$, $\!$, ^ respectively. These corresponding mathematical symbols are also accepted: $∧$, $∨$, $¬$, $⊕$.
Negative logical gate symbols are also supported: $NAND$ ($/$, $↑$), $XNOR$ ($=$, $↔$) and $NOR$ ($†$, $↓$). It is recommended that you use either word or mathematical symbols, because conventions of the character codes are different on the different programming systems.
Can you write Python code for it?

# use | for OR and ⊕ for XOR
print(parseInput("(1 | 0)"), parseInput("(1 ⊕ 0)"))
# use NAND
print(parseInput("(1 ↑ 0)"))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Javascript version
Same applies to Javascript library. You need to include library first and then you can use same API methods (validateInput, parseInput, EvaluateInput, deformatInput) or build object fromthe  PLCParser "class" for more specific usage:
Can you write Python code for it?

%%html

<script src="./dist/PLCParser.min.js"></script>

<script>

var v = PLCParser.validateInput("(A and B (C | D) !F)")

console.log(v)

var p = PLCParser.parseInput("(A and B (C | D) !F)")

console.log(p)

var e = PLCParser.evaluateInput("(true or false)")

console.log(e)

var d = PLCParser.deformatInput([-1, ['A', 'B']])

console.log(d)

</script>


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Like you can see, the nesting of the lists is done a bit different on these two case.
Literals
In above examples only single letters and numbers were used. That is ok as long as they are not reserved keywords or the chosen parentheses and literal wrapper characters. To use sentences that contain spaces and special characters it is safer to make it this way:
Can you write Python code for it?

i = "('Queen Elizabeth' & 'Philip, Duke of Edinburgh')"
parseInput(i)


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Negation
Using negation ($NOT$ , $!$ , $¬$) keywords do shape the structure of the output. $NOT$ will add $-1$ value to the result before the item or node.
As a unary operator, negation can be done for the item or to the group of items:
Can you write Python code for it?

parseInput("""

(!A and !(B or C))

""")


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
PHP version
PHP version of the PLCParser class is practically same as Python having the same API methods and functionality. For example parseInput is called something like this:
Can you write Python code for it?

%%html

require_once('./src/elonmedia/plcparser/php/PLCParser.php')
print_r(PLCParser::parseInput("('A' or 'B')"));


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
PLCParser tries to deformalize and interpret the boolean operator precedence. But sometimes it is better that you decide and choose correctly the format of the nested set / parentheses to get the right result. Order of the precedence differs by authors anyway. In PLCParser this order is used: $NOT$, $AND$, $XOR$, $OR$.
Without parentheses similar input would be interpreted like this:
Can you write Python code for it?

from pyPLCParser import deformatInput
i = "A or B and !C and D or E"
deformatInput(parseInput(i))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
Precedence
In case one needs to adjust the order of the precedence of the operators, it can be done via special argument. In that case you need to import all operator variables and use them to set the order:
Can you write Python code for it?

from pyPLCParser import PLCParser, NOT_OPERATOR, AND_OPERATOR, XOR_OPERATOR, \
                        OR_OPERATOR, NAND_OPERATOR, XNOR_OPERATOR, NOR_OPERATOR

# input without nested parentheses
i = "(1 and 0 nand 1 or 1 nor 0)"
# init object
c = PLCParser()
# output default nesting
print(c.parse(i))

# set up your own operator predecence. note that usually not operator is the last
# while the least weight operators are given first.
operator_precedence = (OR_OPERATOR, NOR_OPERATOR, XOR_OPERATOR, XNOR_OPERATOR,
                       AND_OPERATOR, NAND_OPERATOR, NOT_OPERATOR)
# use argument
c = PLCParser(operator_precedence=operator_precedence)
# output new nested set
print(c.parse(i))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
The last example uses truth table to define, how different operands should be interpreted. By default only numbers 1 and 0, and booleans true and false, can be interpreted accordingly.
Last example demonstrates $NAND$, $XNOR$ and $NOR$ operators:
Can you write Python code for it?

i = "(1 nand 1)"
o = evaluateInput(i)
print("%s => %s" % (i, o))

i = "(1 xnor 0)"
o = evaluateInput(i)
print("%s => %s" % (i, o))

i = "(1 nor 0)"
o = evaluateInput(i)
print("%s => %s" % (i, o))


I am working on the file "Propositional Logic Clause Parser (PLCParser).ipynb".
The first task is:
XOR operator
This brings us to the $XOR$ operator. $XOR$ is an exclusive or, which states that either A or B should exist, but not both at the same time. Same behaviour could be achieved by $OR$, $AND$, and $NOT$ clause groups. Let us demonstrate it by few examples:
Can you write Python code for it?

# xor logic -> one of the group, but not all
i1 = '(A ^ B)' # or just (^(A B))
o1 = parseInput(i1)
print(o1)

# xor logic with and, or, and not operators #1
i2 = '((A or B) and !(A and B))'
o2 = parseInput(i2)
print(o2)

# xor logic with and, or, and not operators #2
i3 = '((A and !B) or (!A and B))'
o3 = parseInput(i3)
print(o3)

# xor logic with and, or, and not operators #3
i4 = '((A or !B) and (!A or B))'
o4 = parseInput(i4)
print(o4)


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Alrighty - we're now ready to try out a neural network! For this try, we will use lasagne and nolearn, two packages which have made things pretty easy for building neural networks. In this segment, I'm going to not show experiments with multiple architectures, activations and the like. The goal is to illustrate how easy the specification of a neural network is.
First off, these are the import statements necessary for constructing and testing a neural network.
Can you write Python code for it?

from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
import theano
theano.config.blas.ldflags = '' # optional. Blas was giving me an error.


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Alrighty, let's add some frills - the class labels, the probability of each class label, and the original class label.
Can you write Python code for it?

### NOTE: Change the value of i to anything above!
i = 5942
plt.figure(figsize=(20,5))
plt.bar(np.arange(len(output_lb.classes_)), preds[i])
plt.xticks(np.arange(len(output_lb.classes_)) + 0.5, output_lb.classes_, rotation='vertical')
plt.title('Original Label: ' + output_lb.inverse_transform(Y_test)[i])
plt.show()
# print(output_lb.inverse_transform(Y_test)[i])


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
As a demonstration of how this model can be used, let's look at the ambiguously labeled sequences, i.e. those from "Environment" and "Avian", to see whether we can make a prediction as to what host it likely came frome.
Can you write Python code for it?

unknown_hosts = unknowns.ix[:,:-1].values

preds = rf.predict(unknown_hosts)
output_lb.inverse_transform(preds)


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
By the majority-consensus rule, and using mutual information as the metric for scoring, things look not so bad! As mentioned above, the RandomForestClassifier is a pretty powerful method for finding non-linear patterns between features and class labels.
Uncomment the cell below if you want to try the scikit-learn's ExtraTreesClassifier.
Can you write Python code for it?

# et = ExtraTreesClassifier()
# et.fit(X_train, Y_train)
# predictions = et.predict(X_test)
# predicted_labels = output_lb.inverse_transform(predictions)
# mi(predicted_labels, output_lb.inverse_transform(Y_test))


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Let's do a majority-consensus rule applied to the labels, and then compute the mutual information score again.
Can you write Python code for it?

preds_labels = []
for i in range(preds.shape[0]):
    maxval = max(preds[i])
    pos = list(preds[i]).index(maxval)

    preds_labels.append(output_lb.classes_[pos])

mi(preds_labels, output_lb.inverse_transform(Y_test))


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Let's grab out the predictions!
Can you write Python code for it?

preds = net1.predict(X_test)
preds.shape


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Next up, we do the train/test split.
Can you write Python code for it?

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=42)


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Read in the viral sequences.
Can you write Python code for it?

sequences = SeqIO.to_dict(SeqIO.parse('20150902_nnet_ha.fasta', 'fasta'))
# sequences


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
The first piece of meat in the code begins here. In the cell below, we convert the sequence matrix into a series of binary 1s and 0s, to encode the features as numbers. This is important - AFAIK, almost all machine learning algorithms require numerical inputs.
Can you write Python code for it?

# Create an empty dataframe.
df = pd.DataFrame()

# Create a dictionary of position + label binarizer objects.
pos_lb = dict()

for pos in range(lengths.most_common(1)[0][0]):
    # Convert position 0 by binarization.
    lb = LabelBinarizer()
    # Fit to the alignment at that position.
    lb.fit(alignment[:,pos])
    # Add the label binarizer to the dictionary.
    pos_lb[pos] = lb
    # Create a dataframe.
    pos = pd.DataFrame(lb.transform(alignment[:,pos]))

    # Append the columns to the dataframe.
    for col in pos.columns:
        maxcol = len(df.columns)
        df[maxcol + 1] = pos[col]

df['host'] = [s.id.split('|')[1] for s in all_sequences.values()]
df

ambiguous_hosts = ['Environment', 'Avian', 'Unknown', 'NA', 'Bird', 'Sea_Mammal', 'Aquatic_Bird']

unknowns = df[df['host'].isin(ambiguous_hosts)]

train_test_df = df[df['host'].isin(ambiguous_hosts) == False]


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
The sequences are going to be of variable length. To avoid the problem of doing multiple sequence alignments, filter to just the most common length (i.e. 566 amino acids).
Can you write Python code for it?

lengths = Counter()
for accession, seqrecord in sequences.items():
    lengths[len(seqrecord.seq)] += 1

lengths.most_common(1)[0][0]


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
Training a simple neural network on my MacBook Air takes quite a bit of time :). But the function call for fitting it is a simple nnet.fit(X, Y).
Can you write Python code for it?


I am working on the file "Prototype Neural Network for predicting HA host tropism.ipynb".
The first task is:
With a score of 0.73, that's not bad either! It certainly didn't outperform the RandomForestClassifier, but the default parameters on the RFC were probably pretty good to begin with. Notice how little tweaking on the neural network we had to do as well.
For good measure, these were the class labels. Notice how successful influenza has been in replicating across the many different species!
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example 2 Simple-checkpoint.ipynb".
The first task is:
Combining potential fields: Depositional series
In reality, most geological settings are formed by a concatenation of depositional phases separated clearly by unconformity bounderies. Each of these phases can be model by a potential field. In order to capture this behavior, we can classify the formations that belong to individual depositional phase into categories or series. The potential field computed for each of these series could be seen as a sort of evolution of the basin if an unconformity did not occur. Finally, sorting the temporal relation between series allow to superpose the corresponding potential field at an specific location.
In the next example, we add a new serie consisting in a layer---'Layer 3'--- Fig X, which generate the potential field of Fig X and subsequently the block Figure X.
Can you write Python code for it?

# Setting extend, grid and compile
# Setting the extent
two_pot = GeMpy_core.GeMpy()
two_pot.import_data([0,10,0,10,0,10])

# Data Generation
layer_1 = np.array([[0.5,4,7], [2,4,6.5], [4,4,7], [5,4,6]])#-np.array([5,5,4]))/8+0.5
layer_2 = np.array([[3,4,5], [6,4,4],[8,4,4], [7,4,3], [1,4,6]])
layer_3 = np.array([[2,4,3], [8,4,2], [9,4,3]])

dip_pos_1 = np.array([7,4,7])#- np.array([5,5,4]))/8+0.5
dip_pos_2 = np.array([2.,4,4])
dip_pos_3 = np.array([1,4,1])

dip_angle_1 = float(15)
dip_angle_2 = float(340)
dip_angle_3 = float(80)

dips_angles = np.asarray([dip_angle_1, dip_angle_2, dip_angle_3], dtype="float64")
layers = np.asarray([layer_1,layer_2, layer_3])
azimuths = np.asarray([90,90, 90], dtype="float64")
polarity = np.asarray([1,1, 1], dtype="float64")

two_pot.Data.Interfaces = pn.DataFrame(data = {"X" :np.hstack((layer_1[:, 0],layer_2[:,0], layer_3[:,0])),
                                               "Y" :np.hstack((layer_1[:, 1],layer_2[:,1], layer_3[:,1])),
                                               "Z" :np.hstack((layer_1[:, 2],layer_2[:,2], layer_3[:,2])),
"formation" : np.hstack((np.tile("Layer 1", len(layer_1)), np.tile("Layer 2", len(layer_2)),
                        np.tile("Layer 3", len(layer_3))))})
two_pot.Data.Foliations =   pn.DataFrame(data = {"X" :np.hstack((dip_pos_1[0], dip_pos_2[0], dip_pos_3[0])),
                                                 "Y" :np.hstack((dip_pos_1[ 1],dip_pos_2[1], dip_pos_3[1])),
                                                 "Z" :np.hstack((dip_pos_1[ 2],dip_pos_2[2], dip_pos_3[2])),
                                         "azimuth" : azimuths,
                                         "dip" : dips_angles,
                                         "polarity" : polarity,
"formation" : ["Layer 1", "Layer 2", 'Layer 3']})

inter_labels =[r'${\bf{x}}_{\alpha \, 0}^1$',
               r'${\bf{x}}_{\alpha \, 1}^1$',
               r'${\bf{x}}_{\alpha \, 2}^1$',
               r'${\bf{x}}_{\alpha \, 3}^1$',
               r'${\bf{x}}_{\alpha \, 0}^2$',
  ...


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example 2 Simple-checkpoint.ipynb".
The first task is:
From potential field to block
The potential field describe the deposition form and direction of a basin. However, in most scenarios the real goal of structural modeling is the segmentation in layers of areas with significant change of properties (e.g. shales and carbonates). Since we need to provide at least one point per interface, we can easily compute the value of the potential field at the intersections between two layers. Therefore, by simple comparison between a concrete value of the potential field and the values of the interfaces it is possible to segment the domain into layers Fig X.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example 2 Simple-checkpoint.ipynb".
The first task is:
Importing dependencies
Can you write Python code for it?

# Importing
import importlib
import theano.tensor as T
import sys, os
sys.path.append("/home/bl3/PycharmProjects/GeMpy/GeMpy")

import pandas as pn

import GeMpy_core
import Visualization
import numpy as np
importlib.reload(GeMpy_core)
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
np.set_printoptions(precision = 4, linewidth= 300, suppress =  True)

import matplotlib.pyplot as plt
from matplotlib import cm

from IPython.display import set_matplotlib_formats
set_matplotlib_formats('pdf', 'png')
plt.rcParams['savefig.dpi'] = 75
plt.rcParams['figure.autolayout'] = False
plt.rcParams['figure.figsize'] = 10, 6
plt.rcParams['axes.labelsize'] = 18
plt.rcParams['axes.titlesize'] = 20
plt.rcParams['font.size'] = 16
plt.rcParams['lines.linewidth'] = 2.0
plt.rcParams['lines.markersize'] = 8
plt.rcParams['legend.fontsize'] = 14

import seaborn as sns

# This sets reasonable defaults for font size for
# a figure that will go in a paper
sns.set_context("paper")

# Set the font to be serif, rather than sans
sns.set(font='Arial')

# Make the background white, and specify the
# specific font family
sns.set_style("white")

import qgrid
qgrid.nbinstall(overwrite=True)  # copies javascript dependencies to your /nbextensions folder

%matplotlib inline


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example 2 Simple-checkpoint.ipynb".
The first task is:
Interactive pandas Dataframe
Using qgrid it is possible to modify the tables in place as following:
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example 2 Simple-checkpoint.ipynb".
The first task is:
Visualize data
Can you write Python code for it?

# Setting extend, grid and compile
# Setting the extent
test = GeMpy_core.GeMpy()
test.import_data([0,10,0,10,0,10])

# =========================
# DATA GENERATION IN PYTHON
# =========================
# Layers coordinates
layer_1 = np.array([[0.5,4,7], [2,4,6.5], [4,4,7], [5,4,6]])#-np.array([5,5,4]))/8+0.5
layer_2 = np.array([[3,4,5], [6,4,4],[8,4,4], [7,4,3], [1,4,6]])
layers = np.asarray([layer_1,layer_2])

# Foliations coordinates
dip_pos_1 = np.array([7,4,7])#- np.array([5,5,4]))/8+0.5
dip_pos_2 = np.array([2.,4,4])

# Dips
dip_angle_1 = float(15)
dip_angle_2 = float(340)
dips_angles = np.asarray([dip_angle_1, dip_angle_2], dtype="float64")

# Azimuths
azimuths = np.asarray([90,90], dtype="float64")

# Polarity
polarity = np.asarray([1,1], dtype="float64")

# Pandas Dataframe with the interfaces data
test.Data.Interfaces = pn.DataFrame(
    data = {"X" :np.append(layer_1[:, 0],layer_2[:,0]),
            "Y" :np.append(layer_1[:, 1],layer_2[:,1]),
            "Z" :np.append(layer_1[:, 2],layer_2[:,2]),
            "formation" : np.append(
               np.tile("Layer 1", len(layer_1)),
               np.tile("Layer 2", len(layer_2)))})

# Pandas Dataframe with the Foliations data
test.Data.Foliations =   pn.DataFrame(
    data = {"X" :np.append(dip_pos_1[0],dip_pos_2[0]),
            "Y" :np.append(dip_pos_1[ 1],dip_pos_2[1]),
            "Z" :np.append(dip_pos_1[ 2],dip_pos_2[2]),
            "azimuth" : azimuths,
            "dip" : dips_angles,
            "polarity" : polarity,
            "formation" : ["Layer 1", "Layer 2"]})

# Creation of the formations (to be deprecated)
test.Data.formations = test.Data.Interfaces["formation"].unique()

# Calculation of the pola gradient from dip azimuth and polarity
test.Data.calculate_gradient()

# Set defautl series
test.Data.set_series()

# Method to be sure all objects get updated
test.update_data()

# The following code is for the visualization of labels of the input data (yet to be implemented)
#...


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
And again after computing the model in the Plot object we can use the method plot_block_section to see a 2D section of the model
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
BIF Series
Can you write Python code for it?

GeMpy.plot_potential_field(geo_data,13, n_pf=1, cmap = "magma",  plot_data = True,
                                        verbose = 5)


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
Below here so far is deprecated
First we make a GeMpy instance with most of the parameters default (except range that is given by the project). Then we also fix the extension and the resolution of the domain we want to interpolate. Finally we compile the function, only needed once every time we open the project (the guys of theano they are working on letting loading compiled files, even though in our case it is not a big deal).
General note. So far the reescaling factor is calculated for all series at the same time. GeoModeller does it individually for every potential field. I have to look better what this parameter exactly means
All input data is stored in pandas dataframes under, self.Data.Interances and self.Data.Foliations:
In case of disconformities, we can define which formation belong to which series using a dictionary. Until python 3.6 is important to specify the order of the series otherwise is random
Now in the data frame we should have the series column too
Next step is the creating of a grid. So far only regular. By default it takes the extent and the resolution given in the import_data method.
Can you write Python code for it?

# Create a class Grid so far just regular grid
#GeMpy.set_grid(geo_data)
#GeMpy.get_grid(geo_data)


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
Now we could visualize the individual potential fields as follow:
Early granite
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
Performance Analysis
One of the advantages of theano is the posibility to create a full profile of the function. This has to be included in at the time of the creation of the function. At the moment it should be active (the downside is larger compilation time and I think also a bit in the computation so be careful if you need a fast call)
CPU
The following profile is with a 2 core laptop. Nothing spectacular.
Looking at the profile we can see that most of time is in pow operation (exponential). This probably is that the extent is huge and we are doing it with too much precision. I am working on it
GPU
Can you write Python code for it?

%%timeit

# Compute the block
GeMpy.compute_block_model(geo_data, [0,1,2], verbose = 0)

geo_data.interpolator._interpolate.profile.summary()


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
Plotting raw data
The object Plot is created automatically as we call the methods above. This object contains some methods to plot the data and the results.
It is possible to plot a 2D projection of the data in a specific direction using the following method. Also is possible to choose the series you want to plot. Additionally all the key arguments of seaborn lmplot can be used.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone-checkpoint.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
And again after computing the model in the Plot object we can use the method plot_block_section to see a 2D section of the model
Can you write Python code for it?

sandstone.Plot.plot_block_section(13, interpolation = 'nearest',  direction='y')
plt.savefig("sandstone_example.png")


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
BIF Series
Can you write Python code for it?

sandstone.Plot.plot_potential_field(13, n_pf=1, cmap = "magma",  plot_data = True,
                                        verbose = 5 )


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Class Interpolator
This class will take the data from the class Data and calculate potential fields and block. We can pass as key arguments all the variables of the interpolation. I recommend not to touch them if you do not know what are you doing. The default values should be good enough. Also the first time we execute the method, we will compile the theano function so it can take a bit of time.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Export  to vtk. (Under development)
Can you write Python code for it?

"""Export model to VTK

Export the geology blocks to VTK for visualisation of the entire 3-D model in an
external VTK viewer, e.g. Paraview.

..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk

**Optional keywords**:
    - *vtk_filename* = string : filename of VTK file (default: output_name)
    - *data* = np.array : data array to export to VKT (default: entire block model)
"""
vtk_filename = "noddyFunct2"

extent_x = 10
extent_y = 10
extent_z = 10

delx = 0.2
dely = 0.2
delz = 0.2
from pyevtk.hl import gridToVTK
# Coordinates
x = np.arange(0, extent_x + 0.1*delx, delx, dtype='float64')
y = np.arange(0, extent_y + 0.1*dely, dely, dtype='float64')
z = np.arange(0, extent_z + 0.1*delz, delz, dtype='float64')

# self.block = np.swapaxes(self.block, 0, 2)
gridToVTK(vtk_filename, x, y, z, cellData = {"geology" : sol})


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
In case of disconformities, we can define which formation belong to which series using a dictionary. Until python 3.6 is important to specify the order of the series otherwise is random
Can you write Python code for it?

sandstone.Data.set_series({"EarlyGranite_Series":sandstone.Data.formations[-1],
                      "BIF_Series":(sandstone.Data.formations[0], sandstone.Data.formations[1]),
                      "SimpleMafic_Series":sandstone.Data.formations[2]},
                       order = ["EarlyGranite_Series",
                              "BIF_Series",
                              "SimpleMafic_Series"])


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Looking at the profile we can see that most of time is in pow operation (exponential). This probably is that the extent is huge and we are doing it with too much precision. I am working on it
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Next step is the creating of a grid. So far only regular. By default it takes the extent and the resolution given in the import_data method.
Can you write Python code for it?

# Create a class Grid so far just regular grid
sandstone.create_grid()
sandstone.Grid.grid


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Now in the data frame we should have the series column too
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Now we could visualize the individual potential fields as follow:
Early granite
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Performance Analysis
One of the advantages of theano is the posibility to create a full profile of the function. This has to be included in at the time of the creation of the function. At the moment it should be active (the downside is larger compilation time and I think also a bit in the computation so be careful if you need a fast call)
CPU
The following profile is with a 2 core laptop. Nothing spectacular.
Can you write Python code for it?

%%timeit
# Reset the block
sandstone.Interpolator.block.set_value(np.zeros_like(sandstone.Grid.grid[:,0]))

# Compute the block
sandstone.Interpolator.compute_block_model([0,1,2], verbose = 0)


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
Plotting raw data
The object Plot is created automatically as we call the methods above. This object contains some methods to plot the data and the results.
It is possible to plot a 2D projection of the data in a specific direction using the following method. Also is possible to choose the series you want to plot. Additionally all the key arguments of seaborn lmplot can be used.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Example_1_Sandstone_Project-checkpoint.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
BIF Series
Can you write Python code for it?

sandstone.compute_potential_field("BIF_Series", verbose=1)
sandstone.plot_potential_field_2D(direction = "y", cell_pos = 12, figsize=(7,6), contour_lines = 100)

sandstone.potential_interfaces, sandstone.layers[0].shape;

%matplotlib qt4
block = np.ones_like(sandstone.Z_x)
block[sandstone.Z_x>sandstone.potential_interfaces[0]] = 0
block[(sandstone.Z_x<sandstone.potential_interfaces[0]) * (sandstone.Z_x>sandstone.potential_interfaces[-1])] = 1
block[sandstone.Z_x<sandstone.potential_interfaces[-1]] = 2
block = block.reshape(40,40,150)
plt.imshow(block[:,13,:].T, origin = "bottom", aspect = "equal", extent = (sandstone.xmin, sandstone.xmax,
                                                                           sandstone.zmin, sandstone.zmax),
          interpolation = "none")


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
Defining Series
Can you write Python code for it?

sandstone.set_series({"EarlyGranite_Series":sandstone.formations[-1],
                      "BIF_Series":(sandstone.formations[0], sandstone.formations[1]),
                      "SimpleMafic_Series":sandstone.formations[2]})
sandstone.series

sys.version_info


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
Export vtk
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
GPU
Can you write Python code for it?

interpolator.theano_set_3D()

%%timeit
sol =  interpolator.geoMigueller(dips,dips_angles,azimuths,polarity, rest, ref)[0].reshape(20,20,20, order = "C")

interpolator.geoMigueller.profile.summary()


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
Loading data from geomodeller
So there are 3 series, 2 of one single layer and 1 with 2. Therefore we need 3 potential fields, so lets begin.
Can you write Python code for it?

sandstone.load_data_csv("foliations", os.pardir+"/input_data/a_Foliations.csv")
sandstone.load_data_csv("interfaces", os.pardir+"/input_data/a_Points.csv")
pn.set_option('display.max_rows', 25)
sandstone.Foliations


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
Performance Analysis
CPU
Can you write Python code for it?

%%timeit
sol =  interpolator.geoMigueller(dips,dips_angles,azimuths,polarity, rest, ref)[0]

sandstone.block_export.profile.summary()


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Project_legacy-checkpoint.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?

sandstone.compute_potential_field("SimpleMafic_Series", verbose = 1)
sandstone.plot_potential_field_2D(direction = "y", cell_pos = 15, figsize=(7,6), contour_lines = 20)

sandstone.potential_interfaces, sandstone.layers[0].shape;

%matplotlib qt4
block = np.ones_like(sandstone.Z_x)
block[sandstone.Z_x>sandstone.potential_interfaces[0]] = 0
block[sandstone.Z_x<sandstone.potential_interfaces[-1]] = 1
block = block.reshape(40,40,150)
#block = np.swapaxes(block, 0, 1)
plt.imshow(block[:,13,:].T, origin = "bottom", aspect = "equal", extent = (sandstone.xmin, sandstone.xmax,
                                                                           sandstone.zmin, sandstone.zmax))


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
All input data is stored in pandas dataframes under, self.Data.Interances and self.Data.Foliations:
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
And again after computing the model in the Plot object we can use the method plot_block_section to see a 2D section of the model
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
GPU
Can you write Python code for it?

%%timeit
# Reset the block
sandstone.block.set_value(np.zeros_like(sandstone.grid[:,0]))

# Compute the block
sandstone.compute_block_model([0,1,2], verbose = 0)

sandstone.block_export.profile.summary()


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
In case of disconformities, we can define which formation belong to which series using a dictionary. Until python 3.6 is important to specify the order of the series otherwise is random
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
Next step is the creating of a grid. So far only regular. By default it takes the extent and the resolution given in the import_data method.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
Now in the data frame we should have the series column too
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
Now we could visualize the individual potential fields as follow:
Early granite
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
Optimizing the export of lithologies
But usually the final result we want to get is the final block. The method compute_block_model will compute the block model, updating the attribute block. This attribute is a theano shared function that can return a 3D array (raveled) using the method get_value().
Can you write Python code for it?

# Reset the block
sandstone.Interpolator.block.set_value(np.zeros_like(sandstone.Grid.grid[:,0]))

# Compute the block
sandstone.Interpolator.compute_block_model([0,1,2], verbose = 0)

sandstone.Interpolator.block.get_value(), np.unique(sandstone.Interpolator.block.get_value())


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
Plotting raw data
The object Plot is created automatically as we call the methods above. This object contains some methods to plot the data and the results.
It is possible to plot a 2D projection of the data in a specific direction using the following method. Also is possible to choose the series you want to plot. Additionally all the key arguments of seaborn lmplot can be used.
Can you write Python code for it?


I am working on the file "Prototype Notebook/.ipynb_checkpoints/Sandstone Testing new structure-checkpoint.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
And again after computing the model in the Plot object we can use the method plot_block_section to see a 2D section of the model
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
Class Interpolator
This class will take the data from the class Data and calculate potential fields and block. We can pass as key arguments all the variables of the interpolation. I recommend not to touch them if you do not know what are you doing. The default values should be good enough. Also the first time we execute the method, we will compile the theano function so it can take a bit of time.
Can you write Python code for it?

%debug

geo_data.interpolator.results

geo_data.interpolator.tg.c_o_T.get_value(), geo_data.interpolator.tg.a_T.get_value()

geo_data.interpolator.compile_potential_field_function()

geo_data.interpolator.compute_potential_fields('BIF_Series',verbose = 3)

geo_data.interpolator.potential_fields

geo_data.interpolator.results

geo_data.interpolator.tg.c_resc.get_value()


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
Export  to vtk. (Under development)
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
Optimizing the export of lithologies
But usually the final result we want to get is the final block. The method compute_block_model will compute the block model, updating the attribute block. This attribute is a theano shared function that can return a 3D array (raveled) using the method get_value().
Can you write Python code for it?

GeMpy.compute_block_model(geo_data)

#GeMpy.set_interpolator(geo_data, u_grade = 0, compute_potential_field=True)


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
Performance Analysis
One of the advantages of theano is the posibility to create a full profile of the function. This has to be included in at the time of the creation of the function. At the moment it should be active (the downside is larger compilation time and I think also a bit in the computation so be careful if you need a fast call)
CPU
The following profile is with a 2 core laptop. Nothing spectacular.
Looking at the profile we can see that most of time is in pow operation (exponential). This probably is that the extent is huge and we are doing it with too much precision. I am working on it
GPU
Can you write Python code for it?

%%timeit

# Compute the block
GeMpy.compute_block_model(geo_data, [0,1,2], verbose = 0)

geo_data.interpolator._interpolate.profile.summary()


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
Plotting raw data
The object Plot is created automatically as we call the methods above. This object contains some methods to plot the data and the results.
It is possible to plot a 2D projection of the data in a specific direction using the following method. Also is possible to choose the series you want to plot. Additionally all the key arguments of seaborn lmplot can be used.
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_1_Sandstone.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_2_Simple-Deprecated.ipynb".
The first task is:
Combining both potential field where the first potential field is younger than the second we can obtain the following structure.
Can you write Python code for it?

GeMpy.compute_block_model(geo_data, series_number= 'all', verbose = 0)
GeMpy.plot_section(geo_data, 13)


I am working on the file "Prototype Notebook/Example_2_Simple-Deprecated.ipynb".
The first task is:
Combining potential fields: Depositional series
In reality, most geological settings are formed by a concatenation of depositional phases separated clearly by unconformity bounderies. Each of these phases can be model by a potential field. In order to capture this behavior, we can classify the formations that belong to individual depositional phase into categories or series. The potential field computed for each of these series could be seen as a sort of evolution of the basin if an unconformity did not occur. Finally, sorting the temporal relation between series allow to superpose the corresponding potential field at an specific location.
In the next example, we add a new serie consisting in a layer---'Layer 3'--- Fig X, which generate the potential field of Fig X and subsequently the block Figure X.
Can you write Python code for it?

layer_3 = np.array([[2,4,3], [8,4,2], [9,4,3]])
dip_pos_3 = np.array([1,4,1])
dip_angle_3 = float(80)
azimuth_3 = 90
polarity_3 = 1

GeMpy.set_interfaces(geo_data, pn.DataFrame(
    data = {"X" :layer_3[:, 0],
            "Y" :layer_3[:, 1],
            "Z" :layer_3[:, 2],
            "formation" : np.tile("Layer 3", len(layer_3)),
            "labels" : [  r'${\bf{x}}_{\alpha \, 0}^3$',
                           r'${\bf{x}}_{\alpha \, 1}^3$',
                           r'${\bf{x}}_{\alpha \, 2}^3$'] }), append = True)
GeMpy.get_raw_data(geo_data,"interfaces")

GeMpy.set_foliations(geo_data, pn.DataFrame(data = {
                     "X" : dip_pos_3[0],
                     "Y" : dip_pos_3[1],
                     "Z" : dip_pos_3[2],
                     "azimuth" : azimuth_3,
                     "dip" : dip_angle_3,
                     "polarity" : polarity_3,
                     "formation" : [ 'Layer 3'],
                     "labels" : r'${\bf{x}}_{\beta \,{2}}$'}), append = True)
GeMpy.get_raw_data(geo_data, 'foliations')

GeMpy.set_data_series(geo_data, {'younger': ('Layer 1', 'Layer 2'),
                      'older': 'Layer 3'}, order_series = ['younger', 'older'])

GeMpy.plot_data(geo_data)


I am working on the file "Prototype Notebook/Example_2_Simple-Deprecated.ipynb".
The first task is:
Grid and potential field
We can see the potential field generated out of the data above
Can you write Python code for it?

from ipywidgets import widgets
from ipywidgets import interact
def cov_cubic_f(r,a = 6, c_o = 1):
    if r <= a:
        return c_o*(1-7*(r/a)**2+35/4*(r/a)**3-7/2*(r/a)**5+3/4*(r/a)**7)
    else:
        return 0

def cov_cubic_d1_f(r,a = 6., c_o = 1):
    SED_dips_dips = r
    f = c_o
    return  (f * ((-14 /a ** 2) + 105 / 4 * SED_dips_dips / a ** 3 -
            35 / 2 * SED_dips_dips ** 3 / a ** 5 + 21 / 4 * SED_dips_dips ** 5 / a ** 7))

def cov_cubic_d2_f(r, a = 6, c_o = 1):
    SED_dips_dips = r
    f = c_o
    return 7*f*(9*r**5-20*a**2*r**3+15*a**4*r-4*a**5)/(2*a**7)

def plot_potential_var(a = 10, c_o = 1, nugget_effect = 0):
    x = np.linspace(0,12,50)
    y = [cov_cubic_f(i, a = a, c_o = c_o) for i in x]

    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(x,c_o-np.asarray(y)+nugget_effect)
    plt.hlines(0,0,12, linestyles = "--")
    plt.title("Variogram")
    plt.margins(0,0.1)

    ax2 = fig.add_subplot(122)
    ax2.plot(x,np.asarray(y))
    ax2.scatter(0,nugget_effect+c_o)
    plt.title("Covariance Function")
    plt.tight_layout()
    plt.margins(0,0.1)
    plt.suptitle('$C_Z(r)$', y = 1.08, fontsize=15, fontweight='bold')

def plot_potential_direction_var( a = 10, c_o = 1, nugget_effect = 0):
    x = np.linspace(0,12,50)
    y = np.asarray([cov_cubic_d1_f(i, a = a, c_o = c_o) for i in x])

    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(x,c_o-np.asarray(y)+nugget_effect)
    plt.title("Variogram")
    plt.margins(0,0.1)

    ax2 = fig.add_subplot(122)
    ax2.plot(x,np.asarray(y))
    #ax2.scatter(0,c_o)
    plt.title("Cross-Covariance Function")
    plt.tight_layout()
    plt.margins(0,0.1)
    plt.suptitle('$C\'_Z / r$', y = 1.08, fontsize=15, fontweight='bold')

def plot_directionU_directionU_var(a = 10, c_o = 1, nugget_effect = 0):

    x = np.linspace(0.01,12,50)
    d1 = np.asarray([cov_cubic_d1_f(i, a = a, c_o = c_o) for i in x])
    d2 = np.asarray([cov_cubic_d2_f(i, a = a, c_o = c_o) for i in x])

    y = -(d2) #...


I am working on the file "Prototype Notebook/Example_2_Simple-Deprecated.ipynb".
The first task is:
Side note: Example of covariances involved in the cokriging system
Can you write Python code for it?


I am working on the file "Prototype Notebook/Example_2_Simple-Deprecated.ipynb".
The first task is:
This potential field gives the following block
Can you write Python code for it?

GeMpy.plot_potential_field(geo_data,4, n_pf=1, direction='y',
                           colorbar = True, cmap = 'magma' )

GeMpy.get_raw_data(geo_data)


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
All input data is stored in pandas dataframes under, self.Data.Interances and self.Data.Foliations:
Can you write Python code for it?

sandstone.Data.Foliations;

# Create a class Grid so far just regular grid
sandstone.create_grid()
sandstone.Grid.grid


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
Export vtk
Can you write Python code for it?

"""Export model to VTK

Export the geology blocks to VTK for visualisation of the entire 3-D model in an
external VTK viewer, e.g. Paraview.

..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk

**Optional keywords**:
    - *vtk_filename* = string : filename of VTK file (default: output_name)
    - *data* = np.array : data array to export to VKT (default: entire block model)
"""
vtk_filename = "noddyFunct2"

extent_x = 10
extent_y = 10
extent_z = 10

delx = 0.2
dely = 0.2
delz = 0.2
from pyevtk.hl import gridToVTK
# Coordinates
x = np.arange(0, extent_x + 0.1*delx, delx, dtype='float64')
y = np.arange(0, extent_y + 0.1*dely, dely, dtype='float64')
z = np.arange(0, extent_z + 0.1*delz, delz, dtype='float64')

# self.block = np.swapaxes(self.block, 0, 2)
gridToVTK(vtk_filename, x, y, z, cellData = {"geology" : sol})


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
Optimizing the export of lithologies
Here I am going to try to return from the theano interpolate function the internal type of the result (in this case DK I guess) so I can make another function in python I guess to decide which potential field I calculate at every grid_pos
Can you write Python code for it?

# Reset the block
sandstone.Interpolator.block.set_value(np.zeros_like(sandstone.Grid.grid[:,0]))

# Compute the block
sandstone.Interpolator.compute_block_model([0,1,2], verbose = 1)

sandstone.Plot.plot_block_section()


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
Performance Analysis
CPU
Can you write Python code for it?


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
Plotting raw data
Can you write Python code for it?


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
SImple mafic
Can you write Python code for it?


I am working on the file "Prototype Notebook/Sandstone Project.ipynb".
The first task is:
Sandstone Model
First we make a GeMpy instance with most of the parameters default (except range that is given by the project). Then we also fix the extension and the resolution of the domain we want to interpolate. Finally we compile the function, only needed once every time we open the project (the guys of theano they are working on letting loading compiled files, even though in our case it is not a big deal).
General note. So far the reescaling factor is calculated for all series at the same time. GeoModeller does it individually for every potential field. I have to look better what this parameter exactly means
Can you write Python code for it?

# Setting extend, grid and compile
# Setting the extent
sandstone = GeMpy_core.GeMpy()

# Create Data class with raw data
sandstone.import_data( 696000,747000,6863000,6950000,-20000, 2000,
                                     path_f = os.pardir+"/input_data/a_Foliations.csv",
                                     path_i = os.pardir+"/input_data/a_Points.csv")

sandstone.Data.set_series({"EarlyGranite_Series":sandstone.Data.formations[-1],
                      "BIF_Series":(sandstone.Data.formations[0], sandstone.Data.formations[1]),
                      "SimpleMafic_Series":sandstone.Data.formations[2]},
                       order = ["EarlyGranite_Series",
                              "BIF_Series",
                              "SimpleMafic_Series"])