Skip to content

sund.install_model

sund.install_model(model, force=False, save_compiled_model=None, keepcfile=None)

Installs one or more models, making it available for import.

Parameters:

Name Type Description Default
model string | list[string]

Model content string or path to model file (str). Can also be a list of such strings. File names can be a regular expression to install multiple models at the same time.

required
force bool

If True, will force reinstallation even if model is already installed. Defaults to False.

False
save_compiled_model bool

If True, will not delete the generated c++-file. Defaults to False.

None
keepcfile bool

Deprecated. Use save_compiled_model instead. Defaults to None.

None

Raises:

Type Description
ValueError

Could not find file, if the file is missing.

ValueError

Model *name* is already installed and up to date, if an identical model is already installed.

ValueError

Model *name* has already been imported to memory, you will need to restart Python before re-installing the model, if the model has already been imported.

ValueError

Error while installing, an unknown error occured while installing the model.

Source code in src/sund/__init__.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def install_model(model:str|list[str], force:bool = False, save_compiled_model:bool = None, keepcfile:bool = None):
    """Installs one or more models, making it available for import.

    Args:
        model (string | list[string]): Model content string or path to model file (str). Can also be a list of such strings. File names can be a regular expression to install multiple models at the same time.
        force (bool, optional): If True, will force reinstallation even if model is already installed. Defaults to False.
        save_compiled_model (bool, optional): If True, will not delete the generated c++-file. Defaults to False.
        keepcfile (bool, optional): Deprecated. Use save_compiled_model instead. Defaults to None.

    Raises:
        ValueError: `Could not find file`, if the file is missing. 
        ValueError: `Model *name* is already installed and up to date`, if an identical model is already installed. 
        ValueError: `Model *name* has already been imported to memory, you will need to restart Python before re-installing the model`, if the model has already been imported.  
        ValueError: `Error while installing`, an unknown error occured while installing the model. 
    """

    # REMOVE WITH NEXT MAJOR RELEASE
    # Deprecated arguments
    if (save_compiled_model != None and keepcfile != None):
        raise SyntaxError("Only either of 'save_compiled_model' and 'keepcfile' can be set!")

    if (keepcfile != None):
        warnings.warn("The 'keepcfile' argument is deprecated and will be removed in a future version. Use the 'save_compiled_model' argument instead!", FutureWarning, 2)
        save_compiled_model = keepcfile
    elif (save_compiled_model == None):
        save_compiled_model = False

    if type(model) is list:
        for m in model:
            install_model(m)
    else:

        # Check if input is a model string, or a model file
        if _is_model_content_string(model):
            models = [model]
        else:
            models = list(Path().glob(model))
            if len(models) == 0:
                raise ValueError('Could not find file "{}"'.format(model))
            models = [str(m.resolve()) for m in models]

        ModelsFolder = Path(__file__).parent / "Models"

        for m in models:
            if _is_model_content_string(m):
                model_content = m
                latest_modified = time.time()
                path = Path.cwd()
            else:
                try:
                    model_path = Path(m)
                    model_content = model_path.read_text()
                except Exception as e:
                    raise ValueError(f"Error while loading the model '{m}'.") from e
                latest_modified = model_path.stat().st_mtime
                path = model_path.parent.resolve()

            model = tools._modelStructure(model_content, file_path=str(path))
            # if not force install, check if model is installed and modification time is less for text file than for module file
            modulefile = ModelsFolder / (model["NAME"] + get_config_var("EXT_SUFFIX"))

            if not force and model["NAME"] in installed_models() and latest_modified < modulefile.stat().st_mtime:
                print(f"Model '{model['NAME']}' is already installed and up to date.")
                continue

            # Check if imported
            if ("sund.Models." + model["NAME"]) in sys.modules:
                print(f"Model '{model['NAME']}' has already been imported into memory. \nTrying to unload the module, but you might need to restart Python before re-installing the model.")
                sys.modules.pop("sund.Models." + model["NAME"])
            # Check if modulefile exist on file system and remove
            if modulefile.exists():
                try:
                    modulefile.unlink()
                except:
                    raise ValueError(f"Model '{model['NAME']}' cannot be re-installed, probably because it is being used by another process. Try terminating any process that might use the model and try again.")

            # create C-file and module file
            cfile = tools._modelCFile(model)
            tools._modelModuleFile(cfile)
            if not save_compiled_model:
                Path(cfile).unlink()
            print(f"Model '{model['NAME']}' succesfully installed.")