# Path: pyglm/models/model_factory.py
# def make_model(template, N=None, dt=None):
#     """ Construct a model from a template and update the specified parameters
#     """
#     if isinstance(template, str):
#         # Create the specified model
#         if template.lower() == 'standard_glm' or \
#            template.lower() == 'standardglm':
#             model = copy.deepcopy(StandardGlm)
#         elif template.lower() == 'spatiotemporal_glm':
#             model = copy.deepcopy(SpatiotemporalGlm)
#         elif template.lower() == 'shared_tuning_curve':
#             model = copy.deepcopy(SharedTuningCurveGlm)
#         elif template.lower() == 'simple_weighted_model' or \
#              template.lower() == 'simpleweightedmodel':
#             model = copy.deepcopy(SimpleWeightedModel)
#         elif template.lower() == 'simple_sparse_model' or \
#              template.lower() == 'simplesparsemodel':
#             model = copy.deepcopy(SimpleSparseModel)
#         elif template.lower() == 'sparse_weighted_model' or \
#              template.lower() == 'sparseweightedmodel':
#             model = copy.deepcopy(SparseWeightedModel)
#         elif template.lower() == 'sbm_weighted_model' or \
#              template.lower() == 'sbmweightedmodel':
#             model = copy.deepcopy(SbmWeightedModel)
#         elif template.lower() == 'distance_weighted_model' or \
#              template.lower() == 'distanceweightedmodel':
#             model = copy.deepcopy(DistanceWeightedModel)
#         else:
#             raise Exception("Unrecognized template model: %s!" % template)
#     elif isinstance(template, dict):
#         model = copy.deepcopy(template)
#     else:
#         raise Exception("Unrecognized template model!")
# 
#     # Override template model parameters
#     if N is not None:
#         model['N'] = N
# 
#     if dt is not None:
#         model['dt'] = dt
# 
#     # # Update other parameters as necessary
#     # if template.lower() == 'distance_weighted_model' or \
#     #    template.lower() == 'distanceweightedmodel':
#     #     #model['network']['graph']['location_prior']['sigma'] = N/2.0/3.0
#     #     model['network']['graph']['location_prior']['mu'] = \
#     #         np.tile(np.arange(N).reshape((N,1)),
#     #                 [1,model['network']['graph']['N_dims']]).ravel()
# 
#     return model
# 
# Path: pyglm/utils/avg_dicts.py
# def average_list_of_dicts(smpls):
#     """ Average a list of dictionaries, e.g. a list of samples from
#         the MCMC loop. The dictionary elements may themselves be
#         dictionaries, so work recursively and only average the leaves.
#     """
#     N_smpls = len(smpls)
#     import copy
#     avg = copy.deepcopy(smpls[0])
# 
#     def inc_avg(avg, smpl):
#         """ Helper to recrusively add to the average
#         """
#         if isinstance(smpl, dict):
#             for (key,val) in smpl.items():
#                 if isinstance(val, dict) or \
#                   isinstance(val, list):
#                   # Recurse if the entry is another dict
#                     avg[key] = inc_avg(avg[key], val)
#                 elif isinstance(val, np.ndarray):
#                     # Otherwise increment the value
#                     avg[key] = avg[key].astype(np.float) + \
#                                val.astype(np.float)
#                 else:
#                     # Who knows if this will work without casting!
#                     avg[key] += val
#         
#         elif isinstance(smpl, list):
#             for (i,val) in enumerate(smpl):
#                 if isinstance(val, list) or \
#                    isinstance(val, dict):
#                     # Recurse if the entry is another iterable
#                     avg[i] = inc_avg(avg[i], val)
#                 elif isinstance(val, np.ndarray):
#                     avg[i] = avg[i].astype(np.float) + \
#                              val.astype(np.float)
#                 else:
#                     # Who knows if this will work without casting!
#                     avg[i] += float(val)
#         return avg
# 
#     for smpl in smpls[1:]:
#         avg = inc_avg(avg, smpl)
# 
#     def norm_avg(avg, N_smpls):
#         """ Normalize the average by dividing by N_smpls
#         """
#         if isinstance(avg, dict):
#             for (key,val) in avg.items():
#                 if isinstance(val, dict) or \
#                    isinstance(val, list):
#                     avg[key] = norm_avg(val, N_smpls)
#                 else:
#                     avg[key] /= float(N_smpls)
#         elif isinstance(avg, list):
#             for (i,val) in enumerate(avg):
#                 if isinstance(val, list) or \
#                    isinstance(val, dict):
#                     # Recurse if the entry is another iterable
#                     avg[i] = norm_avg(val, N_smpls)
#                 else:
#                     avg[i] /= float(N_smpls)
#                         
#         return avg
# 
#     avg = norm_avg(avg, N_smpls)
#     return avg


import os
import cPickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from pyglm.models.model_factory import make_model
from population import Population
from pyglm.utils.avg_dicts import average_list_of_dicts
    from test.synth_harness import initialize_test_harness



matplotlib.use('Agg')       # To enable saving remotely




