<commit_before>Examples
========

Example 1 - Custom controller class, automatic targets
----------------------------------------------------------------
In this this example a model of a CA1 Basket cell will be optimized using
automatic target extraction.

The first thing we do is define a simulation class, this can also be accomplished
by a simple function, but the class defined here gives us some powerful functionality:

.. note::
   This example still has some way to go in terms of detail. I plan to add
   more information about the most important bits, and remove some of the
   relatively superfluous code.

.. code-block:: python

    class Simulation(object):
    
        """
        Simulation class mainly taken from <NAME>, this class has been
        modified slightly by <NAME> to accept a section rather than a cell as the 
        object passed to the set_IClamp method of the class.
        see http://www.paedia.info/neuro/intro_pydesign.html
    
        Objects of this class control a current clamp simulation. Example of use:
        >>> cell = Cell()
        >>> sim = Simulation(cell)
        >>> sim.go()
        >>> sim.show()
        """
    
        def __init__(self, recording_section, sim_time=1000, dt=0.05, v_init=-60):
    
            #h.load_file("stdrun.hoc") # Standard run, which contains init and run
            self.recording_section = recording_section
            self.sim_time = sim_time
            self.dt = dt
            self.go_already = False
            self.v_init=v_init
    
        def set_IClamp(self, delay=5, amp=0.1, dur=1000):
            """
            Initializes values for current clamp.
            
            Default values:
              
              delay = 5 [ms]
              amp   = 0.1 [nA]
              dur   = 1000 [ms]
            """
            stim = h.IClamp(self.recording_section(0.5))
            stim.delay = delay
            stim.amp = amp
            stim.dur = dur
            self.stim = stim
    
        def set_VClamp(self,dur1=100,amp1=0,dur2=0,amp2=0,dur3=0,amp3=0,):
            """
            Initializes values for a Voltage clamp.
    
            techincally this is an SEClamp in neuron, which is a
            three-stage current clamp.
            """
            stim = neuron.h.SEClamp(self.recording_section(0.5))
            
            stim.rs=0.1
            stim.dur1 = dur1
            stim.amp1 = amp1
            stim.dur2 = dur2
            stim.amp2 = amp2
            stim.dur3 = dur3
            stim.amp3 = amp3
    
            self.Vstim = stim
    
        def set_recording(self):
            # Record Time
            self.rec_t = neuron.h.Vector()
            self.rec_t.record(h._ref_t)
            # Record Voltage
            self.rec_v = h.Vector()
            self.rec_v.record(self.recording_section(0.5)._ref_v)
    
        def show(self):
            from matplotlib import pyplot as plt
            if self.go_already:
                x = np.array(self.rec_t)
                y = np.array(self.rec_v)
                plt.plot(x, y)
                #plt.title("Hello World")
                plt.xlabel("Time [ms]")
                plt.ylabel("Voltage [mV]")
                #plt.axis(ymin=-120, ymax=-50)
            else:
                print("""First you have to `go()` the simulation.""")
            plt.show()
        
        def get_recording(self):
            time = np.array(self.rec_t)
            voltage = np.array(self.rec_v)
            return time, voltage
    
        def go(self, sim_time=None):
            self.set_recording()
            h.dt = self.dt
            #h.finitialize(h.E)
            
            h.finitialize(self.v_init)
            neuron.init()
            if sim_time:
                neuron.run(sim_time)
            else:
                neuron.run(self.sim_time)
            self.go_already = True

The next thing we want to do is define our custom controller, this is a "canonical controller"
because it provides a run method and returns timestamp and value arrays:

