#!/usr/bin/env python3

# NOTE: deprecating spherical roots changes the behavior of this model.
# There is no soma, because only the root sample has tag 1, which will be
# ignored as it is always the proximal end of any cable segment.
# The fix is to:
#   - Write an swc interpreter that inserts a cylinder with the
#     appropriate properties.
#   - Extend the cable-only descriptions to handle detached cables, to
#     preserve surface area and correct starting locations of cables
#     attached to the soma.

import arbor
import pandas
import seaborn
import sys

# Load a cell morphology from an swc file.
# Example present here: single_cell_detailed.swc
if len(sys.argv) < 2:
    print("No SWC file passed to the program")
    sys.exit(0)

filename = sys.argv[1]
morpho = arbor.load_swc_arbor(filename)

# Define the regions and locsets in the model.
labels = arbor.label_dict(
    {
        "root": "(root)",  # the start of the soma in this morphology is at the root of the cell.
        "stim_site": "(location 0 0.5)",  # site for the stimulus, in the middle of branch 0.
        "axon_end": '(restrict (terminal) (region "axon"))',
    }  # end of the axon.
).add_swc_tags()  # Finally, add the SWC default labels.

decor = (
    arbor.decor()
    # Set initial membrane potential to -55 mV
    .set_property(Vm=-55)
    # Use Nernst to calculate reversal potential for calcium.
    .set_ion("ca", method=arbor.mechanism("nernst/x=ca"))
    # hh mechanism on the soma and axon.
    .paint('"soma"', arbor.density("hh"))
    .paint('"axon"', arbor.density("hh"))
    # pas mechanism the dendrites.
    .paint('"dend"', arbor.density("pas"))
    # Increase resistivity on dendrites.
    .paint('"dend"', rL=500)
    # Attach stimuli that inject 4 nA current for 1 ms, starting at 3 and 8 ms.
    .place('"root"', arbor.iclamp(10, 1, current=5), "iclamp0")
    .place('"stim_site"', arbor.iclamp(3, 1, current=0.5), "iclamp1")
    .place('"stim_site"', arbor.iclamp(10, 1, current=0.5), "iclamp2")
    .place('"stim_site"', arbor.iclamp(8, 1, current=4), "iclamp3")
    # Detect spikes at the soma with a voltage threshold of -10 mV.
    .place('"axon_end"', arbor.threshold_detector(-10), "detector")
    # Create the policy used to discretise the cell into CVs.
    # Use a single CV for the soma, and CVs of maximum length 1 μm elsewhere.
    .discretization('(replace (single (region "soma")) (max-extent 1.0))')
)

# Combine morphology with region and locset definitions to make a cable cell.
cell = arbor.cable_cell(morpho, decor, labels)

print(cell.locations('"axon_end"'))

# Make single cell model.
m = arbor.single_cell_model(cell)

# Attach voltage probes that sample at 50 kHz.
m.probe("voltage", where='"root"', frequency=50)
m.probe("voltage", where='"stim_site"', frequency=50)
m.probe("voltage", where='"axon_end"', frequency=50)

# Simulate the cell for 15 ms.
tfinal = 15
m.run(tfinal)
print("Simulation done.")

# Print spike times.
if len(m.spikes) > 0:
    print("{} spikes:".format(len(m.spikes)))
    for s in m.spikes:
        print("  {:7.4f}".format(s))
else:
    print("no spikes")

# Plot the recorded voltages over time.
print("Plotting results ...")
df_list = []
for t in m.traces:
    df_list.append(
        pandas.DataFrame(
            {
                "t/ms": t.time,
                "U/mV": t.value,
                "Location": str(t.location),
                "Variable": t.variable,
            }
        )
    )

df = pandas.concat(df_list, ignore_index=True)

seaborn.relplot(
    data=df, kind="line", x="t/ms", y="U/mV", hue="Location", col="Variable", ci=None
).savefig("single_cell_swc.svg")