def make_rwb_cmap():
    # Get a red-white-black cmap
    cdict = {'red': ((0.0, 1.0, 1.0),
                 (0.5, 1.0, 1.0),
                 (1.0, 0.0, 0.0)),
        'green': ((0.0, 0.0, 0.0),

# Path: pyglm/models/model_factory.py
# def make_model(template, N=None, dt=None):
#     """ Construct a model from a template and update the specified parameters
#     """
#     if isinstance(template, str):
#         # Create the specified model
#         if template.lower() == 'standard_glm' or \
#            template.lower() == 'standardglm':
#             model = copy.deepcopy(StandardGlm)
#         elif template.lower() == 'spatiotemporal_glm':
#             model = copy.deepcopy(SpatiotemporalGlm)
#         elif template.lower() == 'shared_tuning_curve':
#             model = copy.deepcopy(SharedTuningCurveGlm)
#         elif template.lower() == 'simple_weighted_model' or \
#              template.lower() == 'simpleweightedmodel':
#             model = copy.deepcopy(SimpleWeightedModel)
#         elif template.lower() == 'simple_sparse_model' or \
#              template.lower() == 'simplesparsemodel':
#             model = copy.deepcopy(SimpleSparseModel)
#         elif template.lower() == 'sparse_weighted_model' or \
#              template.lower() == 'sparseweightedmodel':
#             model = copy.deepcopy(SparseWeightedModel)
#         elif template.lower() == 'sbm_weighted_model' or \
#              template.lower() == 'sbmweightedmodel':
#             model = copy.deepcopy(SbmWeightedModel)
#         elif template.lower() == 'distance_weighted_model' or \
#              template.lower() == 'distanceweightedmodel':
#             model = copy.deepcopy(DistanceWeightedModel)
#         else:
#             raise Exception("Unrecognized template model: %s!" % template)
#     elif isinstance(template, dict):
#         model = copy.deepcopy(template)
#     else:
#         raise Exception("Unrecognized template model!")
# 
#     # Override template model parameters
#     if N is not None:
#         model['N'] = N
# 
#     if dt is not None:
#         model['dt'] = dt
# 
#     # # Update other parameters as necessary
#     # if template.lower() == 'distance_weighted_model' or \
#     #    template.lower() == 'distanceweightedmodel':
#     #     #model['network']['graph']['location_prior']['sigma'] = N/2.0/3.0
#     #     model['network']['graph']['location_prior']['mu'] = \
#     #         np.tile(np.arange(N).reshape((N,1)),
#     #                 [1,model['network']['graph']['N_dims']]).ravel()
# 
#     return model
# 
# Path: pyglm/utils/avg_dicts.py
# def average_list_of_dicts(smpls):
#     """ Average a list of dictionaries, e.g. a list of samples from
#         the MCMC loop. The dictionary elements may themselves be
#         dictionaries, so work recursively and only average the leaves.
#     """
#     N_smpls = len(smpls)
#     import copy
#     avg = copy.deepcopy(smpls[0])
# 
#     def inc_avg(avg, smpl):
#         """ Helper to recrusively add to the average
#         """
#         if isinstance(smpl, dict):
#             for (key,val) in smpl.items():
#                 if isinstance(val, dict) or \
#                   isinstance(val, list):
#                   # Recurse if the entry is another dict
#                     avg[key] = inc_avg(avg[key], val)
#                 elif isinstance(val, np.ndarray):
#                     # Otherwise increment the value
#                     avg[key] = avg[key].astype(np.float) + \
#                                val.astype(np.float)
#                 else:
#                     # Who knows if this will work without casting!
#                     avg[key] += val
#         
#         elif isinstance(smpl, list):
#             for (i,val) in enumerate(smpl):
#                 if isinstance(val, list) or \
#                    isinstance(val, dict):
#                     # Recurse if the entry is another iterable
#                     avg[i] = inc_avg(avg[i], val)
#                 elif isinstance(val, np.ndarray):
#                     avg[i] = avg[i].astype(np.float) + \
#                              val.astype(np.float)
#                 else:
#                     # Who knows if this will work without casting!
#                     avg[i] += float(val)
#         return avg
# 
#     for smpl in smpls[1:]:
#         avg = inc_avg(avg, smpl)
# 
#     def norm_avg(avg, N_smpls):
#         """ Normalize the average by dividing by N_smpls
#         """
#         if isinstance(avg, dict):
#             for (key,val) in avg.items():
#                 if isinstance(val, dict) or \
#                    isinstance(val, list):
#                     avg[key] = norm_avg(val, N_smpls)
#                 else:
#                     avg[key] /= float(N_smpls)
#         elif isinstance(avg, list):
#             for (i,val) in enumerate(avg):
#                 if isinstance(val, list) or \
#                    isinstance(val, dict):
#                     # Recurse if the entry is another iterable
#                     avg[i] = norm_avg(val, N_smpls)
#                 else:
#                     avg[i] /= float(N_smpls)
#                         
#         return avg
# 
#     avg = norm_avg(avg, N_smpls)
#     return avg


# Path: pyglm/plotting/plot_residuals.py
import os
import cPickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from pyglm.models.model_factory import make_model
from population import Population
from pyglm.utils.avg_dicts import average_list_of_dicts
    from test.synth_harness import initialize_test_harness




matplotlib.use('Agg')       # To enable saving remotely




def make_rwb_cmap():
    # Get a red-white-black cmap
    cdict = {'red': ((0.0, 1.0, 1.0),
                 (0.5, 1.0, 1.0),
                 (1.0, 0.0, 0.0)),
        'green': ((0.0, 0.0, 0.0),

                  (0.5, 1.0, 1.0),