I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit 03-checkpoint.ipynb".
The first task is:
The Jaynes-Cummings model
The Jaynes-Cummings model is one of the most elementary quantum mechanical models light-matter interaction. It describes a single two-level atom that interacts with a single harmonic-oscillator mode of a electromagnetic cavity.
The Hamiltonian for a two-level system in its eigenbasis can be written as
$$
H = \frac{1}{2}\omega_q \sigma_z
$$
and the Hamiltonian of a quantum harmonic oscillator (cavity or nanomechanical resonator, NR) is
$$
H = \hbar\omega_r (a^\dagger a + 1/2)
$$
$$
H = \hbar\omega_{NR} (b^\dagger b + 1/2)
$$
The atom interacts with the electromagnetic field produced by the cavity (NR) mode $a + a^\dagger$ ($b + b^\dagger$) through its dipole moment. The dipole-transition operators is $\sigma_x$ (which cause a transition from the two dipole states of the atom). The combined atom-cavity Hamiltonian can therefore be written in the form
$$
H =
\hbar \omega_r (a^\dagger a + 1/2)
+
\hbar \omega_{NR} (b^\dagger b + 1/2)
+ \frac{1}{2}\hbar\Omega\sigma_z
+
\hbar
\sigma_x \left( g(a + a^\dagger)
+
\lambda(b + b^\dagger)\right)
$$
Although the Jaynes-Cumming Hamiltonian allow us to evolve the given initial state according to the Schrödinger Equation, in an experiment we would like to predicte the response of the coupled cavity-NR-qubit system under the influence of driving fields for the cavity and qubit, and also account for the effects of dissipation and dephasing (not treated here)
The external coherent-state input may be incorporated in the Jaynes-Cummings Hamiltonian by addition of terms involving the amplitude of the driving field $\vec{E_d} \left(\vec{E_s}\right)$ and it's frequency $\omega_d\left(\omega_s\right)$
$$
H_{cavity} =
E_d \left(e^{i\omega_dt}a +e^{-i\omega_dt}a^\dagger\right)
$$
$$
H_{qubit} =
E_s \left(e^{i\omega_st}\sigma_- +e^{-i\omega_st}\sigma_+\right)
$$
$$
H_{NR} =
E_p \left(e^{i\omega_st}b +e^{-i\omega_st}b^\dagger\right)
$$
To obtain the Jaynes-Cumming Hamiltonian
$$
?
H =
\hbar\omega_r (a^\dagger a + 1/2)
%-\frac{1}{2}\Delta\sigma_x
+...
Can you write Python code for it?


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit 03-checkpoint.ipynb".
The first task is:
This is the interaction term of in the Jaynes-Cumming model in the interaction picture. If we transform back to the Schrödinger picture we have:
Can you write Python code for it?

U = exp(-I * omega_r * t * Dagger(a) * a)
H6 = hamiltonian_transformation(U, H5.expand(), independent =True)

U = exp(-I * omega_q * t * sp * sm)
H7 = hamiltonian_transformation(U, H6.expand(),independent = True)

H8 = simplify_exp(H7).subs(Delta_CPW, omega_q - omega_r)

H8 = simplify_exp(powsimp(H8)).expand()

H8 = drop_c_number_terms(H8)

H = collect(H8, [g])

Eq(Hsym, H)

H = collect(H,[L*sm])
H = collect(H,[L*sp])
H = collect(H,[L*(Dagger(b)+b), A, B ,C])
H = H.subs(sm+sp,sx)
H


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit 03-checkpoint.ipynb".
The first task is:
We introduce the detuning parameter $\Delta = \omega_q - \omega_r$ and substitute into this expression
Can you write Python code for it?

# trick to simplify exponents
def simplify_exp(e):
    if isinstance(e, exp):
        return exp(simplify(e.exp.expand()))

    if isinstance(e, (Add, Mul)):
        return type(e)(*(simplify_exp(arg) for arg in e.args))

    return e

H4 = simplify_exp(H3).subs(-omega_r + omega_q, Delta_CPW)

H4


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Introduce the detuning $\Delta_{SP} = \omega_S - \omega_D$ and $\Delta_{SD} = \omega_S - \omega_D$:
Can you write Python code for it?

H4 = simplify_exp(powsimp(H4))
H4 = H4.subs(omega_p - omega_s,-Delta_SP).expand()
H4 = simplify_exp(powsimp(H4))
H4 = H4.subs(omega_d - omega_s,-Delta_SD).expand()

H5 = H4.collect([A,B,C,L,Dagger(a)*a,Dagger(b)*b,g])
# H5

H5 = H5.expand()
# H5

H6 = simplify_exp(powsimp(H5))
# H6 = simplify_exp(H6).subs(omega_t - omega_s, Delta_t)

H = H6.collect([A,B,C,Dagger(a)*a,g,sz,L])

Eq(Hsym, H)


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Now, in the rotating-wave approximation we can drop the fast oscillating terms containing the factors
$e^{\pm i(\omega_q + \omega_r)t} $ and $e^{\pm i(\omega_q + \omega_{NR})t}  $
Can you write Python code for it?

H4 = drop_terms_containing(H3, [exp( I * (omega_q + omega_r) * t),
                                exp(-I * (omega_q + omega_r) * t),
                                exp(I * (omega_q + omega_nr) * t),
                                exp(-I * (omega_q + omega_nr) * t)],
                          )

H4 = drop_c_number_terms(H4.expand())

Eq(Hsym, H4)


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Qubit - Sigma_z
Can you write Python code for it?

U = exp(I * omega_q * t * sp * sm)

# U

H2 = hamiltonian_transformation(U, H1a.expand())

H2 = H2.subs(sx, sm + sp).expand()

H2 = powsimp(H2)

# H2

# H2

# trick to simplify exponents
def simplify_exp(e):
    if isinstance(e, exp):
        return exp(simplify(e.exp.expand()))

    if isinstance(e, (Add, Mul)):
        return type(e)(*(simplify_exp(arg) for arg in e.args))

    return e

H3a = simplify_exp(H2).subs(-omega_r + omega_q, Delta_CPW)
H3 = simplify_exp(H3a).subs(-omega_nr + omega_q, Delta_NR)

# H3


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Second we apply the unitary transformation $U = e^{i \omega_p b^\dagger b t}$:
Can you write Python code for it?

U = exp(I * Dagger(b) * b * omega_p * t)

H3a = hamiltonian_transformation(U, H3, independent=True)

H3b = drop_terms_containing(H3a.expand(), [exp(-2*I*omega_p*t), exp(2*I*omega_p*t)])
H3b = H3b.collect([A,B,C,L,Dagger(a)*a,Dagger(b)*b,g])

H3c = H3b.subs(-omega_p+omega_nr, Delta_p).expand()

H3c = H3c.collect([A,B,C,L,Dagger(a)*a,Dagger(b)*b,g])

H3c


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Second we apply the unitary transformation $U = e^{i \omega_s \sigma_+ \sigma_- t}$:
Can you write Python code for it?

U = exp(I * sp*sm* omega_s * t)

# U

H4 = hamiltonian_transformation(U, H3, independent=True)

H4 =H4.expand()
H4


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Substiture $\sigma_z = 2\sigma_+\sigma_-$
Can you write Python code for it?

H3 = H3c.subs(sz,2*sp*sm).expand()
# H3

H3 = H3.collect([A,B,C,L,Dagger(a)*a,Dagger(b)*b,g])
# H3

# H3


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
This is the Hamiltonian of the Jaynes-Cummings model in the the dispersive regime. It can be interpreted as the resonator having a qubit-state-dependent frequency shift, or alternatively that the qubit is feeling a resonator-photon-number dependent Stark-shift.
Can you write Python code for it?


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
This is the Jaynes-Cumming model give above, and we have now seen that it is obtained to the dipole interaction Hamiltonian through the rotating wave approximation.
Dispersive regime
In the dispersive regime, where the two-level system is detuned from the cavity by much more than the interaction strength, $\Delta \gg g, \lambda$, an effective Hamiltonian can be dervied which describes the Stark shift of the two-level system (which depends on the number of photons in the cavity) and the frequency shift of the cavity (which depend on the state of the two-level system).
This effective Hamiltonian, which is correct up to second order in the small paramter $g/\Delta$, is obtained by performing the unitary transformation
$$
U = e^{\frac{g}{\Delta}(a \sigma_- - a^\dagger \sigma_+)}
$$
$$
U = e^{\frac{\lambda}{\Delta}(b \sigma_- - b^\dagger \sigma_+)}
$$
Can you write Python code for it?

U = exp(x * (a * sp).expand())

# U

#H1 = unitary_transformation(U, H, allinone=True, expansion_search=False, N=3).expand()
#H1 = qsimplify(H1)
#H1

H1 = hamiltonian_transformation(U, H, expansion_search=False, N=3).expand()

H1a = qsimplify(H1)

# H1a

U = exp(y * (b * sp).expand())

# U

H1a = hamiltonian_transformation(U, H1a, expansion_search=False, N=3).expand()

H1 = qsimplify(H1a)

# H1

U = exp(-x * (Dagger(a) * sm).expand())

# U

H2a = hamiltonian_transformation(U, H1, expansion_search=False, N=3).expand()

H2a = qsimplify(H2a)

# H2a

U = exp(-y * (Dagger(b) * sm).expand())

# U

H2 = hamiltonian_transformation(U, H2a, expansion_search=False, N=3).expand()

H2 = qsimplify(H2)

# H2

# H3 = drop_terms_containing(H2.expand(), [x**2,x**3, x**4,x**5,x**6,x**7, y**2,y**3, y**4,y**5,y**6,y**7])
H3 = drop_terms_containing(H2.expand(), [x**3, x**4,x**5,x**6,x**7, y**3, y**4,y**5,y**6,y**7])

# H3

H4 = H3.subs(x, g/Delta_CPW)
H4a = H4.subs(y, L/Delta_NR)
# H4

H4b = qsimplify(H4a)

H5 = drop_c_number_terms(H4b)
# H6a = drop_terms_containing(H5.expand(), [exp(I*Delta_SP*t), exp(-I*Delta_SP*t)])
# H6 = drop_terms_containing(H6a.expand(), [exp(I*Delta_SD*t), exp(-I*Delta_SD*t)])

# H6

H6 = collect(H5, [A,B,C,Dagger(a)*a,Dagger(b)*b,sz,g,L])
# H6

U = exp(I * omega_r * t * Dagger(a) * a)
H7 = hamiltonian_transformation(U, H6.expand()).expand()

H7a = qsimplify(H7)

U = exp(I * omega_nr * t * Dagger(b) * b)
H7b = hamiltonian_transformation(U, H7a).expand()

H7b = qsimplify(H7b)

U = exp(I * omega_q * t * sp * sm)
H7c = hamiltonian_transformation(U, H7b, expansion_search=False, N=3).expand()

H7c = qsimplify(H7c)

H8 = drop_terms_containing(H7, [exp(I * omega_r * t), exp(-I * omega_r * t),
                                exp(I * omega_nr * t), exp(-I * omega_nr * t),
                                exp(I * omega_q * t), exp(-I * omega_q * t)])

U = exp(- I * omega_r * t * Dagger(a) * a)
H9 = hamiltonian_transformation(U, H8.expand(), expansion_search=False, N=3).expand()

H9 = qsimplify(H9)