.. code-block:: python

    class BasketCellController():
    
        """
        Example of "canonical controler"
        """
    
        def run(self,candidates,parameters):
    	traces = []
    
    	for candidate in candidates:
    	    sim_var = dict(zip(parameters,candidate))
    	    t,v = self.run_individual(sim_var)
    	    traces.append([t,v])
    
    	return traces
            def set_section_mechanism(self, sec, mech, mech_attribute, mech_value):
    	for seg in sec:
    	    setattr(getattr(seg, mech), mech_attribute, mech_value)
        
        def run_individual(self,sim_var):
      
            #make compartments and connect them
            soma=h.Section()
            axon=h.Section()
            soma.connect(axon)
        
            axon.insert('na')
            axon.insert('kv')
            axon.insert('kv_3')
            soma.insert('na')
            soma.insert('kv')
            soma.insert('kv_3')
        
            soma.diam=10
            soma.L=10
            axon.diam=2
            axon.L=100
        
            #soma.insert('canrgc')
            #soma.insert('cad2')
        
            #nrntools.set_section_mechanism(sec,'kv','gbar',gkv_dend)
        
            self.set_section_mechanism(axon,'na','gbar',sim_var['axon_gbar_na'])
            self.set_section_mechanism(axon,'kv','gbar',sim_var['axon_gbar_kv'])
            self.set_section_mechanism(axon,'kv_3','gbar',sim_var['axon_gbar_kv3'])
            self.set_section_mechanism(soma,'na','gbar',sim_var['soma_gbar_na'])
            self.set_section_mechanism(soma,'kv','gbar',sim_var['soma_gbar_kv'])
            self.set_section_mechanism(soma,'kv_3','gbar',sim_var['soma_gbar_kv3'])
        
            for sec in h.allsec():
                sec.insert('pas')
                sec.Ra=300
                sec.cm=0.75
                self.set_section_mechanism(sec,'pas','g',1.0/30000)
                self.set_section_mechanism(sec,'pas','e',-70)
        
            h.vshift_na=-5.0
            sim=Simulation(soma,sim_time=1000,v_init=-70.0)
            sim.set_IClamp(150, 0.1, 750)
            sim.go()
        
            sim.show()
        
            return np.array(sim.rec_t), np.array(sim.rec_v)

We create some initial variables for our simulation and instantiate a controller:

.. code-block:: python

    sim_var={}
    
    sim_var['axon_gbar_na']    = 1000.0
    sim_var['axon_gbar_kv']	   = 2310.0
    sim_var['axon_gbar_kv3']   = 0.0
    sim_var['soma_gbar_na']	   = 30.0
    sim_var['soma_gbar_kv']	   = 220.0
    sim_var['soma_gbar_kv3']   = 330.0
    
    cell = BasketCellController()

and finally the optimization script itself:

.. code-block:: python
<commit_msg>fixed indentation issue<commit_after>Examples
========

Example 1 - Custom controller class, automatic targets
----------------------------------------------------------------
In this this example a model of a CA1 Basket cell will be optimized using
automatic target extraction.

The first thing we do is define a simulation class, this can also be accomplished
by a simple function, but the class defined here gives us some powerful functionality:

.. note::
   This example still has some way to go in terms of detail. I plan to add
   more information about the most important bits, and remove some of the
   relatively superfluous code.

.. code-block:: python

    class Simulation(object):
    
        """
        Simulation class mainly taken from <NAME>, this class has been
        modified slightly by Mike Vella to accept a section rather than a cell as the 
        object passed to the set_IClamp method of the class.
        see http://www.paedia.info/neuro/intro_pydesign.html
    
        Objects of this class control a current clamp simulation. Example of use:
        >>> cell = Cell()
        >>> sim = Simulation(cell)
        >>> sim.go()
        >>> sim.show()
        """
    
        def __init__(self, recording_section, sim_time=1000, dt=0.05, v_init=-60):
    
            #h.load_file("stdrun.hoc") # Standard run, which contains init and run
            self.recording_section = recording_section
            self.sim_time = sim_time
            self.dt = dt
            self.go_already = False
            self.v_init=v_init
    
        def set_IClamp(self, delay=5, amp=0.1, dur=1000):
            """
            Initializes values for current clamp.
            
            Default values:
              
              delay = 5 [ms]
              amp   = 0.1 [nA]
              dur   = 1000 [ms]
            """
            stim = h.IClamp(self.recording_section(0.5))
            stim.delay = delay
            stim.amp = amp
            stim.dur = dur
            self.stim = stim
    
        def set_VClamp(self,dur1=100,amp1=0,dur2=0,amp2=0,dur3=0,amp3=0,):
            """
            Initializes values for a Voltage clamp.
    
            techincally this is an SEClamp in neuron, which is a
            three-stage current clamp.
            """
            stim = neuron.h.SEClamp(self.recording_section(0.5))
            
            stim.rs=0.1
            stim.dur1 = dur1
            stim.amp1 = amp1
            stim.dur2 = dur2
            stim.amp2 = amp2
            stim.dur3 = dur3
            stim.amp3 = amp3
    
            self.Vstim = stim
    
        def set_recording(self):
            # Record Time
            self.rec_t = neuron.h.Vector()
            self.rec_t.record(h._ref_t)
            # Record Voltage
            self.rec_v = h.Vector()
            self.rec_v.record(self.recording_section(0.5)._ref_v)
    
        def show(self):
            from matplotlib import pyplot as plt
            if self.go_already:
                x = np.array(self.rec_t)
                y = np.array(self.rec_v)
                plt.plot(x, y)
                #plt.title("Hello World")
                plt.xlabel("Time [ms]")
                plt.ylabel("Voltage [mV]")
                #plt.axis(ymin=-120, ymax=-50)
            else:
                print("""First you have to `go()` the simulation.""")
            plt.show()
        
        def get_recording(self):
            time = np.array(self.rec_t)
            voltage = np.array(self.rec_v)
            return time, voltage
    
        def go(self, sim_time=None):
            self.set_recording()
            h.dt = self.dt
            #h.finitialize(h.E)
            
            h.finitialize(self.v_init)
            neuron.init()
            if sim_time:
                neuron.run(sim_time)
            else:
                neuron.run(self.sim_time)
            self.go_already = True

