Пример #1
0
    def importCellTemplate(self, modelParameters):
        try:
            with redirect_stdout(sys.__stdout__):
                rule = modelParameters["label"]
                # Get Current dir
                owd = os.getcwd()

                conds = {} if rule not in self.netParams.cellParams else self.netParams.cellParams[
                    rule]['conds']

                compileModMechFiles(modelParameters["compileMod"],
                                    modelParameters["modFolder"])

                del modelParameters["modFolder"]
                del modelParameters["compileMod"]
                # import cell template
                self.netParams.importCellParams(**modelParameters, conds=conds)

                # convert fron netpyne.specs.dict to dict
                self.netParams.cellParams[rule] = self.netParams.cellParams[
                    rule].todict()

                return utils.getJSONReply()
        except:
            return utils.getJSONError(
                "Error while importing the NetPyNE cell template",
                sys.exc_info())
        finally:
            os.chdir(owd)
Пример #2
0
 def exportNeuroML(self, modelParams):
     try:
         with redirect_stdout(sys.__stdout__):
             sim.exportNeuroML2(modelParams['fileName'], specs.SimConfig())
         return utils.getJSONReply()
     except:
         return utils.getJSONError(
             "Error while exporting the NetPyNE model", sys.exc_info())
Пример #3
0
    def importModel(self, modelParameters):
        """ Imports a model stored in form of Python files.

        :param modelParameters:
        :return:
        """
        if self.doIhaveInstOrSimData()['haveInstance']:
            # TODO: this must be integrated into the general lifecycle of "model change -> simulate"
            #   Shouldn't be specific to Import
            sim.clearAll()

        try:
            # Get Current dir
            owd = os.getcwd()

            compileModMechFiles(modelParameters['compileMod'],
                                modelParameters['modFolder'])

            with redirect_stdout(sys.__stdout__):
                # NetParams
                net_params_path = str(modelParameters["netParamsPath"])
                sys.path.append(net_params_path)
                os.chdir(net_params_path)
                # Import Module
                net_params_module_name = importlib.import_module(
                    str(modelParameters["netParamsModuleName"]))
                # Import Model attributes
                self.netParams = getattr(
                    net_params_module_name,
                    str(modelParameters["netParamsVariable"]))

                for key, value in self.netParams.cellParams.items():
                    if hasattr(value, 'todict'):
                        self.netParams.cellParams[key] = value.todict()

                # SimConfig
                sim_config_path = str(modelParameters["simConfigPath"])
                sys.path.append(sim_config_path)
                os.chdir(sim_config_path)
                # Import Module
                sim_config_module_name = importlib.import_module(
                    str(modelParameters["simConfigModuleName"]))
                # Import Model attributes
                self.simConfig = getattr(
                    sim_config_module_name,
                    str(modelParameters["simConfigVariable"]))

                # TODO: when should sim.initialize be called?
                #   Only on import or better before every simulation or network instantiation?
                sim.initialize()
            return utils.getJSONReply()
        except:
            return utils.getJSONError(
                "Error while importing the NetPyNE model", sys.exc_info())
        finally:
            os.chdir(owd)
Пример #4
0
    def deleteModel(self, modelParams):
        try:
            with redirect_stdout(sys.__stdout__):
                self.netParams = specs.NetParams()
                self.simConfig = specs.SimConfig()
                self.netParams.todict()
                self.netParams.todict()
                if self.doIhaveInstOrSimData()['haveInstance']: sim.clearAll()
                self.geppetto_model = None
            return utils.getJSONReply()

        except:
            return utils.getJSONError(
                "Error while exporting the NetPyNE model", sys.exc_info())
Пример #5
0
    def deleteModel(self, modelParams):
        try:
            with redirect_stdout(sys.__stdout__):
                self.netParams = specs.NetParams()
                self.simConfig = specs.SimConfig()
                sim.initialize(specs.NetParams(), specs.SimConfig())
                self.geppetto_model = None
        except Exception:
            message = "Error while exporting the NetPyNE model"
            logging.exception(message)
            return utils.getJSONError(message, sys.exc_info())

        try:
            sim.clearAll()
        except:
            logging.exception("Failed to clear simulation")

        return utils.getJSONReply()
Пример #6
0
 def exportModel(self, args):
     try:
         with redirect_stdout(sys.__stdout__):
             if not args['netCells']:
                 sim.initialize(netParams=self.netParams,
                                simConfig=self.simConfig)
             sim.cfg.filename = args['fileName']
             include = [
                 el for el in specs.SimConfig().saveDataInclude
                 if el in args.keys() and args[el]
             ]
             if args['netCells']: include += ['netPops']
             sim.cfg.saveJson = True
             sim.saveData(include)
             sim.cfg.saveJson = False
         return utils.getJSONReply()
     except:
         return utils.getJSONError(
             "Error while exporting the NetPyNE model", sys.exc_info())