U = exp(-I...


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
This is the interaction term of in the Jaynes-Cumming model in the interaction picture. If we transform back to the Schrödinger picture we have:
Can you write Python code for it?

U = exp(-I * omega_r * t * Dagger(a) * a)
H5 = hamiltonian_transformation(U, H4.expand(), independent=True)
# H5

U = exp(-I * omega_nr * t * Dagger(b) * b)
H5a = hamiltonian_transformation(U, H5.expand(), independent=True)
# H5a

U = exp(-I * omega_q * t * sp * sm)
H6 = hamiltonian_transformation(U, H5a.expand())
# H6

H7a = simplify_exp(H6).subs(Delta_CPW, omega_q - omega_r)
H7 = simplify_exp(H7a).subs(Delta_NR, omega_q - omega_nr)

H7 = simplify_exp(powsimp(H7)).expand()

H7 = drop_c_number_terms(H7)

H = collect(H7, [A,B, C,g,L])

Eq(Hsym, H)


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
Unitary transformation to interaction picture
CPW (a)
Can you write Python code for it?

U = exp(I  * omega_r * t * Dagger(a)*a)
# U

H1 = hamiltonian_transformation(U, H_total.expand(), independent=True)

# H1


I am working on the file "Simulation - CPW-Filter-qubit/.ipynb_checkpoints/SimPSI - Qubit-Cavity-NR Dispersive limit-checkpoint.ipynb".
The first task is:
We can now perform a rotating-wave approximation (RWA) by eliminating all terms that rotate with frequencies $2\omega_d$:
Can you write Python code for it?

H2 = drop_terms_containing(H1.expand(), [exp(-2*I*omega_d*t), exp(2*I*omega_d*t)])
H2 = H2.collect([A,B,Dagger(a)*a,g])
# H2
# Eq(Symbol("H_{rwa}"), H2)


I am working on the file "Simulation_and_Optimization/EFS_System_Requirements.ipynb".
The first task is:
Reference Equations for Mechanical Energy Process
Mechanical Energy Equation (Energy per Unit Weight, Nm / N = m):
$$\frac{P_{out}}{\gamma} + \frac{v_{out}^2}{2g} + z_{out} = \frac{P_{in}}{\gamma} + \frac{v_{in}^2}{2g} + z_{in} + h_s - h_{L,total}$$
Pump Assumptions:
$v_{out} = v_{in}$: Constant mass flow through constant diameter pipe makes for constant velocity. $v_{in}$ is the velcity before the pump, $v_{out}$ is the fluid leaving the pump.
$z_{out} = z_{in}$: Elevation difference between Propellant tank and rocket engine producing negligible amount of system energy.
Reduced Mechanical Energy Equation:
$$\frac{P_{out}}{\gamma}  = \frac{P_{in}}{\gamma} + h_s - h_{L,total}$$
Solve for Shaft Work:
$$h_s = \frac{P_{out}}{\gamma} - \frac{P_{in}}{\gamma} + h_{L,total}$$
$$h_s = \frac{W_{shaft, net, in}}{g}$$ (work per unit weight, unit of length)
This section, the calculated power requirement can be used to estimate the battery requirement for a propellant system. Reassign any necessary variable once new design and experimental losses are identified.
If the propellant tank size is known, this value can be used directly instead of determined with mass flow, gravity, and estimated operation time as shown above.
Can you write Python code for it?

def power_req(p_ch, mdot, material, p_in, fric, plum_len, delP_inj, static_head):
    qdot, v, v_lfets, Re = pipe_flow(mdot, material)
    h_L         = head_loss(fric, plum_len, v) # Total Head Loss
    p_out       = 1.25 * (p_ch + delP_inj) # Required Outlet Pressure including injector and venturi losses
    delP        = p_out - p_in
    spec_dens   = G_N * material['rho']
    h_s         = delP / material['rho'] + h_L * G_N # Shaft Work Head times standard gravity
    if h_s <= 0:
        return v_lfets, p_out, 0, 0
    W           = mdot * h_s / PUMP_EFF # power requirement
    tau         = 2 # no less than 2, to avoid cavitation
    inlet_head  = p_in / spec_dens
    vap_p_head  = material['p_v'] / spec_dens
    npsh_a      = inlet_head + static_head - vap_p_head - h_L # available net pressure suction head
    npsh_r      = max(0, npsh_a / tau) # rotational. pardon the kludge...
    rpm         = U_SS * (npsh_r*3.281)**0.75 / (21.2 * np.sqrt(qdot*35.31)) # magic numbers are unit conversion weirdness
    #print(material['name'], ' SH: ',static_head, ' HL: ', h_L)
    return v_lfets, p_out, W * 1.111, rpm * 1.111 # FOS so that operating conditions are 80% of maximum


I am working on the file "Simulation_and_Optimization/EFS_System_Requirements.ipynb".
The first task is:
Summary
Credit to Julio, minor modifications by Cory.
This document is to provide a calculation process for determining the required power necessary to power the Electric Feed System.
In this document, variables for Pressure, Mass Flowrate, Fluid Properties, and Plumbing Geometry will be self-defined variables.
Equations will use the defined variables for calculations.
I found this website useful, as well as this.
Parameter Definitions
Can you write Python code for it?

RtoD = EPSILON_PIPE / D_PIPE # Rougness to Diameter Ratio
# used to determine friction factors?


I am working on the file "Simulation_and_Optimization/EFS_System_Requirements.ipynb".
The first task is:
Up to this point, the goal of the file has been to identify the characteristics of the system along with calculated some critical factors such as:
* The Reynolds nubmer which helps predict flow characteristics of moving fluids
* The fluid velocity which will helps us predict loss factors for the system.
Plumbing Losses
System Major Losses
(energy loss due to viscous effects (friction) through straight pipe sections).

System Minor Losses (energy losses due to changes in flow direction caused by plumbing connections.)
Can you write Python code for it?

def head_loss(fric, plum_len, v):
    h_LMajor = fric * plum_len * v**2 / (D_PIPE * 2 * G_N) # m Head Major Loss
    h_LMinor = K_L * v**2 / (2 * G_N) # m Head Minor Loss
    return h_LMajor + h_LMinor


I am working on the file "Simulation_and_Optimization/Launcher_Settings_Optimization.ipynb".
The first task is:
Optimization Problem
Given a design vector $x$ and the iteration number $n$ our merit function cost runs a trajectory simulation and evaluates the quality of that rocket. We keep track of each design and its merit value for later visualization, hence why global variables are used.
We run an iterative sequence of optimization routines with a decreasing barrier function and increasing penalty functions so that the optimization can range over a larger portion of the design space away from its boundaries before settling into local minima closer to the boundary.
Can you write Python code for it?

# this manages all our constraints
# penalty parameters: mu -> 0 and rho -> infinity
def penalty(alt, mu, rho):
    b = [#barrier(alt, CONS_ALT, int_point=False, good_if_less_than=False)
        ]
    eq = []
    ext = [exterior(alt, CONS_ALT-3000, good_if_less_than=False)
          ]
    return mu*sum(b) + rho*(sum(eq) + sum(ext))

# Pseudo-objective merit function
# x is array of design parameters, n is index of penalty and barrier functions
def cost(x, nominal):
    global allvectors, allobjfun
    # get trajectory data
    sim = trajectory(M_PROP, MDOT, P_E,
               THROTTLE_WINDOW, MIN_THROTTLE,
               RCS_MDOT, RCS_P_E, RCS_P_CH,
               BALLAST, FIN_ROOT, FIN_TIP, FIN_SWEEP_ANGLE, FIN_SEMISPAN, FIN_THICKNESS, CON_NOSE_L,
               LOX_TANK_P, IPA_TANK_P, RIB_T, NUM_RADL_DVSNS,
               AIRFRM_IN_RAD, IPA_WT, OF, ENG_P_CH, ENG_T_CH, ENG_KE, ENG_MM,
               [0, 0, x[0], x[1], False, 0, 0, 0, 0, 0, 0, True],
                0.025, True, 0.005, True, True)

    # either minimize the distance from nominal impact point
    if TARGET:
        #nominal = np.array([nominal, kludge])
        obj_func = objective_additive(sim.impact, nominal)
    # or maximize distance from launch point
    else:
        obj_func = - objective_additive(sim.impact, sim.env.launch_pt)

    pen_func = penalty(sim.LV4.apogee, MU_0 / (2**1), RHO_0 * (2**1))
    # add objective and penalty functions
    merit_func = obj_func + pen_func
    allvectors.append(x) # maintains a list of every design, side effect
    allobjfun.append(merit_func)
    #print("vec:", x,'\t', "impact:", sim.impact, '\t', "alt:", sim.LV4.apogee)
    return merit_func

# we want to iterate our optimizer for theoretical "convergence" reasons (given some assumptions)
# n = number of sequential iterations
def iterate(func, x_0, n, nominal):
    x = x_0
    designs = []
    for i in range(n):
        print("Iteration " + str(i+1) + ":")
        # this minimizer uses simplex method
        res = minimize(func, x,...


I am working on the file "Simulation_and_Optimization/Launcher_Settings_Optimization.ipynb".
The first task is:
The purpose of this notebook is to determine the optimal launch azimuth and elevation angles, in order to maximize the likelihood of landing in a particular region. Eventually, this should be expanded to enable input of day-of wind measurements so that we can determine these settings on the day of the launch. We may need to optimize the trajectory simulation code for this purpose, perhaps with less degrees of freedom, since it is currently fairly slow.
This program has essentially the same structure as the MDO and differs only in how trajectory performance is evaluated and which parameters are held constant or optimized over. Examination of the differences should enable one to make similar programs for different but related purposes.
Functions of Merit
We chose to abstract all of the functions used within the merit function for increased flexibility, ease of reading, and later utility. We use convex functions four our optimization, but we don't use much of the theory of convex optimization.

objective_additive is arbitrarily constructed. It is
appropriate for vector-valued measurements,
not normalized,
squared to reward (or punish) relative to the distance from nominal value, and
divided by two for aesthetic reasons.

objective is arbitrarily constructed. It is
normalized (by a somewhat arbitrary constant) to bring it into the same range as constraints,
squared to reward (or punish) relative to the distance from nominal value, and
divided by two so that our nominal value is 0.5 instead of 1.0.

exact is less arbitrarily constructed. It is
squared to be horizontally symmetric (which could also be obtained by absolute value),
determined by the distance from a constant, and
divided by two is for aesthetic value.

exterior is not particularly arbitrary. It is
boolean so that we can specify whether it is minimizing or maximizing its variable,
0 when the inequality is satisfied, otherwise it is just as punishing as exact.

barrier comes in two flavors, one of which is not used here. It is
boolean so that we can...
Can you write Python code for it?

# all of our comparisons are ratios instead of subtractions because
# it's normalized, instead of dependent on magnitudes of variables and constraints

def objective_additive(var, cons):
    return np.linalg.norm(var - cons)**2 / 2

# minimize this, **2 makes it well behaved w.r.t. when var=cons
def objective(var, cons):
    return (var/cons)**2 / 2

# **2 because i like it more than abs(), but that also works
def exact(var, cons):
    return (var/cons - 1)**2 / 2

# this is your basic exterior penalty, either punishes for unfeasibility or is inactive
def exterior(var, cons, good_if_less_than=False):
    if good_if_less_than:
        return max(0, var/cons - 1)**2 / 2
    else:
        return max(0, -(var/cons - 1))**2 / 2

# this barrier function restricts our objective function to the strictly feasible region
# make rockets great again, build that wall, etc, watch out for undefined operations
def barrier(var, cons, int_point=False, good_if_less_than=True):
    global dbz
    try: # just in case we accidentally leave feasible region
        if not int_point:
            if good_if_less_than:
                return -log(-(var/cons - 1))
            else:
                return -log(var/cons - 1)
        elif int_point:
            def interior(g): return 1/g # in case we don't like logarithms, which is a mistake
            if good_if_less_than:
                return -interior(var/cons - 1)
            else:
                return -interior(-(var/cons - 1))
    except:
        return float('inf') # ordinarily, this is bad practice since it could confuse the optimizer
                            # however, since this is a barrier function not an ordinary penalty, i think it's fine


I am working on the file "Simulation_and_Optimization/Launcher_Settings_Optimization.ipynb".
The first task is:
Top-Level of Optimization Routine
Here's where the magic happens. This code block runs the iterative optimization and provides details from our optimized trajectory.
Can you write Python code for it?

# this either maximizes distance from launch site or minimizes distance from nominal impact point
if __name__ == '__main__':
    if TARGET:
        target_pt = np.array([32.918255, -106.349477])
    else:
        target_pt = None

    if SIMPLEX:
        x0 = np.array([AZ_PERTURB, EL_PERTURB])
        # feed initial design into iterative optimizer, get most (locally) feasible design
        x = iterate(cost, x0, 1, nominal = target_pt)

    else:
        # probe design space, darwin style. if design space has more than 3 dimensions, you might need this. takes forever.
        x = rbf_optimizer(cost, nominal = target_pt)

    print("Optimization done!")

if __name__ == '__main__':
# Rename the optimized output for convenience
    az_perturb    = x[0]
    el_perturb    = x[1]

    # get trajectory info from optimal design
    sim = trajectory(M_PROP, MDOT, P_E,
               THROTTLE_WINDOW, MIN_THROTTLE,
               RCS_MDOT, RCS_P_E, RCS_P_CH,
               BALLAST, FIN_ROOT, FIN_TIP, FIN_SWEEP_ANGLE, FIN_SEMISPAN, FIN_THICKNESS, CON_NOSE_L,
               LOX_TANK_P, IPA_TANK_P, RIB_T, NUM_RADL_DVSNS,
               AIRFRM_IN_RAD, IPA_WT, OF, ENG_P_CH, ENG_T_CH, ENG_KE, ENG_MM,
               [0, 0, az_perturb, el_perturb, False, 0, 0, 0, 0, 0, 0, True],
                0.025, False, 0.005, True, False)

    print("Azimuth Perturbation:", az_perturb)
    print("Elevation Perturbation:", el_perturb)
    print("Launch point", sim.env.launch_pt)
    print("Impact point", sim.impact)
    print()

    textlist = print_results(sim, False)
    # draw pretty pictures of optimized trajectory
    rocket_plot(sim.t, sim.alt, sim.v, sim.a, sim.thrust,
                sim.dyn_press, sim.Ma, sim.m, sim.p_a, sim.drag, sim.throttle, sim.fin_flutter, sim, False, None, None)

    # get/print info about our trajectory and rocket
    for line in textlist:
        print(line)

    # draw more pretty pictures, but of the optimizer guts
    design_grapher(allvectors)


I am working on the file "Simulation_and_Optimization/Pressure_Requirements.ipynb".
The first task is:
Some of the relevant quantities can be obtained directly from the MDO.
We must determine:
* the compressibility factors of the pressurant (z_g) and the gaseous mixtures (z_p_lox, z_p_ipa).
* specific heat at constant pressure of pressurant (c_pg)
* molar masses of propellants (mm_lox, mm_ipa)
* specific heats of liquid propellants (c_pl_lox, c_pl_ipa)
* heats of vaporization of propellants (h_v_lox, h_v_ipa)
* specific heats of propellant vapors (c_pv_lox, c_pv_ipa)
* vaporization temperatures of propellants (t_v_lox, t_v_ipa)
* heat transfer coefficients at gas-liquid interfaces (h_lox, h_ipa)
* assumed temperature of gaseous mixtures after expulsion (t_u_lox, t_u_ipa)
Some of these quantities may only depend on the choice of material. We are certainly using LOX for the oxidizer and IPA/H20 for the fuel, but we have not yet finalized the IPA/H20 ratio for the fuel so a stretch goal would be a method of determining related parameters as a function of this ratio.
The assumed temperatures after expulsion will require several iterations to nail down, since we want to end up with the same holding temperature of pressurant. We could possibly start with this temperature, but H&H don't provide much insight into solving the resultant heat balance equation (1 equation in 3 unknowns). Alternatively, we could heat the pressurant differently prior to injection.
Can you write Python code for it?

# 1st order approximation
def n2_prop_reqs(rkt):
    m_g_lox = mass(rkt.lox_tank.p_0, rkt.lox_tank.volume, N2_TEMP, 0.95, N2_MM)
    m_g_ipa = mass(rkt.ipa_tank.p_0, rkt.ipa_tank.volume, N2_TEMP, 0.95, N2_MM)
    return m_g_lox + m_g_ipa

# n2 requirements with heat transfer
def n2_prop_reqs_detailed(sim, z_g, c_pg,
                   z_p_lox, mm_lox, c_pl_lox, h_v_lox, c_pv_lox, t_v_lox, h_lox, t_u_lox,
                   z_p_ipa, mm_ipa, c_pl_ipa, h_v_ipa, c_pv_ipa, t_v_ipa, h_ipa, t_u_ipa):
    m_g_lox, t_g_lox = pressurant_reqs_3(sim.LV4.lox_tank.p_0, sim.LV4.lox_tank.volume, z_g, N2_MM,
                     h_lox, np.pi * sim.LV4.lox_tank.in_radius**2, sim.t[sim.F_index], t_u_lox, 90.18,
                     c_pl_lox, h_v_lox, c_pv_lox, t_v_lox,
                     z_p_lox, mm_lox,
                     c_pg,
                     0, 0)

    m_g_ipa, t_g_ipa = pressurant_reqs_3(sim.LV4.ipa_tank.p_0, sim.LV4.ipa_tank.volume, z_g, N2_MM,
                     h_ipa, np.pi * sim.LV4.ipa_tank.in_radius**2, sim.t[sim.F_index], t_u_ipa, 298.15,
                     c_pl_ipa, h_v_ipa, c_pv_ipa, t_v_ipa,
                     z_p_ipa, mm_ipa,
                     c_pg,
                     0, 0)
    return m_g_lox + m_g_ipa, t_g_lox, t_g_ipa

if __name__ == '__main__' and not '__file__' in globals():
    %run Trajectory_Simulation.ipynb
    sim = trajectory(M_PROP, MDOT, P_E, THROTTLE_WINDOW, MIN_THROTTLE, RCS_MDOT, RCS_P_E, RCS_P_CH,
                          0, FIN_ROOT, FIN_TIP, FIN_SWEEP_ANGLE, FIN_SEMISPAN, FIN_THICKNESS,
                          LOX_TANK_P, IPA_TANK_P, AIRFRM_IN_RAD,
                          OF, ENG_P_CH, ENG_T_CH, ENG_KE, ENG_MM,
                          [0, 0, 0, 0, False, 0, 0, 0, 0, 0, 0, False],
                          0.05, True, 0.1, True, False)

if False and __name__ == '__main__' and not '__file__' in globals():
    m_g, t_g_lox, t_g_ipa = calculate_reqs(sim, z_g, c_pg,
                                           z_p_lox, mm_lox, c_pl_lox, h_v_lox, c_pv_lox,...


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Actions
Pour représenter une action choisie par une personne :
Can you write Python code for it?

class action():
    def __init__(self, typeAction="piocher", choix=None):
        assert typeAction in ["piocher", "choisir", "Jap Jap !"]
        self.typeAction = typeAction
        assert choix is None or choix in [0, 1, 2, 3, 4]
        self.choix = choix

    def __str__(self):
        if self.est_piocher(): return "Piocher"
        elif self.est_japjap(): return "Jap Jap !"
        elif self.est_choisir(): return "Choisir #{}".format(self.choix)

    def est_piocher(self):
        return self.typeAction == "piocher"

    def est_choisir(self):
        return self.typeAction == "choisir"

    def est_japjap(self):
        return self.typeAction == "Jap Jap !"

action_piocher = action("piocher")
action_japjap = action("Jap Jap !")
action_choisir0 = action("choisir", 0)
action_choisir1 = action("choisir", 1)
action_choisir2 = action("choisir", 2)
action_choisir3 = action("choisir", 3)
action_choisir4 = action("choisir", 4)


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Etat du jeu
Maintenant on peut représenter un état du jeu.
Can you write Python code for it?

# on peut changer ici pour jouer moins longtemps !
scoreMax = 90
scoreMax = 10

class EtatJeu():
    def __init__(self, nbPersonnes=2, nomsPersonnes=None,
                 scoreMax=scoreMax, malusContreJapJap=25, nbCartesMax=5):
        assert 2 <= nbPersonnes <= 5, "Le nombre de personnes pouvant jouer doit etre entre 2 et 5."
        self.nbPersonnes = nbPersonnes
        self.nomsPersonnes = nomsPersonnes
        self.scoreMax = scoreMax
        self.malusContreJapJap = malusContreJapJap
        self.nbCartesMax = nbCartesMax
        # on initialise le stockage interne
        self.personnes = [personne for personne in range(nbPersonnes)]
        self.scores = [
            0 for personne in self.personnes
        ]
        self.mains = [
            [ ] for personne in self.personnes
        ]
        self.visibles = []
        self.jeu = nouveau_jeu()

    def montrer_information_visibles(self):
        print("- Nombre de carte dans la pioche :", len(self.jeu))
        print("- Cartes visibles au sommet de la défausse :", len(self.visibles))
        for personne in self.personnes:
            nom = self.nomsPersonnes[personne] if self.nomsPersonnes is not None else personne
            main = self.mains[personne]
            score = self.scores[personne]
            print("    + Personne {} a {} carte{} en main, et un score de {}.".format(
                nom, len(main), "s" if len(main) > 1 else "", score)
            )

    def montrer_information_privee(self, personne=0):
        main = self.mains[personne]
        nom = self.nomsPersonnes[personne] if self.nomsPersonnes is not None else personne
        display(Markdown("[{}] Carte{} en main : {}".format(nom, "s" if len(main) > 1 else "", main)))

    # --- Mécanique de pioche et distribution initiale

    def prendre_une_carte_pioche(self):
        if len(self.jeu) <= 0:
            raise FinDuneManche
        premiere_carte = self.jeu.pop(0)
        return premiere_carte

    def debut_jeu(self):
        self.distribuer_mains()
    ...


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Exemples de coups valides :
Can you write Python code for it?

valide_le_coup([Carte(4, coeur)])

valide_le_coup([Carte(4, coeur), Carte(5, coeur)])

valide_le_coup([Carte(4, coeur), Carte(5, coeur), Carte(3, coeur)])

valide_le_coup([Carte(4, coeur), Carte(5, coeur), Carte(3, coeur), Carte(2, coeur), Carte(6, coeur)])

valide_le_coup([Carte(4, coeur), Carte(4, carreau)])

valide_le_coup([Carte(4, coeur), Carte(4, carreau), Carte(4, pique)])

valide_le_coup([Carte(4, coeur), Carte(4, carreau), Carte(4, pique), Carte(4, treffle)])


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Fin du jeu
Pour représenter la fin du jeu :
Can you write Python code for it?

class FinDuneManche(Exception):
    pass

class FinDunePartie(Exception):
    pass


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
On va tricher et afficher les cartes avec display(Markdown(...)) plutôt que print, pour les avoir en couleurs.
Can you write Python code for it?

from IPython.display import Markdown
print("[Alice] Cartes en main : [ 6♦,  5♠,  V♣,  V♠,  1♣]")
# avec de la couleurs
display(Markdown("[Alice] Cartes en main : [ 6♦,  5♠,  V♣,  V♠,  1♣]"))


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Pour savoir quoi piocher :
Can you write Python code for it?

exemple_de_visibles = [Carte(11, pique), Carte(10, treffle)]
exemple_de_visibles

def quoi_prendre(visibles):
    return widgets.ToggleButtons(
        options=visibles,
        #index=0,
        description="Prendre quelle carte du sommet ?",
        style=style,
    )

quoi_prendre(exemple_de_visibles)


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Pour valider un coup choisie par une personne :
Can you write Python code for it?

def valide_le_coup(jetees):
    if jetees is None or not (1 <= len(jetees) <= 5):
        return False
    # coup valide si une seule carte !
    elif len(jetees) == 1:
        return True
    # si plus d'une carte
    elif len(jetees) >= 2:
        couleurs_jetees = [carte.couleur for carte in jetees]
        valeurs_jetees  = sorted([carte.valeur for carte in jetees])
        # coup valide si une seule couleur et une suite de valeurs croissantes et continues
        if len(set(couleurs_jetees)) == 1:
            return suite_valeurs_est_continue(valeurs_jetees)
        # coup valide si une seule valeur et différentes couleurs
        elif len(set(valeurs_jetees)) == 1:
            return len(set(couleurs_jetees)) == len(couleurs_jetees)
        return False


I am working on the file "Simulations du jeu de carte Jap-Jap.ipynb".
The first task is:
Valider un coup
Pour savoir si une suite de valeurs est bien continue :
Can you write Python code for it?

def suite_valeurs_est_continue(valeurs):
    vs = sorted(valeurs)
    differences = [ vs[i + 1] - vs[i] for i in range(len(vs) - 1) ]
    return all([d == 1 for d in differences])

suite_valeurs_est_continue([5, 6, 7])
suite_valeurs_est_continue([5, 7, 8])


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Adding boundary conditions
Next, we need to add some boundary conditions to the simulation. By default, OpenPNM assumes zero flux for the boundary pores.
Can you write Python code for it?

inlet  = net.pores('left')
outlet = net.pores(['right', 'top', 'bottom'])
ad.set_value_BC(pores=inlet, values=100.0)
ad.set_value_BC(pores=outlet, values=0.0)


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Adding geometry
Next, we need to add a geometry to the generated network. A geometry contains information about size of the pores/throats in a network. OpenPNM has tons of prebuilt geometries that represent the microstructure of different materials such as Toray090 carbon papers, sand stone, electrospun fibers, etc. For now, we stick to a sample geometry called StickAndBall that assigns random values to pore/throat diameters.
Can you write Python code for it?

geom = op.geometry.StickAndBall(network=net, pores=net.Ps, throats=net.Ts)


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Adding phase
Next, we need to add a phase to our simulation. A phase object(s) contain(s) thermophysical information about the working fluid(s) in the simulation. OpenPNM has tons of prebuilt phases as well! For this simulation, we use air as our working fluid.
Can you write Python code for it?


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Adding physics
Finally, we need to add a physics. A physics object contains information about the working fluid in the simulation that depend on the geometry of the network. A good example is diffusive conductance, which not only depends on the thermophysical properties of the working fluid, but also depends on the geometry of pores/throats.
Can you write Python code for it?

phys_air = op.physics.Standard(network=net, phase=air, geometry=geom)


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Heatmap
Well, it's hard to make sense out of a bunch of numbers! Let's visualize the results. Since the network is 2d, we can simply reshape the results in form of a 2d array similar to the shape of the network and plot the heatmap of it using matplotlib.
Can you write Python code for it?

print('Network shape:', net._shape)
c2d = c.reshape((net._shape))

import matplotlib.pyplot as plt
plt.imshow(c2d[0,:,:])
plt.title('Concentration (mol/m$^3$)')
plt.colorbar()


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
It is essential that you attach the results from StokesFlow (i.e. pressure field) to the corresponding phase, since the results from any algorithm in OpenPNM are by default only attached to the algorithm object (in this case to sf). Here's how you can update your phase:
Can you write Python code for it?


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Now that we know the quantity for which AdvectionDiffusion was solved, let's take a look at the results:
Can you write Python code for it?


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Performing Stokes flow
Note that the advection diffusion algorithm assumes that velocity field is given. Naturally, we solve Stokes flow inside a pore network model to obtain the pressure field, and eventually the velocity field. Therefore, we need to run the StokesFlow algorithm prior to running our advection diffusion. There's a separate tutorial on how to run StokesFlow in OpenPNM, but here's a simple code snippet that does the job for us.
Can you write Python code for it?

sf = op.algorithms.StokesFlow(network=net, phase=air)
sf.set_value_BC(pores=net.pores('left'), values=200.0)
sf.set_value_BC(pores=net.pores('right'), values=0.0)
sf.run();


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Post processing
When an algorithm is successfully run, the results are attached to the same object. To access the results, you need to know the quantity for which the algorithm was solving. For instance, AdvectionDiffusion solves for the quantity pore.concentration, which is somewhat intuitive. However, if you ever forget it, or wanted to manually check the quantity, you can take a look at the algorithm settings:
Can you write Python code for it?


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
Summary
One of the main applications of OpenPNM is simulating transport phenomena such as Fickian diffusion, advection diffusion, reactive transport, etc. In this example, we will learn how to perform advection diffusion on a Cubic network. The algorithm works fine with every other network type, but for now we want to keep it simple. In OpenPNM, we've implemented 4 different discretization schemes for the advection diffusion:

Upwind
Hybrid
Powerlaw
Exact

Depending on the Peclet regime, the results you get from these schemes might differ. To be on the safe side, either use Powerlaw or the Exact scheme.
Problem setup
Generating network
First, we need to generate a Cubic network. For now, we stick to a 2d network, but you might as well try it in 3d!
Can you write Python code for it?

import openpnm as op
net = op.network.Cubic(shape=[1, 10, 10], spacing=1e-4)


I am working on the file "Simulations/advection_diffusion.ipynb".
The first task is:
set_value_BC applies the so-called "Dirichlet" boundary condition to the specified pores. Note that unless you want to apply a single value to all of the specified pores (like we just did), you must pass a list (or ndarray) as the values parameter.
Running the algorithm
Now, it's time to run the algorithm. This is done by calling the run method attached to the algorithm object.
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Adding phase
Next, we need to add a phase to our simulation. A phase object(s) contain(s) thermophysical information about the working fluid(s) in the simulation. OpenPNM has tons of prebuilt phases as well! For this simulation, we use air as our working fluid.
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Adding physics
Finally, we need to add a physics. A physics object contains information about the working fluid in the simulation that depend on the geometry of the network. A good example is diffusive conductance, which not only depends on the thermophysical properties of the working fluid, but also depends on the geometry of pores/throats.
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Heatmap
Well, it's hard to make sense out of a bunch of numbers! Let's visualize the results. Since the network is 2d, we can simply reshape the results in form of a 2d array similar to the shape of the network and plot the heatmap of it using matplotlib.
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Note that network and phase are required parameters for pretty much every algorithm we add, since we need to specify on which network and for which phase do we want to run the algorithm.
Adding boundary conditions
Next, we need to add some boundary conditions to the simulation. By default, OpenPNM assumes zero flux for the boundary pores.
Can you write Python code for it?

inlet  = net.pores('left')
outlet = net.pores('right')
fd.set_value_BC(pores=inlet, values=1.0)
fd.set_value_BC(pores=outlet, values=0.0)


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Now that we know the quantity for which FickianDiffusion was solved, let's take a look at the results:
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Performing Fickian diffusion
Now that everything's set up, it's time to perform our Fickian diffusion simulation. For this purpose, we need to add the FickianDiffusion algorithm to our simulation. Here's how we do it:
Can you write Python code for it?

fd = op.algorithms.FickianDiffusion(network=net, phase=air)


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Post processing
When an algorithm is successfully run, the results are attached to the same object. To access the results, you need to know the quantity for which the algorithm was solving. For instance, FickianDiffusion solves for the quantity pore.concentration, which is somewhat intuitive. However, if you ever forget it, or wanted to manually check the quantity, you can take a look at the algorithm settings:
Can you write Python code for it?


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
Summary
One of the main applications of OpenPNM is simulating transport phenomena such as Fickian diffusion, advection diffusion, reactive transport, etc. In this example, we will learn how to perform Fickian diffusion on a Cubic network. The algorithm works fine with every other network type, but for now we want to keep it simple.
Problem setup
Generating network
First, we need to generate a Cubic network. For now, we stick to a 2d network, but you might as well try it in 3d!
Can you write Python code for it?

import openpnm as op
net = op.network.Cubic(shape=[1, 10, 10], spacing=1e-5)


I am working on the file "Simulations/fickian_diffusion.ipynb".
The first task is:
set_value_BC applies the so-called "Dirichlet" boundary condition to the specified pores. Note that unless you want to apply a single value to all of the specified pores (like we just did), you must pass a list (or ndarray) as the values parameter.
Running the algorithm
Now, it's time to run the algorithm. This is done by calling the run method attached to the algorithm object.
Can you write Python code for it?


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
Generating the Phases and Physics objects
Now a Phase object is defined along with a corresponding Physics object. On the Phase object, the thermal conductivity is set equal to 1.0 across the whole domain. The Physics object is then assigned a model for the thermal conduction simulation, which is the series_resistors model. This model will utilize the geometry properties we defined above to generate the correct conductances between cells.
Can you write Python code for it?

# Create Phase object and associate with a Physics object
Cu = op.phases.GenericPhase(network=pn)
Cu['pore.thermal_conductivity'] = 1.0  # W/m.K
phys = op.physics.GenericPhysics(network=pn, phase=Cu, geometry=geom)
mod = op.models.physics.thermal_conductance.series_resistors
phys.add_model(propname='throat.thermal_conductance', model=mod)


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
Generating the algorithm objects and running the simulation
The last step in the OpenPNM simulation involves the generation of a Algorithm object and running the simulation.
Can you write Python code for it?

# Setup Algorithm object
alg = op.algorithms.FourierConduction(network=pn)
alg.setup(phase=Cu)
inlets = pn.pores('back_boundary')
outlets = pn.pores(['front_boundary', 'left_boundary', 'right_boundary'])
T_in = 30*sp.sin(sp.pi*pn['pore.coords'][inlets, 1]/5)+50
alg.set_value_BC(values=T_in, pores=inlets)
alg.set_value_BC(values=50, pores=outlets)
alg.run()


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
In this example we are using OpenPNM to calculate the temperature profile on a grid.  In this case each pore is a grid cell and they connect to each other on four sides. The throats are thus set to have the same dimensions as the pores, but a very short length so that the distance between the pores is very low.  Essentially the resistance is all coming from the pores.
Can you write Python code for it?

geom['pore.area'] = Lc**2
geom['pore.diameter'] = Lc
geom['throat.length'] = 1e-25
geom['throat.area'] = Lc**2


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
The analytical solution is computed in Python as well, and the result is the same shape as the network (including the boundary pores).
Can you write Python code for it?

# Calculate analytical solution over the same domain spacing
X = pn['pore.coords'][:, 0]
Y = pn['pore.coords'][:, 1]
soln = 30*sp.sinh(sp.pi*X/5)/sp.sinh(sp.pi/5)*sp.sin(sp.pi*Y/5) + 50
soln = soln[pn.pores('internal')]
soln = sp.reshape(soln, (divs[0], divs[1]))

plt.subplots(1, 1, figsize=(25, 10))
plt.imshow(soln, cmap=plt.cm.plasma)
plt.colorbar()


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
There is one gotcha that must be considered with the boundary pores.  We genererally want these pores to offer no resistance, which means they should have zero length (ie. transport from the pore center to the entrance of the throat is negligible), so we will set these manually:
Can you write Python code for it?


I am working on the file "Simulations/match_analytical_temperature_profile.ipynb".
The first task is:
This is the last step usually required in a OpenPNM simulation. The algorithm was run, and now the simulation data obtained can be analyzed. For illustrative purposes, the results obtained using OpenPNM shall be compared to an analytical solution of the problem in the following.
First let's rehape the 'pore.temperature' array into the shape of the network while also extracting only the internal pores to avoid showing the boundaries.
Can you write Python code for it?

import matplotlib.pyplot as plt
sim = alg['pore.temperature'][pn.pores('internal')]
temp_map = sp.reshape(a=sim, newshape=divs)
plt.subplots(1, 1, figsize=[25, 10])
plt.imshow(temp_map, cmap=plt.cm.plasma)
plt.colorbar()


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
Add Geometrical Properties to the Large Domain
Can you write Python code for it?

geom_lg['pore.diameter'] = spacing_lg*sp.rand(combo_net.num_pores('large'))
geom_lg.add_model(propname='pore.area',
                  model=gm.pore_area.sphere)
geom_lg.add_model(propname='throat.diameter',
                  model=mm.misc.from_neighbor_pores,
                  pore_prop='pore.diameter', mode='min')
geom_lg.add_model(propname='throat.area',
                  model=gm.throat_area.cylinder)
geom_lg.add_model(propname='throat.length',
                  model=gm.throat_length.straight)


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
Create Phase and Physics Objects
Can you write Python code for it?

air = op.phases.Air(network=combo_net, name='air')
phys_lg = op.physics.GenericPhysics(network=combo_net, geometry=geom_lg, phase=air)
phys_sm = op.physics.GenericPhysics(network=combo_net, geometry=geom_sm, phase=air)


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
For the small layer we've used a normal diffusive conductance model, which when combined with the diffusion coefficient of air will be equivalent to open-air diffusion.  If we want the small layer to have some tortuosity we must account for this:
Can you write Python code for it?

porosity = 0.5
tortuosity = 2
phys_sm['throat.diffusive_conductance'] *= (porosity/tortuosity)


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
Note that this extra line is NOT a pore-scale model, so it will be over-written when the phys_sm object is regenerated.
Add a Reaction Term to the Small Layer
A standard n-th order chemical reaction is $ r=k \cdot x^b $, or more generally: $ r = A_1 \cdot x^{A_2} + A_3 $.  This model is available in OpenPNM.Physics.models.generic_source_terms, and we must specify values for each of the constants.
Can you write Python code for it?

# Set Source Term
air['pore.A1'] = 1e-10  # Reaction pre-factor
air['pore.A2'] = 2  # Reaction order
air['pore.A3'] = 0  # A generic offset that is not needed so set to 0
phys_sm.add_model(propname='pore.reaction',
                  model=pm.generic_source_term.power_law,
                  A1='pore.A1', A2='pore.A2', A3='pore.A3',
                  X='pore.mole_fraction',
                  regen_mode='deferred')


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
Perform a Diffusion Calculation
Can you write Python code for it?

Deff = op.algorithms.ReactiveTransport(network=combo_net, phase=air)
Ps = combo_net.pores(['large', 'right'], mode='intersection')
Deff.set_value_BC(pores=Ps, values=1)
Ps = combo_net.pores('small')
Deff.set_source(propname='pore.reaction', pores=Ps)
Deff.settings['conductance'] = 'throat.diffusive_conductance'
Deff.settings['quantity'] = 'pore.mole_fraction'
Deff.run()


I am working on the file "Simulations/mixed_continuum_and_pore_network.ipynb".
The first task is:
Visualize the Concentration Distribution
Save the results to a VTK file for visualization in Paraview:
Can you write Python code for it?


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Define the Pore-Scale Physics
For this simulation the standard physics object can be used as it contains capillary pressure for use in the OrdinaryPercolation algorithm and diffusive conductance for use in the FickianDiffusion algorithm.
Can you write Python code for it?

phys_air = openpnm.physics.Standard(network=pn, phase=air, geometry=geom)
phys_water = openpnm.physics.Standard(network=pn, phase=water, geometry=geom)


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Finally plot the results:
Can you write Python code for it?

[lt.ioff()  # Turn off automatic plotting
fig = plt.figure()
ax = fig.gca()
plots=[]
plots.append(plt.plot(sat,rel_diff_air_x,'^-r',label='Dra_x'))
plots.append(plt.plot(sat,rel_diff_air_y,'^-g',label='Dra_y'))
plots.append(plt.plot(sat,rel_diff_air_z,'^-b',label='Dra_z'))
plots.append(plt.plot(sat,rel_diff_water_x,'*-r',label='Drw_x'))
plots.append(plt.plot(sat,rel_diff_water_y,'*-g',label='Drw_y'))
plots.append(plt.plot(sat,rel_diff_water_z,'*-b',label='Drw_z'))
h = plt.xlabel('Liquid Water Saturation')
h = plt.ylabel('Relative Diffusivity')
handles, labels = ax.get_legend_handles_labels()
h = ax.legend(handles, labels,loc=1)
box = ax.get_position()
h = ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])
h = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Here we have selected half of the boundary pores at the bottom of the domain as inlets for the percolation Algorithm. OrdinaryPercolation has a helpful plotting function which displays the saturation of the invading phase (volume fraction of the pore space) vs. capillary pressure: OP_1.plot_drainage_curve(). The red line is pore saturation, blue is throat saturation and green is total saturation.

Note :  OpenPNM's Postprocessing module also has the ability to plot drainage curves and is suitable for use with the InvasionPercolation algorithm too.

Run a Fickian Diffusion Algorithm for each step of the invasion process
We now need to model how the presence of the phases affects the diffusive conductivity of the network. Currently the Physics objects have a property called throat.diffusive_conductance but this model does not account for the occupancy of each phase and assumes that the phase occupies every pore-throat-pore conduit. OpenPNM has a number of multiphase models including a conduit conductance that multiplies the single phase conductance by a factor (default 0.000001) when the phase associated with the physics object is not present. The model has a mode which defaults to 'strict' which applies the conductivity reduction if any one of the connected pores or connecting throat is unoccupied.
Can you write Python code for it?

import openpnm.models.physics as pm
phys_air.add_model(model=pm.multiphase.conduit_conductance,
                   propname='throat.conduit_diffusive_conductance',
                   throat_conductance='throat.diffusive_conductance')
phys_water.add_model(model=pm.multiphase.conduit_conductance,
                     propname='throat.conduit_diffusive_conductance',
                     throat_conductance='throat.diffusive_conductance')


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Next create a Network object with a cubic topology and lattice spacing of 25 microns and add boundary pores
Can you write Python code for it?

pn = openpnm.network.Cubic(shape=[10, 10, 10], spacing=4.0e-5)
pn.add_boundary_pores()
proj = pn.project


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Now for each invasion step we cycle through the principle directions and create FickianDiffusion objects for each phase and calculate the effective diffusivity.
Can you write Python code for it?

for Pc in np.unique(OP_1['pore.inv_Pc']):
    OP_1.return_results(Pc=Pc)
    phys_air.regenerate()
    phys_water.regenerate()
    this_sat = 0
    this_sat += np.sum(pn["pore.volume"][water["pore.occupancy"] == 1])
    this_sat += np.sum(pn["throat.volume"][water["throat.occupancy"] == 1])
    sat.append(this_sat)
    for bound_increment in range(len(bounds)):
        BC1_pores = pn.pores(labels=bounds[bound_increment][0]+'_boundary')
        BC2_pores = pn.pores(labels=bounds[bound_increment][1]+'_boundary')
        FD_1 = OpenPNM.Algorithms.FickianDiffusion(network=pn, phase=air)
        FD_1.set_boundary_conditions(bctype='Dirichlet', bcvalue=0.6,
                                     pores=BC1_pores)
        FD_1.set_boundary_conditions(bctype='Dirichlet', bcvalue=0.2,
                                     pores=BC2_pores)
        FD_1.run(conductance='conduit_diffusive_conductance')
        eff_diff = FD_1.calc_eff_diffusivity()
        diff_air[str(bound_increment)].append(eff_diff)
        FD_2 = OpenPNM.Algorithms.FickianDiffusion(network=pn, phase=water)
        FD_2.set_boundary_conditions(bctype='Dirichlet', bcvalue=0.6,
                                     pores=BC1_pores)
        FD_2.set_boundary_conditions(bctype='Dirichlet', bcvalue=0.2,
                                     pores=BC2_pores)
        FD_2.run(conductance='conduit_diffusive_conductance')
        eff_diff = FD_2.calc_eff_diffusivity()
        diff_water[str(bound_increment)].append(eff_diff)
        workspace.purge_object(FD_1)
        workspace.purge_object(FD_2)


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
Relative Diffusivity
Generating the Network, adding Geometry and creating Phases
This example shows you how to calculate a transport property relative to the saturation of the domain by a particular phase. In this case the property is the diffusivity of air relative to the saturation of water. Start by importing OpenPNM and some other useful packages:
Can you write Python code for it?

import openpnm
import numpy as np
import matplotlib.pyplot as plt


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
The Toray090 Geometry is a predefined class that applies Weibull distributed pore and throat sizes to the internal pores and is named after the Toray carbon paper gas diffusion layer commonly used in fuel cells.  The Boundary class is predefined with properties suitable for boundaries such as 0 volume and length.
We must also create the Phase objects, for our purposes the standard air and water phase classes provided are fine:
Can you write Python code for it?

air = openpnm.phases.Air(network=pn, name='air')
water = openpnm.phases.Water(network=pn, name='water')


I am working on the file "Simulations/relative_diffusivity.ipynb".
The first task is:
The return_results method updates the two Phase objects with the occupancy at the given capillary pressure (Pc). The Physics objects are then regenerated to re-calculate the conduit_diffusive_conductance property.

Note :  Six Diffusion algorithm objects could have been created outside the loop and then run over and over with the updated conductance values and this would possibly save some computational time but is not as nice to code. Instead the objects are purged and redefined with updated boundary pores inside another for loop.

Plot the Relative Diffusivity Curves for each direction and Phase
Now tidy up the data converting them into Numpy arrays for easy plotting and manipulation and normalize the results by the single phase values:
Can you write Python code for it?

sat=np.asarray(sat)
sat /= tot_vol
rel_diff_air_x    =  np.asarray(diff_air['0'])
rel_diff_air_x   /=  rel_diff_air_x[0]
rel_diff_air_y    =  np.asarray(diff_air['1'])
rel_diff_air_y   /=  rel_diff_air_y[0]
rel_diff_air_z    =  np.asarray(diff_air['2'])
rel_diff_air_z   /=  rel_diff_air_z[0]
rel_diff_water_x  =  np.asarray(diff_water['0'])
rel_diff_water_x /=  rel_diff_water_x[-1]
rel_diff_water_y  =  np.asarray(diff_water['1'])
rel_diff_water_y /=  rel_diff_water_y[-1]
rel_diff_water_z  =  np.asarray(diff_water['2'])
rel_diff_water_z /=  rel_diff_water_z[-1]


I am working on the file "Simulator Notebook.ipynb".
The first task is:
Agent-Based Model to Dissect Contribution of Host Immunity and Contact Structure to Influenza Reassortment

Eric J. Ma
Runstadler Lab Meeting
If you want to follow along: https://github.com/ericmjl/reassortment-simulator

Reassortment

The reticulate evolutionary mechanism for the influenza virus.
Implicated in all past human pandemics.
Quantitatively important for host switches. (we're really excited about this finding!)

Scientific Questions

How does host contact structure affect the ability of a virus to shuffle its genome?
How does host immunity affect the necessity of a virus to shuffle its genome?
How does fitness of the virus within a host affect the ability of the virus to reassort? @Wendy
How does waning immunity affect the necessity of the virus to reassort? @Jon

Agent-Based Simulation Setup

Two types of agents: Host and Virus.
Interaction between hosts:
Homophily: degree of preference for interaction with the same color.
Transmission: passing on of virus.

Interaction between viruses:
Reassortment: exchange of genes between viruses.

Interaction between host and virus:

Host can gain immunity to viruses over time.
Virus has host preference of same color on one segment.

Host:

colour
immunity
viruses
expiry_time
alive_time

Virus:

seg1color
seg2color
infection_time
expiry_time

Simulation Setup
In the following blocks of code, we will look at how the simulation will run.
Initialization
1000 hosts: 500 red, 500 blue.
Can you write Python code for it?

hosts = []
n_hosts = 1000
for i in range(n_hosts):
    if i < n_hosts / 2:
        hosts.append(Host(color='blue'))
    else:
        hosts.append(Host(color='red'))


I am working on the file "Simulator Notebook.ipynb".
The first task is:
Result: Contact Frequency
Can you write Python code for it?

plt.plot(data['n_contacts'], color='olive', label='contacts')
plt.title('Contact Frequency')
np.where(np.array(data['n_contacts']) >= 1)[0]

import pandas as pd
pd.DataFrame(data)


I am working on the file "Simulator Notebook.ipynb".
The first task is:
Result: Viral Dynamics
Can you write Python code for it?

# Reassortment successful in establishing infection or not?
plt.plot(data['n_red_virus'], color='red', label='red')
plt.plot(data['n_blue_virus'], color='blue', label='blue')
plt.plot(data['n_original'], color='black', label='original')
plt.plot(data['n_mixed'], color='purple', label='mixed')
plt.ylabel('Number of  Viruses')
plt.xlabel('Time Step')
plt.title('Viruses')
plt.legend()

np.array_equal(np.array(data['n_mixed']), np.zeros(100))

np.where(np.array(data['n_mixed']) == np.max(data['n_mixed']))[0] - np.where(np.array(data['n_original']) == np.max(data['n_original']))[0]


I am working on the file "Simulator Notebook.ipynb".
The first task is:
Run Simulation!
Can you write Python code for it?

# Run simulation
for t in range(n_timesteps):
    # First part, clear up old infections.
    for h in hosts:
        h.increment_time()
        h.remove_old_viruses()
        h.remove_immune_viruses()

    # Step to replicate viruses present in hosts.
    infected_hosts = [h for h in hosts if h.is_infected()]
    for h in infected_hosts:
        if bernoulli.rvs(p_replicate): # we probabilistically allow replication to occur
            h.replicate_virus()

    # Step to transmit the viruses present in hosts.
    infected_hosts = [h for h in hosts if h.is_infected()]
    num_contacts = 0
    for h in infected_hosts:
        same_color = bernoulli.rvs(p_contact)
        if same_color:
            new_host = choice([h2 for h2 in hosts if h2.color == h.color])
            num_contacts += 0
        else:
            new_host = choice([h2 for h2 in hosts if h2.color != h.color])
            num_contacts += 1
        virus = h.viruses[-1] # choose the newly replicated virus every time.

        # Determine whether to transmit or not.
        p_transmit = 1
        ### First, check immunity ###
        if virus.seg1color in new_host.immunity:
            p_transmit = p_transmit * p_immune
        elif virus.seg1color not in new_host.immunity:
            pass

        ### Next, check seg1.
        if virus.seg1color == new_host.color:
            p_transmit = p_transmit * p_same_color
        else:
            p_transmit = p_transmit * p_diff_color

        ### Finally, check seg2.
        if virus.seg2color == new_host.color:
            p_transmit = p_transmit * p_same_color
        else:
            p_transmit = p_transmit * p_diff_color

        # Determine whether to transmit or not, by using a Bernoulli trial.
        transmit = bernoulli.rvs(p_transmit)

        # Perform transmission step
        if transmit:
            new_host.viruses.append(virus)
#             # Capture data in the summary graph.
#             if virus.is_mixed():
#                ...


I am working on the file "Simulator/Concepts/Inverse Transform Sampling.ipynb".
The first task is:
Below, first we compute probabilities of flux. Afterwards, we compute the cumulative probability.
Can you write Python code for it?

prob = fluxes/float(sum(fluxes))
cum_prob = np.cumsum(prob)
cum_prob


I am working on the file "Simulator/Concepts/PowerLaw Spectrum.ipynb".
The first task is:
Start with B=1 to get a flicker noise distribution.
Can you write Python code for it?

f = simulate(1)
plt.plot(np.real(f))
plt.xlabel('Time')
plt.ylabel('Counts')
plt.title('Recovered LightCurve with B=1')


I am working on the file "Simulator/Concepts/Simulate Event Lists With Inverse CDF.ipynb".
The first task is:
Let us start with a standard light curve simulation with the Timmer & Koenig method:
Can you write Python code for it?

from astropy.modeling import models

pds_model = \
    models.PowerLaw1D(x_0=1, alpha=1, amplitude=1)

nyq = 100.
freq = np.linspace(0, nyq, 1000)[1:]

pds_shape = pds_model(freq)
mean = 10
rms = 0.3

dt = 0.5 / nyq

flux = timmerkoenig(pds_shape, mean, rms)
times = dt * np.arange(flux.size)

plt.plot(times, flux)


I am working on the file "Simulator/Concepts/Simulate Event Lists With Inverse CDF.ipynb".
The first task is:
Simulating event times with the inverse CDF method
Given a positive-definite light curve (generated, e.g., with the method by Timmer & Koenig), we treat it as a probability distribution: we calculate the cumulative distribution function by calculating its cumulative sum and normalizing to 1. Then, we generate random numbers uniformly distributed between 0 and 1 (horizontal lines) and take the event times at the corresponding values of the CDF (vertical lines).
Can you write Python code for it?

from scipy.interpolate import interp1d

def cdf_from_lc(lc, dt):
    cdf = np.cumsum(lc)
    cdf = np.concatenate([[0], cdf])
    cdf /= cdf.max()
    return cdf

# cdf_times = np.concatenate([[0], dt / 2 + time])
cdf_values = cdf_from_lc(flux, dt)
cdf_times = np.arange(cdf_values.size) * dt

cdf_inverse = interp1d(cdf_values, cdf_times)

plt.plot(times, flux / flux.max(), color="grey", label="Light curve")
plt.plot(cdf_times, cdf_values, color="k", label="CDF")

for prob_val in np.linspace(0, 1, 100):
    time = cdf_inverse(prob_val)
    plt.plot([0, time], [prob_val, prob_val], color="r", lw=0.3)
    plt.plot([time, time], [0, prob_val], color="r", lw=0.3)

plt.xlabel("Time")
plt.ylabel("Probability")

plt.ylim([0, 1])
plt.xlim([0, 10])
plt.legend(loc="lower right");
plt.tight_layout()
plt.savefig("CDF_lc.jpg")


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Calculate time lag.
Can you write Python code for it?

lag = np.angle(cross.cs)/ (2 * np.pi * cross.freq)


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Compute lags and cutoffs.
Can you write Python code for it?

lags = [np.angle(cross.cs)/ (2 * np.pi * cross.freq) for cross in cross_spectrums]


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Create impulse responses for all energy channels.
Can you write Python code for it?

h_zeros = [np.zeros(int(i/lc.dt)) for i in energies]
responses = [np.append(h, 1) for h in h_zeros]

delays = [int(i/lc.dt) for i in energies]
outputs = [signal.fftconvolve(s, h)[d:-d] for h,d in zip(responses,delays)]
s_mods = [s[d:] for d in delays]


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Define variability signal.
Can you write Python code for it?

lc = sampledata.sample_data()
s = lc.counts


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Energy Dependence
With same intensity and varying position
To create different lags for different energy channels, we create delta impulses of same intensity at different positions.
Can you write Python code for it?


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Find cross spectrum and compute lags.
Can you write Python code for it?

cross = Crossspectrum(lc1, lc2)
cross = cross.rebin(0.0075)
lag = np.angle(cross.cs)/ (2 * np.pi * cross.freq)


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Find output signal by taking convolution of variability signal and impulse response.
Can you write Python code for it?

output = signal.fftconvolve(s, h)
# To make two counts of equal size, remove last 'delay' entries and avoid first zeros
output = output[delay:-delay]
s_mod = s[delay:]


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Form light curves.
Can you write Python code for it?

time = lc.time[delay:]
lc1 = Lightcurve(time, s_mod)
lc2 = Lightcurve(time, output)


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Get cutoff points for all energy channels.
Can you write Python code for it?

v_cutoffs = [1.0/(2*energy) for energy in energies]
h_cutoffs = [lag[int((v_cutoff-0.0075)*1/0.0075)] for lag, v_cutoff in zip(lags, v_cutoffs)]


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Lag-frequency Spectrum
Simple Delta Impulse Response
Define a delta impulse response with a delay of 10.
Can you write Python code for it?

delay = int(10/lc.dt)
h_zeros = np.zeros(delay)
h = np.append(h_zeros, 1)


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Make light curves.
Can you write Python code for it?

t_mods = [lc.time[d:] for d in delays]
lc_input = [Lightcurve(t_mod, s_mod) for t_mod, s_mod in zip(t_mods,s_mods)]
lc_output = [Lightcurve(t_mod, output) for t_mod, output in zip(t_mods,outputs)]

cross_spectrums = [Crossspectrum(lc1, lc2).rebin(0.0075) for lc1,lc2 in zip(lc_input,lc_output)]


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Make lightcurves using Lightcurve class.
Can you write Python code for it?


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Plot lag.
Can you write Python code for it?

plt.figure()

# Plot lag-frequency spectrum.
plt.plot(cross.freq, lag, 'r')

# Find cutoff points
v_cutoff = 1.0/(2*10.0)
h_cutoff = lag[int((v_cutoff-0.0075)*1/0.0075)]

plt.axvline(v_cutoff, color='g',linestyle='--')
plt.axhline(h_cutoff, color='g', linestyle='-.')

# Define axis
plt.axis([0,0.2,-15,15])
plt.show()


I am working on the file "Simulator/Concepts/Simulator.ipynb".
The first task is:
Plot results.
Can you write Python code for it?

plt.figure()

# Plot lag-frequency spectrum.
plt.plot(cross.freq, lag, 'r')

# Define the x-position of vertical line
v_cutoff = 1.0/(2*t2)
h_cutoff = lag[int((v_cutoff-0.0075)*1/0.0075)]

plt.axvline(v_cutoff, color='g', linestyle='--')
plt.axhline(h_cutoff, color='g', linestyle='-.')

# Define axis
plt.axis([0,0.2,-10,10])
plt.show()


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Analysis
Compute crossspectrum.
Can you write Python code for it?


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Calculate time lag.
Can you write Python code for it?


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Compute cross-spectrum for each channel.
Can you write Python code for it?

cross = [Crossspectrum(var, lc).rebin(0.005) for lc in sim.get_channels(['3.5-4.5', '4.5-5.5'])]


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Finally, simulate a filtered light curve. Here, filtered means that the initial lag delay portion is cut.
Can you write Python code for it?

lc = sim.simulate(var.counts, s_ir)

plt.plot(lc.time, lc.counts)
plt.plot(var.time, var.counts)


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Get cut-off points.
Can you write Python code for it?

v_cuts = [1.0/(2*d) for d in delays]
h_cuts = [lag[int((v_cutoff-0.005)*1/0.005)] for lag, v_cut in zip(lags, v_cuts)]


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Import relevant stingray libraries.
Can you write Python code for it?

from stingray import Lightcurve, Crossspectrum, sampledata
from stingray.simulator import simulator, models


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Initializing
Instantiate a simulator object and define a variability signal.
Can you write Python code for it?

var = sampledata.sample_data()

# Beware: set tstart here, or nothing will work!
sim = simulator.Simulator(N=1024, mean=0.5, dt=0.125, rms=0.4, tstart=var.tstart)


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Now, we create two energy channels to simulate light curves for these two impulse responses.
Can you write Python code for it?

sim.simulate_channel('3.5-4.5', var, h1)
sim.simulate_channel('4.5-5.5', var, h2)


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Plot lag-frequency spectrums.
Can you write Python code for it?

plt.figure()
plots = []
colors = ['r','g']
energies = ['3.5-4.5 keV', '4.5-5.5 keV']

# Plot lag-frequency spectrum
for i in range(0,len(lags)):
    plots += plt.plot(cross[i].freq, lags[i], colors[i], label=energies[i])
    plt.axvline(v_cuts[i],color=colors[i],linestyle='--')
    plt.axhline(h_cuts[i], color=colors[i], linestyle='-.')

# Define axes and add labels
plt.axis([0,0.2,-20,20])
plt.legend()
plt.xlabel('Frequencies (Hz)')
plt.ylabel('Lags')
plt.title('Energy Dependent Frequency-lag Spectrum')
plt.show()


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Plot lag.
Can you write Python code for it?

plt.figure()

# Plot lag-frequency spectrum.
plt.plot(cross.freq, lag, 'r')

# Find cutoff points
v_cutoff = 1.0/(2*delay)
h_cutoff = lag[int((v_cutoff-0.0050)*1/0.0050)]

plt.axvline(v_cutoff, color='g',linestyle='--')
plt.axhline(h_cutoff, color='g', linestyle='-.')

# Define axis
plt.axis([0,0.2,-20,20])
plt.xlabel('Frequency (Hz)')
plt.ylabel('Lag')
plt.title('Lag-frequency Spectrum')
plt.show()


I am working on the file "Simulator/Lag Analysis.ipynb".
The first task is:
Rebin the crosss-spectrum for ease of visualization.
Can you write Python code for it?


I am working on the file "Simulator/Power Spectral Models.ipynb".
The first task is:
Import pyplot from matplotlib for plotting light curves.
Can you write Python code for it?

from matplotlib import pyplot as plt
%matplotlib inline


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
(ii) Using user-defined model
Light curve can also be simulated using a user-defined spectrum.
Can you write Python code for it?

w = np.fft.rfftfreq(sim.N, d=sim.dt)[1:]
spectrum = np.power((1/w),2/2)
plt.plot(spectrum)

lc = sim.simulate(spectrum)
plt.plot(lc.counts)


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
A more realistic impulse response mimicking black hole dynamics can be created using relativistic_ir(). Its arguments are: primary peak time, secondary peak time, end time, primary peak value, secondary peak value, rise slope and decay slope. These paramaters are set to appropriate values by default.
Can you write Python code for it?

r_ir = sim.relativistic_ir()
r_ir = sim.relativistic_ir(t1=3, t2=4, t3=10, p1=1, p2=1.4, rise=0.6, decay=0.1)
plt.plot(r_ir)


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Above command assigns a light curve of random-walk distribution to energy channel of range 3.5-4.5. Notice, that simulate_channel() has the same parameters as simulate() with the exception of first parameter that describes the energy range of channel.
To get a light curve belonging to a specific channel, get_channel() is used.
Can you write Python code for it?

lc = sim.get_channel('3.5-4.5')
plt.plot(lc.counts)


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Finally, some times, we do not need to include lag delay portion in the output light curve. This can be done by changing the final function parameter to filtered.
Can you write Python code for it?

lc_new = sim.simulate(sample, r_ir, 'filtered')


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Light Curve Simulation
There are multiple way to simulate a light curve:

Using power-law spectrum
Using user-defined model
Using pre-defined models (lorenzian etc)
Using impulse response

(i) Using power-law spectrum
By passing a beta value as a function argument, the shape of power-law spectrum can be defined. Passing beta as 1 gives a flicker-noise distribution.
Can you write Python code for it?

lc = sim.simulate(1)
plt.errorbar(lc.time, lc.counts, yerr=lc.counts_err)


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Now, that the impulse response is ready, simulate() method can be called to produce a light curve.
Can you write Python code for it?


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Passing beta as 2, gives random-walk distribution.
Can you write Python code for it?

lc = sim.simulate(2)

plt.errorbar(lc.time, lc.counts, yerr=lc.counts_err)

lc_pois = sim_pois.simulate(2)
plt.plot(lc_pois.time, lc_pois.counts)
plt.plot(lc_pois.time, lc_pois.smooth_counts)


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Reading/Writing
Simulator object can be saved or retrieved at any time using pickle.
Can you write Python code for it?


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
Since, the new light curve is produced by the convolution of original light curve and impulse response, its length is truncated by default for ease of analysis. This can be changed, however, by supplying an additional parameter full.
Can you write Python code for it?

lc_new = sim.simulate(sample, r_ir, 'full')


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
To learn more about what the lags look like in practice, head to the lag analysis notebook.
Channel Simulation
Here, we demonstrate simulator's functionality to simulate light curves independently for each channel. This is useful, for example, when dealing with energy dependent impulse responses where you can create a new channel for each energy range and simulate.
In practical situations, different channels may have different impulse responses and hence, would react differently to incoming light curves. To account for this, there is an option to simulate light curves and add them to corresponding energy channels.
Can you write Python code for it?


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
We also import some sample data for later use.
Can you write Python code for it?


I am working on the file "Simulator/Simulator Tutorial.ipynb".
The first task is:
When simulating Poisson-distributed light curves, a smooth_counts attribute is added to the light curve, containing the original smooth light curve, for debugging purposes.
Can you write Python code for it?

lc_pois = sim_pois.simulate(1)
plt.plot(lc_pois.time, lc_pois.counts)
plt.plot(lc_pois.time, lc_pois.smooth_counts)


I am working on the file "SimultaneousEquation.ipynb".
The first task is:
この結果から古典的最小二乗法による推定式をまとめると、
[供給関数]
$\hat Q_{i} = 4.8581 + 1.5094 P_{i} - 1.5202 E_{i} $
[需要関数]
$\hat Q_{i} = 16.6747 - 0.9088 P_{i} - 1.0369 A_{i}$
となる。
しかし、説明変数Pと誤差の間に関係があるため、同時方程式バイアスが生じてしまいます。
そこで、以下では同時方程式体系の推定法として代表的な二段階最小二乗法を用いて推定し直します。
Can you write Python code for it?

# 外生変数設定
inst = data[[ 'A', 'E']].as_matrix()
inst = sm.add_constant(inst)

# 2SLSの実行(Two Stage Least Squares: 二段階最小二乗法)
model1 = IV2SLS(Y, X1, inst)
model2 = IV2SLS(Y, X2, inst)
result1 = model1.fit()
result2 = model2.fit()

print(result1.summary())

print(result2.summary())


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Autocorrelation
Display the Autocorrelation plot of your transformed data.
Choose the start and end time in seconds. to capture whole time series, use end = -1. May be slow
key = 'Mean1'
start = 0
end = 10

Autocorrelation Plot
Can you write Python code for it?

#autocorrelation
key = 'Mean1'
start = 0 #seconds, where you want the slice to begin
end = 1 #seconds, where you want the slice to end.
autocorrelation_plot(Data['trans'][key][start:end])
plt.show()


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Begin User Input
For help, check out the wiki: Protocol
Or the video tutorial: Coming Soon!
Load Data File
Use the following block to change your settings. You must use this block.
Here are some helpful information about the loading settings:
Settings['folder']= Full File Path for data input:
Designate the path to your file to load. It can also be the relative path to the folder where this notebook is stored. This does not include the file itself.
Mac OSX Example: '/Users/MYNAME/Documents/bass'
Microsoft Example: r'C:\\Users\MYNAME\Documents\bass'

Settings['Label']= File name:
This is the name of your data file. It should include the file type. This file should NOT have a header and the first column must be time in seconds. Note: This file name will also appear as part of the output files names.
'rat34_ECG.txt'

Settings['Output Folder'] = Full File Path for data output: Designate the location of the folder where you would like the folder containing your results to go. If the folder does not exist, then it will be created. A plots folder, called 'plots' will be created inside this folder for you if it does not already exist.
Mac OSX Example: '/Users/MYNAME/Documents/output'
Microsoft Example: r'C:\\Users\MYNAME\Documents\output'

Loading a file
WARNING All text input should be raw, especially if in Windows.
r'string!'
r"string!"

Other Settings
For more information about other settings, go to:
Transforming Data
Baseline Settings
Peak Detection Settings
Burst Detection Settings
Can you write Python code for it?

#initialize new file
Data = {}
Settings = {}
Results ={}

############################################################################################
#manual Setting block
Settings['folder']= r"/Users/abigaildobyns/Desktop"
Settings['Label'] = r'rat34_ECG.txt'
Settings['Output Folder'] = r"/Users/abigaildobyns/Desktop/demo"

#transformation Settings
Settings['Absolute Value'] = True #Must be True if Savitzky-Golay is being used

Settings['Bandpass Highcut'] = r'none' #in Hz
Settings['Bandpass Lowcut'] = r'none' #in Hz
Settings['Bandpass Polynomial'] = r'none' #integer

Settings['Linear Fit'] = False #between 0 and 1 on the whole time series
Settings['Linear Fit-Rolling R'] = 0.75 #between 0 and 1
Settings['Linear Fit-Rolling Window'] = 1000 #window for rolling mean for fit, unit is index not time
Settings['Relative Baseline'] = 0 #default 0, unless data is normalized, then 1.0. Can be any float

Settings['Savitzky-Golay Polynomial'] = 4 #integer
Settings['Savitzky-Golay Window Size'] = 251 #must be odd. units are index not time

#Baseline Settings
Settings['Baseline Type'] = r'static' #'linear', 'rolling', or 'static'
#For Linear
Settings['Baseline Start'] = 0.0 #start time in seconds
Settings['Baseline Stop'] = 1.0 #end time in seconds
#For Rolling
Settings['Rolling Baseline Window'] = r'none' #leave as 'none' if linear or static

#Peaks
Settings['Delta'] = 0.25
Settings['Peak Minimum'] = -1 #amplitude value
Settings['Peak Maximum'] = 1 #amplitude value

#Bursts
Settings['Burst Area'] = False #calculate burst area
Settings['Exclude Edges'] = True #False to keep edges, True to discard them
Settings['Inter-event interval minimum (seconds)'] = 0.0100 #only for bursts, not for peaks
Settings['Maximum Burst Duration (s)'] = 10
Settings['Minimum Burst Duration (s)'] = 0
Settings['Minimum Peak Number'] = 1 #minimum number of peaks/burst, integer
Settings['Threshold']= 0.15 #linear: proportion of baseline.
                           #static: literal value.
                           #rolling, linear ammount...


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Descriptive Statistics
Moving/Sliding Averages, Standard Deviation, and Count
Generates the moving mean, standard deviation, and count for a given measurement across all columns of the Data in the form of a DataFrame (displayed as a table).
Saves out the dataframes of these three results automatically with the window size in the name as a .csv.
If meas == 'All', then the function will loop and produce these tables for all measurements.
event_type = 'Peaks'
meas = 'all'
window = 30

Moving Stats
Can you write Python code for it?

#Moving Stats
event_type = 'Peaks'
meas = 'all'
window = 30 #seconds
Results = moving_statistics(event_type, meas, window, Data, Settings, Results)


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Display Event Detection Tables
Display Settings used for analysis
Can you write Python code for it?


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Display Summary Results for Peaks
Can you write Python code for it?

#grouped summary for peaks
Results['Peaks-Master'].groupby(level=0).describe()


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Frequency Plot
Use this block to plot changes of any measurement over time. Does not support 'all'. Example:
event_type = 'Peaks'
meas = 'Intervals'
key = 'Mean1'

Frequency Plot
Can you write Python code for it?

event_type = 'Peaks'
meas = 'Intervals'
key = 'Mean1' #'Mean1' default for single wave
frequency_plot(event_type, meas, key, Data, Settings, Results)


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Interactive Graphs
Line Graphs
One pannel, detected events
Plot one time series by calling it's name
Can you write Python code for it?

#Interactive, single time series by Key
key = 'Mean1'
graph_ts(Data, Settings, Results, key)


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Quick Poincare Plot
Quickly call one poincare plot for display. Plot and Table are not saved automatically. Choose an event type (Peaks or Bursts), measurement type, and key. Calling meas = 'All' is not supported.
Quick Poincare
Can you write Python code for it?

#quick
event_type = 'Bursts'
meas = 'Burst Duration'
key = 'Mean1'
poincare_plot(Results[event_type][key][meas])


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Raster Plot
Shows the temporal relationship of peaks in each column. Auto scales. Display only. Intended for more than one column of data
Can you write Python code for it?


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Sample Entropy
this only runs if you have pyeeg.py in the same folder as this notebook and bass.py. WARNING: THIS FUNCTION RUNS SLOWLY
run the below code to get the sample entropy of any measurement. Returns the entropy of the entire results array (no windowing). I am using the following M and R values:
M = 2
R = 0.2*std(measurement)

these values can be modified in the source code. alternatively, you can call samp_entropy directly.
Supports 'all'
Sample Entropy in BASS
Sample Entropy Source
Events
Can you write Python code for it?

#Sample Entropy
event_type = 'Bursts'
meas = 'all'
Results = samp_entropy_wrapper(event_type, meas, Data, Settings, Results)
Results['Sample Entropy']


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Spectrogram
Use the block below to get the spectrogram of the signal. The frequency (y-axis) scales automatically to only show 'active' frequencies. This can take some time to run.
version = 'original'
key = 'Mean1'

After transformation is run, you can call version = 'trans'. This graph is not automatically saved.
Spectrogram
Can you write Python code for it?

version = 'original'
key = 'Mean1'
spectogram(version, key, Data, Settings, Results)


I am working on the file "Single Wave- Basic.ipynb".
The first task is:
Time Series
Use the settings code block to set your frequency bands to calculate area under the curve. This block is not required. band output is always in raw power, even if the graph scale is dB/Hz.
Power Spectral Density: Signal
Can you write Python code for it?

#optional
Settings['PSD-Signal'] = Series(index = ['ULF', 'VLF', 'LF','HF','dx'])

#Set PSD ranges for power in band
Settings['PSD-Signal']['ULF'] = 25 #max of the range of the ultra low freq band. range is 0:ulf
Settings['PSD-Signal']['VLF'] = 75 #max of the range of the very low freq band. range is ulf:vlf
Settings['PSD-Signal']['LF'] = 150 #max of the range of the low freq band. range is vlf:lf
Settings['PSD-Signal']['HF'] = 300 #max of the range of the high freq band. range is lf:hf. hf can be no more than (hz/2) where hz is the sampling frequency
Settings['PSD-Signal']['dx'] = 2 #segmentation for integration of the area under the curve.


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Autocorrelation Plot
Display the Autocorrelation plot of your transformed data.
Choose the start and end time in seconds. May be slow
key = 'Mean1'
start = 0
end = 10

Autocorrelation Plot
Can you write Python code for it?

#autocorrelation
key = 'Mean1'
start = 0 #seconds, where you want the slice to begin
end = 10 #seconds, where you want the slice to end.
autocorrelation_plot(Data['trans'][key][start:end])
plt.show()


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Begin User Input
For help, check out the wiki: Protocol
Or the video tutorial: Coming Soon!
Load Data File
Use the following block to change your settings. You must use this block.
Here are some helpful information about the loading settings:
Full File Path to Folder containing file:
Designate the path to your file to load. It can also be the relative path to the folder where this notebook is stored. This does not include the file itself.
Mac OSX Example: '/Users/MYNAME/Documents/bass'
Microsoft Example: 'C:\\Users\MYNAME\Documents\bass'

File name:
This is the name of your data file. It should include the file type. This file should NOT have a header and the first column must be time in seconds. Note: This file name will also appear as part of the output files names.
'rat34_ECG.txt'

Full File Path for data output: Designate the location of the folder where you would like the folder containing your results to go. If the folder does not exist, then it will be created. A plots folder, called 'plots' will be created inside this folder for you if it does not already exist.
Mac OSX Example: '/Users/MYNAME/Documents/output'
Microsoft Example: 'C:\\Users\MYNAME\Documents\output'

Loading a file
Can you write Python code for it?

Data, Settings, Results = load_interact()


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Bursts
Bursts are the boundaries of events defined by their amplitudes, which are greater than the set threshold
Enter Burst Settings
Run the Following Block of code to enter or change burst detection settings. If you have loaded settings from a previous file, you do not need to run this block.
Burst Settings
Can you write Python code for it?

Settings = event_burstdet_settings(Data, Settings, Results)


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Enter your settings for data transformation
WARNING: If you do not load a settings file OR enter your own settings, the analysis will not run. There are no defaults. This section is not optional.
Enter the parameters of the functions you would like to use to transform your data.
If you do not want to use a function, enter 'none'
For more help on settings:
Transformation Settings
Can you write Python code for it?


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Event Detection
Peaks
Peaks are local maxima, defined by local minima on either side of them. Click here for more information about this algorithm
Peak Detection Settings
Run the Following Block of code to enter or change peak detection settings. If you have loaded settings from a previous file, you do not need to run this block.
Peak Detection Settings
Can you write Python code for it?

Settings = event_peakdet_settings(Data, Settings)


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Event PSD
Use block below to return the PSD plot, as well as the power in the bands defined by the settings above.
Can you write Python code for it?

event_type = 'Bursts'
meas = 'Total Cycle Time'
key = 'Mean1'
scale = 'raw'
Results = psd_event(event_type, meas, key, scale, Data, Settings, Results)
Results['PSD-Event'][key]


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Graph Data (Optional)
Use this block to check any slicing you need to do to cut out problematic data from the head or tail. You can click on any point in the wave to get the (x,y) location of that point. Clipping inside this notebook is not supported at this time.
Graph Raw Data
Can you write Python code for it?


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Line Plots
Create line plots of the raw data as well as the data analysis.
Plots are saved by clicking the save button in the pop-up window with your graph.
key = 'Mean1'
start =100
end= 101

Results Line Plot
Can you write Python code for it?

key = 'Mean1'
start =100 #start time in seconds
end= 101 #end time in seconds
results_timeseries_plot(key, start, end, Data, Settings, Results)


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Moving/Sliding Averages, Standard Deviation, and Count
Generates the moving mean, standard deviation, and count for a given measurement across all columns of the Data in the form of a DataFrame (displayed as a table).
Saves out the dataframes of these three results automatically with the window size in the name as a .csv.
If meas == 'All', then the function will loop and produce these tables for all measurements.
event_type = 'Peaks'
meas = 'all'
window = 30

Moving Stats
Can you write Python code for it?


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Plot Events (Optional)
Call a column of data by its key (column name). Default name for one column of data is 'Mean1'
Visualize Bursts
Can you write Python code for it?

key = 'Mean1'
graph_ts(Data, Settings, Results, key)


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Power Spectral Density
The following blocks allows you to asses the power of event measuments in the frequency domain. While you can call this block on any event measurement, it is intended to be used on interval data (or at least data with units in seconds). Reccomended:
event_type = 'Bursts'
meas = 'Total Cycle Time'
key = 'Mean1'
scale = 'raw'

event_type = 'Peaks'
meas = 'Intervals'
key = 'Mean1'
scale = 'raw'

Because this data is in the frequency domain, we must interpolate it in order to perform a FFT on it. Does not support 'all'.
Power Spectral Density: Events
Settings
Use the code block below to specify your settings for event measurment PSD.
Can you write Python code for it?

Settings['PSD-Event'] = Series(index = ['Hz','ULF', 'VLF', 'LF','HF','dx'])
#Set PSD ranges for power in band

Settings['PSD-Event']['hz'] = 4.0 #freqency that the interpolation and PSD are performed with.
Settings['PSD-Event']['ULF'] = 0.03 #max of the range of the ultra low freq band. range is 0:ulf
Settings['PSD-Event']['VLF'] = 0.05 #max of the range of the very low freq band. range is ulf:vlf
Settings['PSD-Event']['LF'] = 0.15 #max of the range of the low freq band. range is vlf:lf
Settings['PSD-Event']['HF'] = 0.4 #max of the range of the high freq band. range is lf:hf. hf can be no more than (hz/2)
Settings['PSD-Event']['dx'] = 10 #segmentation for the area under the curve.


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Quick Poincare Plot
Quickly call one poincare plot for display. Plot and Table are not saved automatically. Choose an event type (Peaks or Bursts), measurement type, and key. Calling meas = 'All' is not supported.
Quick Poincare
Can you write Python code for it?


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Results Plots
Poincare Plots
Create a Poincare Plot of your favorite varible. Choose an event type (Peaks or Bursts), measurement type. Calling meas = 'All' is supported.
Plots and tables are saved automatically
Example:
event_type = 'Bursts'
meas = 'Burst Duration'

More on Poincare Plots
Batch Poincare
Batch Poincare
Can you write Python code for it?

#Batch
event_type = 'Peaks'
meas = 'all'
Results = poincare_batch(event_type, meas, Data, Settings, Results)
pd.concat({'SD1':Results['Poincare SD1'],'SD2':Results['Poincare SD2']})


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Run Event Peak Detection
Run block of code below to run peak deteaction. This block will print a summary table of the all available peak measurments.
Peak Detection
Can you write Python code for it?

Results = event_peakdet_wrapper(Data, Settings, Results)
Results['Peaks-Master'].groupby(level=0).describe()


I am working on the file "Single Wave- Interactive.ipynb".
The first task is:
Run baseline
Generate Baseline
Can you write Python code for it?

Data, Settings, Results = baseline_wrapper(Data, Settings, Results)
graph_ts(Data, Settings, Results)