CARLsim  4.1.0
CARLsim: a GPU-accelerated SNN simulator
simple_weight_tuner.cpp
Go to the documentation of this file.
1 /* * Copyright (c) 2016 Regents of the University of California. All rights reserved.
2 *
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions
5 * are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * 3. The names of its contributors may not be used to endorse or promote
15 * products derived from this software without specific prior written
16 * permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 * *********************************************************************************************** *
31 * CARLsim
32 * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
33 * maintained by:
34 * (MA) Mike Avery <averym@uci.edu>
35 * (MB) Michael Beyeler <mbeyeler@uci.edu>,
36 * (KDC) Kristofor Carlson <kdcarlso@uci.edu>
37 * (TSC) Ting-Shuo Chou <tingshuc@uci.edu>
38 * (HK) Hirak J Kashyap <kashyaph@uci.edu>
39 *
40 * CARLsim v1.0: JM, MDR
41 * CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC
42 * CARLsim3: MB, KDC, TSC
43 * CARLsim4: TSC, HK
44 *
45 * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
46 * Ver 12/31/2016
47 */
48 #include "simple_weight_tuner.h"
49 
50 #include <carlsim.h> // CARLsim, SpikeMonitor
51 #include <math.h> // fabs
52 #include <stdio.h> // printf
53 #include <limits> // double::max
54 #include <assert.h> // assert
55 
56 // ****************************************************************************************************************** //
57 // SIMPLEWEIGHTTUNER UTILITY PRIVATE IMPLEMENTATION
58 // ****************************************************************************************************************** //
59 
68 public:
69  // +++++ PUBLIC METHODS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
70 
71  Impl(CARLsim *sim, double errorMargin, int maxIter, double stepSizeFraction) {
72  assert(sim!=NULL);
73  assert(errorMargin>0);
74  assert(maxIter>0);
75  assert(stepSizeFraction>0.0f && stepSizeFraction<=1.0f);
76 
77  sim_ = sim;
78  assert(sim_->getCARLsimState()!=RUN_STATE);
79 
80  errorMargin_ = errorMargin;
81  stepSizeFraction_ = stepSizeFraction;
82  maxIter_ = maxIter;
83 
84  connId_ = -1;
85  wtRange_ = NULL;
86  wtInit_ = -1.0;
87 
88  grpId_ = -1;
89  targetRate_ = -1.0;
90 
91  wtStepSize_ = -1.0;
92  cntIter_ = 0;
93 
94  wtShouldIncrease_ = true;
95  adjustRange_ = true;
96 
97  needToInitConnection_ = true;
98  needToInitTargetFiring_ = true;
99 
100  needToInitAlgo_ = true;
101  }
102 
103  ~Impl() {
104  if (wtRange_!=NULL)
105  delete wtRange_;
106  wtRange_=NULL;
107  }
108 
109 // user function to reset algo
110 void reset() {
111  needToInitAlgo_ = true;
112  initAlgo();
113 }
114 
115 bool done(bool printMessage) {
116  // algo not initalized: we're not done
117  if (needToInitConnection_ || needToInitTargetFiring_ || needToInitAlgo_)
118  return false;
119 
120  // success: margin reached
121  if (fabs(currentError_) < errorMargin_) {
122  if (printMessage) {
123  printf("SimpleWeightTuner successful: Error margin reached in %d iterations.\n",cntIter_);
124  }
125  return true;
126  }
127 
128  // failure: max iter reached
129  if (cntIter_ >= maxIter_) {
130  if (printMessage) {
131  printf("SimpleWeightTuner failed: Max number of iterations (%d) reached.\n",maxIter_);
132  }
133  return true;
134  }
135 
136  // else we're not done
137  return false;
138 }
139 
140 void setConnectionToTune(short int connId, double initWt, bool adjustRange) {
141  assert(connId>=0 && connId<sim_->getNumConnections());
142 
143  connId_ = connId;
144  wtInit_ = initWt;
145  adjustRange_ = adjustRange;
146 
147  needToInitConnection_ = false;
148  needToInitAlgo_ = true;
149 }
150 
151 void setTargetFiringRate(int grpId, double targetRate) {
152  grpId_ = grpId;
153  targetRate_ = targetRate;
154  currentError_ = targetRate;
155 
156  // check whether group has SpikeMonitor
157  SM_ = sim_->getSpikeMonitor(grpId);
158  if (SM_==NULL) {
159  // setSpikeMonitor has not been called yet
160  SM_ = sim_->setSpikeMonitor(grpId,"NULL");
161  }
162 
163  needToInitTargetFiring_ = false;
164  needToInitAlgo_ = true;
165 }
166 
167 void iterate(int runDurationMs, bool printStatus) {
168  assert(runDurationMs>0);
169 
170  // if we're done, don't iterate
171  if (done(printStatus)) {
172  return;
173  }
174 
175  // make sure we have initialized algo
176  assert(!needToInitConnection_);
177  assert(!needToInitTargetFiring_);
178  if (needToInitAlgo_)
179  initAlgo();
180 
181  // in case the user has already been messing with the SpikeMonitor, we need to make sure that
182  // PersistentMode is off
183  SM_->setPersistentData(false);
184 
185  // now iterate
186  SM_->startRecording();
187  sim_->runNetwork(runDurationMs/1000, runDurationMs%1000, false);
188  SM_->stopRecording();
189 
190  double thisRate = SM_->getPopMeanFiringRate();
191  if (printStatus) {
192  printf("#%d: rate=%.4fHz, target=%.4fHz, error=%.7f, errorMargin=%.7f\n", cntIter_, thisRate, targetRate_,
193  thisRate-targetRate_, errorMargin_);
194  }
195 
196  currentError_ = thisRate - targetRate_;
197  cntIter_++;
198 
199  // check if we're done now
200  if (done(printStatus)) {
201  return;
202  }
203 
204  // else update parameters
205  if (wtStepSize_>0 && thisRate>targetRate_ || wtStepSize_<0 && thisRate<targetRate_) {
206  // we stepped too far to the right or too far to the left
207  // turn around and cut step size in half
208  // note that this should work for inhibitory connections, too: they have negative weights, so adding
209  // to the weight will actually decrease it (make it less negative)
210  wtStepSize_ = -wtStepSize_/2.0;
211  }
212 
213  // find new weight
214  sim_->biasWeights(connId_, wtStepSize_, adjustRange_);
215 }
216 
217 private:
218  // +++++ PRIVATE METHODS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
219 
220 // need to call this whenever connection or target firing changes
221 // or when user calls reset
222 void initAlgo() {
223  if (!needToInitAlgo_)
224  return;
225 
226  // make sure we have all the data structures we need
227  assert(!needToInitConnection_);
228  assert(!needToInitTargetFiring_);
229 
230  // update weight ranges
231  RangeWeight wt = sim_->getWeightRange(connId_);
232  wtRange_ = new RangeWeight(wt.min, wt.init, wt.max);
233 
234  // reset algo
235  wtShouldIncrease_ = true;
236  wtStepSize_ = stepSizeFraction_ * (wtRange_->max - wtRange_->min);
237 #if defined(WIN32) || defined(WIN64)
238  currentError_ = DBL_MAX;
239 #else
240  currentError_ = std::numeric_limits<double>::max();
241 #endif
242 
243  // make sure we're in the right CARLsim state
244  if (sim_->getCARLsimState()!=RUN_STATE)
245  sim_->runNetwork(0,0,false);
246 
247  // initialize weights
248  if (wtInit_>=0) {
249  // start at some specified initWt
250  if (wt.init != wtInit_) {
251  // specified starting point is not what is specified in connect
252 
253  sim_->biasWeights(connId_, wtInit_ - wt.init, adjustRange_);
254  }
255  }
256 
257  needToInitAlgo_ = false;
258 }
259 
260 
261  // +++++ PRIVATE STATIC PROPERTIES ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
262 
263  // +++++ PRIVATE PROPERTIES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
264 
265  // flags that manage state
266  bool needToInitConnection_;
267  bool needToInitTargetFiring_;
268  bool needToInitAlgo_;
269 
270  // CARLsim data structures
271  CARLsim *sim_;
272  SpikeMonitor *SM_;
273  int grpId_;
274  short int connId_;
275  RangeWeight* wtRange_;
276 
277  // termination condition params
278  int maxIter_;
279  double errorMargin_;
280  double targetRate_;
281 
282  // params that are updated every iteration step
283  int cntIter_;
284  double wtStepSize_;
285  bool wtShouldIncrease_;
286  double currentError_;
287 
288  // options
289  bool adjustRange_;
290  double wtInit_;
291  double stepSizeFraction_;
292 };
293 
294 
295 // ****************************************************************************************************************** //
296 // SIMPLEWEIGHTTUNER API IMPLEMENTATION
297 // ****************************************************************************************************************** //
298 
299 // create and destroy a pImpl instance
300 SimpleWeightTuner::SimpleWeightTuner(CARLsim* sim, double errorMargin, int maxIter, double stepSizeFraction) :
301  _impl( new Impl(sim, errorMargin, maxIter, stepSizeFraction) ) {}
303 
304 void SimpleWeightTuner::setConnectionToTune(short int connId, double initWt, bool adjustRange) {
305  _impl->setConnectionToTune(connId, initWt, adjustRange);
306 }
307 void SimpleWeightTuner::setTargetFiringRate(int grpId, double targetRate) {
308  _impl->setTargetFiringRate(grpId, targetRate);
309 }
310 void SimpleWeightTuner::iterate(int runDurationMs, bool printStatus) { _impl->iterate(runDurationMs, printStatus); }
311 bool SimpleWeightTuner::done(bool printMessage) { return _impl->done(printMessage); }
312 void SimpleWeightTuner::reset() { _impl->reset(); }
RangeWeight::init
double init
Definition: carlsim_datastructures.h:334
RUN_STATE
@ RUN_STATE
run state, where the model is stepped
Definition: carlsim_datastructures.h:262
SimpleWeightTuner::Impl::setTargetFiringRate
void setTargetFiringRate(int grpId, double targetRate)
Definition: simple_weight_tuner.cpp:151
SimpleWeightTuner::Impl::Impl
Impl(CARLsim *sim, double errorMargin, int maxIter, double stepSizeFraction)
Definition: simple_weight_tuner.cpp:71
RangeWeight
a range struct for synaptic weight magnitudes
Definition: carlsim_datastructures.h:311
SpikeMonitor
Class SpikeMonitor.
Definition: spike_monitor.h:119
SimpleWeightTuner::setConnectionToTune
void setConnectionToTune(short int connId, double initWt=-1.0, bool adjustRange=true)
Sets up the connection to tune.
Definition: simple_weight_tuner.cpp:304
SpikeMonitor::setPersistentData
void setPersistentData(bool persistentData)
Sets PersistentMode either on (true) or off (false)
Definition: spike_monitor.cpp:246
SimpleWeightTuner::Impl::reset
void reset()
Definition: simple_weight_tuner.cpp:110
CARLsim::runNetwork
int runNetwork(int nSec, int nMsec=0, bool printRunSummary=true)
run the simulation for time=(nSec*seconds + nMsec*milliseconds)
Definition: carlsim.cpp:1909
CARLsim::biasWeights
void biasWeights(short int connId, float bias, bool updateWeightRange=false)
Adds a constant bias to the weight of every synapse in the connection.
Definition: carlsim.cpp:1936
SpikeMonitor::stopRecording
void stopRecording()
Ends a recording period.
Definition: spike_monitor.cpp:207
SimpleWeightTuner::Impl::setConnectionToTune
void setConnectionToTune(short int connId, double initWt, bool adjustRange)
Definition: simple_weight_tuner.cpp:140
SimpleWeightTuner::Impl::iterate
void iterate(int runDurationMs, bool printStatus)
Definition: simple_weight_tuner.cpp:167
RangeWeight::max
double max
Definition: carlsim_datastructures.h:334
SimpleWeightTuner::~SimpleWeightTuner
~SimpleWeightTuner()
Destructor.
Definition: simple_weight_tuner.cpp:302
SimpleWeightTuner::Impl
Private implementation of the Stopwatch Utility.
Definition: simple_weight_tuner.cpp:67
simple_weight_tuner.h
SpikeMonitor::getPopMeanFiringRate
float getPopMeanFiringRate()
Returns the mean firing rate of the entire neuronal population.
Definition: spike_monitor.cpp:76
SimpleWeightTuner::setTargetFiringRate
void setTargetFiringRate(int grpId, double targetRate)
Sets up the target firing rate of a specific group.
Definition: simple_weight_tuner.cpp:307
SimpleWeightTuner::reset
void reset()
Resets the algorithm to initial conditions.
Definition: simple_weight_tuner.cpp:312
SimpleWeightTuner::SimpleWeightTuner
SimpleWeightTuner(CARLsim *sim, double errorMargin=1e-3, int maxIter=100, double stepSizeFraction=0.5)
Creates a new instance of class SimpleWeightTuner.
Definition: simple_weight_tuner.cpp:300
SimpleWeightTuner::done
bool done(bool printMessage=false)
Determines whether a termination criterion has been met.
Definition: simple_weight_tuner.cpp:311
CARLsim::getSpikeMonitor
SpikeMonitor * getSpikeMonitor(int grpId)
Returns the number of spikes per neuron for a certain group.
Definition: carlsim.cpp:2093
CARLsim
CARLsim User Interface This class provides a user interface to the public sections of CARLsimCore sou...
Definition: carlsim.h:137
CARLsim::getWeightRange
RangeWeight getWeightRange(short int connId)
returns the RangeWeight struct for a specific connection ID
Definition: carlsim.cpp:2096
SpikeMonitor::startRecording
void startRecording()
Starts a new recording period.
Definition: spike_monitor.cpp:200
SimpleWeightTuner::Impl::~Impl
~Impl()
Definition: simple_weight_tuner.cpp:103
CARLsim::getCARLsimState
CARLsimState getCARLsimState()
Writes population weights from gIDpre to gIDpost to file fname in binary.
Definition: carlsim.cpp:1998
carlsim.h
SimpleWeightTuner::iterate
void iterate(int runDurationMs=1000, bool printStatus=true)
Performs an iteration step of the tuning algorithm.
Definition: simple_weight_tuner.cpp:310
RangeWeight::min
double min
Definition: carlsim_datastructures.h:334
CARLsim::setSpikeMonitor
SpikeMonitor * setSpikeMonitor(int grpId, const std::string &fileName)
Sets a Spike Monitor for a groups, prints spikes to binary file.
Definition: carlsim.cpp:1972
SimpleWeightTuner::Impl::done
bool done(bool printMessage)
Definition: simple_weight_tuner.cpp:115