Пример #7
0
    def importModel(self, modelParameters):
        try:
            # Get Current dir
            owd = os.getcwd()

            self.compileModMechFiles(modelParameters['compileMod'],
                                     modelParameters['modFolder'])

            with redirect_stdout(sys.__stdout__):
                # NetParams
                netParamsPath = str(modelParameters["netParamsPath"])
                sys.path.append(netParamsPath)
                os.chdir(netParamsPath)
                # Import Module
                netParamsModuleName = importlib.import_module(
                    str(modelParameters["netParamsModuleName"]))
                # Import Model attributes
                self.netParams = getattr(
                    netParamsModuleName,
                    str(modelParameters["netParamsVariable"]))

                for key, value in self.netParams.cellParams.items():
                    if hasattr(value, 'todict'):
                        self.netParams.cellParams[key] = value.todict()

                # SimConfig
                simConfigPath = str(modelParameters["simConfigPath"])
                sys.path.append(simConfigPath)
                os.chdir(simConfigPath)
                # Import Module
                simConfigModuleName = importlib.import_module(
                    str(modelParameters["simConfigModuleName"]))
                # Import Model attributes
                self.simConfig = getattr(
                    simConfigModuleName,
                    str(modelParameters["simConfigVariable"]))

            return utils.getJSONReply()
        except:
            return utils.getJSONError(
                "Error while importing the NetPyNE model", sys.exc_info())
        finally:
            os.chdir(owd)
Пример #8
0
    def deleteModel(self, modelParams):
        try:
            with redirect_stdout(sys.__stdout__):
                self.netParams = specs.NetParams()
                self.simConfig = specs.SimConfig()
                sim.initialize(specs.NetParams(), specs.SimConfig())
                self.geppetto_model = None
        except:
            return utils.getJSONError(
                "Error while exporting the NetPyNE model", sys.exc_info())

        try:
            # This function fails is some keys don't exists
            # sim.clearAll()
            # TODO: as part of #264 we should remove the method and use clearAll intstead
            self.clearSim()
        except:
            pass

        return utils.getJSONReply()
Пример #9
0
    def loadModel(self, args):
        """ Imports a model stored as file in json format.

        :param args:
        :return:
        """
        def remove(dictionary):
            # remove reserved keys such as __dict__, __Method__, etc
            # they appear when we do sim.loadAll(json_file)
            if isinstance(dictionary, dict):
                for key, value in list(dictionary.items()):
                    if key.startswith('__'):
                        dictionary.pop(key)
                    else:
                        remove(value)

        if not any([
                args[option] for option in
            ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
        ]):
            return utils.getJSONError(
                "Error while loading data",
                'You have to select at least one option')

        try:
            owd = os.getcwd()
            compileModMechFiles(args['compileMod'], args['modFolder'])
        except:
            return utils.getJSONError("Error while importing/compiling mods",
                                      sys.exc_info())
        finally:
            os.chdir(owd)

        try:
            with redirect_stdout(sys.__stdout__):
                sim.initialize()
                wake_up_geppetto = False
                if all([
                        args[option] for option in
                    ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
                ]):
                    wake_up_geppetto = True
                    if self.doIhaveInstOrSimData()['haveInstance']:
                        sim.clearAll()
                    sim.initialize()
                    sim.loadAll(args['jsonModelFolder'])
                    self.netParams = sim.net.params
                    self.simConfig = sim.cfg
                    remove(self.netParams.todict())
                    remove(self.simConfig.todict())
                else:
                    if args['loadNet']:
                        wake_up_geppetto = True
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.initialize()
                        sim.loadNet(args['jsonModelFolder'])

                    if args['loadSimData']:  # TODO (https://github.com/Neurosim-lab/netpyne/issues/360)
                        wake_up_geppetto = True
                        if not self.doIhaveInstOrSimData()['haveInstance']:
                            sim.create(specs.NetParams(), specs.SimConfig())
                            sim.net.defineCellShapes()
                            sim.gatherData(gatherLFP=False)
                        sim.loadSimData(args['jsonModelFolder'])

                    if args['loadSimCfg']:
                        sim.loadSimCfg(args['jsonModelFolder'])
                        self.simConfig = sim.cfg
                        remove(self.simConfig.todict())

                    if args['loadNetParams']:
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.loadNetParams(args['jsonModelFolder'])
                        self.netParams = sim.net.params
                        remove(self.netParams.todict())

                if wake_up_geppetto:
                    if len(sim.net.cells) > 0:
                        section = list(sim.net.cells[0].secs.keys())[0]
                        if 'pt3d' not in list(
                                sim.net.cells[0].secs[section].geom.keys()):
                            sim.net.defineCellShapes()
                            sim.gatherData()
                            sim.loadSimData(args['jsonModelFolder'])

                    sim.gatherData()
                    self.geppetto_model = self.model_interpreter.getGeppettoModel(
                        sim)
                    return json.loads(
                        GeppettoModelSerializer.serialize(self.geppetto_model))
                else:
                    return utils.getJSONReply()
        except:
            return utils.getJSONError("Error while loading the NetPyNE model",
                                      sys.exc_info())