The next thing we want to do is define our custom controller, this is a "canonical controller"
because it provides a run method and returns timestamp and value arrays:

.. code-block:: python

    class BasketCellController():
    
        """
        Example of "canonical controler"
        """
    
        def run(self,candidates,parameters):
            traces = []
    
            for candidate in candidates:
                sim_var = dict(zip(parameters,candidate))
                t,v = self.run_individual(sim_var)
                traces.append([t,v])
    
            return traces
    
        def set_section_mechanism(self, sec, mech, mech_attribute, mech_value):
            for seg in sec:
                setattr(getattr(seg, mech), mech_attribute, mech_value)
        
        def run_individual(self,sim_var):
      
            #make compartments and connect them
            soma=h.Section()
            axon=h.Section()
            soma.connect(axon)
        
            axon.insert('na')
            axon.insert('kv')
            axon.insert('kv_3')
            soma.insert('na')
            soma.insert('kv')
            soma.insert('kv_3')
        
            soma.diam=10
            soma.L=10
            axon.diam=2
            axon.L=100
        
            #soma.insert('canrgc')
            #soma.insert('cad2')
        
            #nrntools.set_section_mechanism(sec,'kv','gbar',gkv_dend)
        
            self.set_section_mechanism(axon,'na','gbar',sim_var['axon_gbar_na'])
            self.set_section_mechanism(axon,'kv','gbar',sim_var['axon_gbar_kv'])
            self.set_section_mechanism(axon,'kv_3','gbar',sim_var['axon_gbar_kv3'])
            self.set_section_mechanism(soma,'na','gbar',sim_var['soma_gbar_na'])
            self.set_section_mechanism(soma,'kv','gbar',sim_var['soma_gbar_kv'])
            self.set_section_mechanism(soma,'kv_3','gbar',sim_var['soma_gbar_kv3'])
        
            for sec in h.allsec():
                sec.insert('pas')
                sec.Ra=300
                sec.cm=0.75
                self.set_section_mechanism(sec,'pas','g',1.0/30000)
                self.set_section_mechanism(sec,'pas','e',-70)
        
            h.vshift_na=-5.0
            sim=Simulation(soma,sim_time=1000,v_init=-70.0)
            sim.set_IClamp(150, 0.1, 750)
            sim.go()
        
            sim.show()
        
            return np.array(sim.rec_t), np.array(sim.rec_v)


We create some initial variables for our simulation and instantiate a controller:

.. code-block:: python

    sim_var={}
    
    sim_var['axon_gbar_na']    = 1000.0
    sim_var['axon_gbar_kv']	   = 2310.0
    sim_var['axon_gbar_kv3']   = 0.0
    sim_var['soma_gbar_na']	   = 30.0
    sim_var['soma_gbar_kv']	   = 220.0
    sim_var['soma_gbar_kv3']   = 330.0
    
    cell = BasketCellController()

and finally the optimization script itself:

.. code-block:: python

{'fraction_non_alphanumeric': 0.11142143172129942, 'fraction_numerical': 0.019991180361605174, 'mean_word_length': 1.6197535618020793, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3256444', 'n_tokens_mistral': 4380, 'n_tokens_neox': 4121, 'n_words': 915}