Пример #10
0
    def exportHLS(self, args):
        def convert2bool(string):
            return string.replace('true', 'True').replace('false',
                                                          'False').replace(
                                                              'null', 'False')

        def header(title, spacer='-'):
            return '\n# ' + title.upper() + ' ' + spacer * (77 -
                                                            len(title)) + '\n'

        try:
            params = ['popParams', 'cellParams', 'synMechParams']
            params += ['connParams', 'stimSourceParams', 'stimTargetParams']

            fname = args['fileName'] if args['fileName'][
                -3:] == '.py' else args['fileName'] + '.py'

            with open(fname, 'w') as script:
                script.write('from netpyne import specs, sim\n')
                script.write(header('documentation'))
                script.write(
                    "''' Script generated with NetPyNE-UI. Please visit:\n")
                script.write(
                    "    - https://www.netpyne.org\n    - https://github.com/MetaCell/NetPyNE-UI\n'''\n"
                )
                script.write(header('script', spacer='='))
                script.write('netParams = specs.NetParams()\n')
                script.write('simConfig = specs.SimConfig()\n')
                script.write(header('single value attributes'))
                for attr, value in list(self.netParams.__dict__.items()):
                    if attr not in params:
                        if value != getattr(specs.NetParams(), attr):
                            script.write('netParams.' + attr + ' = ')
                            script.write(
                                convert2bool(json.dumps(value, indent=4)) +
                                '\n')

                script.write(header('network attributes'))
                for param in params:
                    for key, value in list(
                            getattr(self.netParams, param).items()):
                        script.write("netParams." + param + "['" + key +
                                     "'] = ")
                        script.write(
                            convert2bool(json.dumps(value, indent=4)) + '\n')

                script.write(header('network configuration'))
                for attr, value in list(self.simConfig.__dict__.items()):
                    if value != getattr(specs.SimConfig(), attr):
                        script.write('simConfig.' + attr + ' = ')
                        script.write(
                            convert2bool(json.dumps(value, indent=4)) + '\n')

                script.write(header('create simulate analyze  network'))
                script.write(
                    '# sim.createSimulateAnalyze(netParams=netParams, simConfig=simConfig)\n'
                )

                script.write(header('end script', spacer='='))

            return utils.getJSONReply()

        except:
            return utils.getJSONError(
                "Error while importing the NetPyNE model", sys.exc_info())
Пример #11
0
    def loadModel(self, args):
        """ Imports a model stored as file in json format.

        :param args:
        :return:
        """
        if not any([
                args[option] for option in
            ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
        ]):
            return utils.getJSONError(
                "Error while loading data",
                'You have to select at least one option')

        try:
            owd = os.getcwd()
            compileModMechFiles(args['compileMod'], args['modFolder'])
        except Exception:
            message = "Error while importing/compiling mods"
            logging.exception(message)
            return utils.getJSONError(message, sys.exc_info())
        finally:
            os.chdir(owd)

        try:
            with redirect_stdout(sys.__stdout__):
                sim.initialize()
                wake_up_geppetto = False
                if all([
                        args[option] for option in
                    ['loadNetParams', 'loadSimCfg', 'loadSimData', 'loadNet']
                ]):
                    wake_up_geppetto = True
                    if self.doIhaveInstOrSimData()['haveInstance']:
                        sim.clearAll()
                    sim.initialize()
                    sim.loadAll(args['jsonModelFolder'])
                    self.netParams = sim.net.params
                    self.simConfig = sim.cfg
                    netpyne_ui_utils.remove(self.netParams.todict())
                    netpyne_ui_utils.remove(self.simConfig.todict())
                else:
                    if args['loadNet']:
                        wake_up_geppetto = True
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.initialize()
                        sim.loadNet(args['jsonModelFolder'])

                    # TODO (https://github.com/Neurosim-lab/netpyne/issues/360)
                    if args['loadSimData']:
                        wake_up_geppetto = True
                        if not self.doIhaveInstOrSimData()['haveInstance']:
                            sim.create(specs.NetParams(), specs.SimConfig())
                            sim.net.defineCellShapes()
                            sim.gatherData(gatherLFP=False)
                        sim.loadSimData(args['jsonModelFolder'])

                    if args['loadSimCfg']:
                        sim.loadSimCfg(args['jsonModelFolder'])
                        self.simConfig = sim.cfg
                        netpyne_ui_utils.remove(self.simConfig.todict())

                    if args['loadNetParams']:
                        if self.doIhaveInstOrSimData()['haveInstance']:
                            sim.clearAll()
                        sim.loadNetParams(args['jsonModelFolder'])
                        self.netParams = sim.net.params
                        netpyne_ui_utils.remove(self.netParams.todict())

                if wake_up_geppetto:
                    self._create3D_shapes(args['jsonModelFolder'])

                    # TODO: Fix me - gatherData will remove allSimData!
                    sim.gatherData()

                    self.geppetto_model = self.model_interpreter.getGeppettoModel(
                        sim)
                    return json.loads(
                        GeppettoModelSerializer.serialize(self.geppetto_model))
                else:
                    return utils.getJSONReply()
        except Exception:
            message = "Error while loading the NetPyNE model"
            logging.exception(message)
            return utils.getJSONError(message, sys.exc_info())