sotb-wrapper

This repo shows how to use SEISCOPE optimization toolbox Fortran code from Python

https://github.com/ofmla/seiscope_opt_toolbox_w_ctypes

Science Score: 67.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 1 DOI reference(s) in README
  • Academic publication links
    Links to: zenodo.org
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (13.9%) to scientific vocabulary

Keywords

ctypes-wrapper fortran fortran-package-manager geophysics gradient-based-optimisation python-bindings wrapper-library
Last synced: 4 months ago · JSON representation ·

Repository

This repo shows how to use SEISCOPE optimization toolbox Fortran code from Python

Basic Info
  • Host: GitHub
  • Owner: ofmla
  • License: mit
  • Language: Fortran
  • Default Branch: main
  • Homepage:
  • Size: 2.39 MB
Statistics
  • Stars: 26
  • Watchers: 2
  • Forks: 7
  • Open Issues: 1
  • Releases: 5
Topics
ctypes-wrapper fortran fortran-package-manager geophysics gradient-based-optimisation python-bindings wrapper-library
Created almost 5 years ago · Last pushed about 2 years ago
Metadata Files
Readme License Citation

README.md

GitHub release (latest by date) Build Status last-commit DOI codecov Code style: black fpm Fortran

sotb-wrapper: A Python wrapper for the SEISCOPE optimization toolbox (using Ctypes)

This repo demonstrates how it is possible to use the SEISCOPE optimization toolbox (written in Fortran) from Python. The original code is public domain and was written by Ludovic Métivier and Romain Brossier. Minor changes to the original code have been made to allow the call of the gradient-based optimization subroutines from Python. Such changes and some improvements are listed as follows. * The original source organized in 6 subdirectories (each of which is associated with one gradient-based algorithm) was placed in only one folder in a modular fashion. That is, one module for each optimization algorithm grouping the procedures from each one of the old subdirectories. * The Euclidean vector norm and scalar product calculations were replaced with calls to the intrinsic Fortran norm2 and dot_product functions, respectively. * Removing Trivial Code Duplication: i.e., same procedures in Steepest Descent and Preconditioned Nonlinear Conjugate Gradient subdirectories. * Removing unused variable declarations. * Vectors of lower and upper bounds (box constraints) are now optional arguments in the optimization subroutines instead of array components of a derived data type

The SEISCOPE toolbox uses a derived data type (optim); functionality that is not yet supported at this time by f2py - and for this reason it is used ctypes. The optim data type is maintained, but without allocatable arrays.

The repo contains a src directory with the modified fortran source files and another named apps where each method is used to find the minimum of the banana Rosenbrock function. The python wrapper for the SEISCOPE optimization toolbox is found inside the sotb_wrapper directory. A test directory includes a script to check that the wrapper has suceeded in reproducing the results of the original fortran code.

Install Seiscope optimization toolbox (sotb)

If you only want to use the Fortran library, you can simply clone the repo and build it with Fortran Package Manager or CMake. In the first case you just need to run bash fpm build --profile release This command creates the library in static form, as originally designed as well as executable files from demo codes.

To use sotb within your fpm project, add the following to your fpm.toml file:

yml [dependencies] sotb = { git="https://github.com/ofmla/seiscope_opt_toolbox_w_ctypes.git" } In the second case, you can run a workflow as the following: bash FC=gfortran cmake -B _build -DCMAKE_INSTALL_PREFIX=$PREFIX -DCMAKE_BUILD_TYPE=Release cmake --build _build cmake --install _build where you need to replace $PREFIX with the desired directory.

Examples of use of sotb can be found in the app folder, which contains a folder with an example for each one of the optimization algorithms available in the library. The executable files for each example are built with cmake invocation above and made available at $PREFIX/bin folder. As mentioned before, when you use fpm, executable files for the examples are also created. In this latest case, you can use fpm run --profile release <test_name> to run an specific example. So, if you want to run the example that uses the limited-memory version of Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) algorithm, simply run fpm run --profile release test_LBFGS. If you run fpm run --profile release you can see the names of the six available examples. You can also find a simple example on calling the Fortran subroutines from a C main program in the c_code directory. The example uses the L-BFGS to minimize the Rosenbrock's "banana function". Assuming that $PREFIX points to the repository root directory, you can create the executable from c_code directory, by running bash cmake -S. -B _build -DCMAKE_PREFIX_PATH="`pwd`/../../" cmake --build _build or bash cmake -S. -B _build -Dsotb_DIR="`pwd`/../../lib/cmake/sotb" cmake --build _build

Install the python wrapper of sotb (sotb-wrapper)

To install the Python API with the embedded sotb shared library you can use pip. bash pip install sotb-wrapper It is also possible to install directly from the GitHub repository. You will need a Fortran compiler such as GFortran to compile the shared library but the whole process is automated via scikit-build. bash pip install git+https://github.com/ofmla/seiscope_opt_toolbox_w_ctypes

Usage

The following example demonstrates how to define and solve the classical Rosenbrock problem ```python import numpy as np from sotb_wrapper import interface

Declare the objective function

def rosenbrock(X): """ http://en.wikipedia.org/wiki/Rosenbrock_function A generalized implementation is available as the scipy.optimize.rosen function """ a = 1. - X[0] b = X[1] - X[0]X[0] return aa + bb100., np.array([-a2. - 400.X[0]b, 200.b], dtype=np.float32)

Create an instance of the SEISCOPE optimization toolbox wrapper (sotb_wrapper) Class.

sotb = interface.sotb_wrapper() n = 2 # dimension flag = 0 # first flag; 0 means initialization X = np.ones(2, dtype=np.float32)*-1. # initial guess

computation of the cost and gradient associated with the initial guess

fcost, grad = rosenbrock(X)

copy of grad in grad_preco: no preconditioning in this test

grad_preco = np.copy(grad)

Set parameters of the UserDefined derived type in Fortran (ctype structure).

The first two parameters are mandatory; all others are optional.

sotb.set_inputs(fcost, 10000, conv=1e-8, l=10)

optimization loop: while convergence not reached or linesearch not failed, iterate

while (flag != 2 and flag != 4): flag = sotb.PSTD(n, X, fcost, grad, gradpreco, flag) if flag == 1: # compute cost and gradient at point x fcost, grad = rosenbrock(X) # no preconditioning in this test: simply copy grad in gradpreco grad_preco = np.copy(grad) print('FINAL iterate is : ', X) ```

The code above is part of a tutorial in the form of a Jupyter notebook (rosenbrock.ipynb) provided in the examples subdirectory. The goal of the tutorial is show you how one can use sotb-wrapper to find a minimum for a problem, which can optionally be subject to bound constraints (also called box constraints). The directory also includes examples in the context of geophysical inversion. Note that you must have Devito in order to be able to run them. A python script plot_curves.py is also provide in the examples directory. It may not be the best implementation and is intended for illustrative purposes only.

The following figures were obtained with the plot_curves.py script after ran one of the examples (lsrtm_aniso.py).

License

sotb-wrapper is distributed under the MIT license. See the included LICENSE file for details.

See also

  • SEISCOPE optimization toolbox paper: https://library.seg.org/doi/10.1190/geo2015-0031.1
  • Original source code: http://seiscope2.osug.fr/IMG/tgz/TOOLBOX22092014OPTIMIZATION.tgz

Owner

  • Name: Oscar Mojica
  • Login: ofmla
  • Kind: user
  • Company: SENAI CIMATEC Supercomputing Center

Geoscientist with a little bit of knowledge in programming.

Citation (CITATION.cff)

# This CITATION.cff file was generated with cffinit.
# Visit https://bit.ly/cffinit to generate yours today!

cff-version: 1.2.0
title: sotb-wrapper
message: >-
  If you use this software, please cite it using the
  metadata from this file.
type: software
authors:
  - given-names: Oscar Fabian
    family-names: Mojica
    email: o_mojical@hotmail.com
identifiers:
  - type: doi
    value: 10.5281/zenodo.5846111
    description: The versioned DOI for version 1.0.1 of the work
  - type: url
    value: >-
      https://github.com/ofmla/seiscope_opt_toolbox_w_ctypes/releases/tag/v1.0.1
    description: The GitHub release URL of tag 1.0.1
license: MIT
commit: 03f8403c5c46c6c29464239f42864aa08cf88710
version: 1.0.1
date-released: '2022-01-13'

GitHub Events

Total
  • Watch event: 6
Last Year
  • Watch event: 6

Committers

Last synced: almost 2 years ago

All Time
  • Total Commits: 145
  • Total Committers: 1
  • Avg Commits per committer: 145.0
  • Development Distribution Score (DDS): 0.0
Past Year
  • Commits: 6
  • Committers: 1
  • Avg Commits per committer: 6.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
ofmla o****l@h****m 145

Issues and Pull Requests

Last synced: over 1 year ago

All Time
  • Total issues: 1
  • Total pull requests: 5
  • Average time to close issues: N/A
  • Average time to close pull requests: 12 days
  • Total issue authors: 1
  • Total pull request authors: 3
  • Average comments per issue: 1.0
  • Average comments per pull request: 0.8
  • Merged pull requests: 3
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • AtilaSaraiva (1)
Pull Request Authors
  • ofmla (3)
  • AtilaSaraiva (1)
  • aavbsouza (1)
Top Labels
Issue Labels
Pull Request Labels

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 96 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 3
  • Total maintainers: 1
pypi.org: sotb-wrapper

wrapper to call fortran routines from SEISCOPE optimization toolbox

  • Versions: 3
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 96 Last month
Rankings
Dependent packages count: 7.4%
Forks count: 14.3%
Stargazers count: 15.2%
Downloads: 15.9%
Average: 24.3%
Dependent repos count: 68.9%
Maintainers (1)
Last synced: 4 months ago

Dependencies

.github/workflows/build_wheels.yml actions
  • actions/checkout v3 composite
  • actions/download-artifact v3 composite
  • actions/upload-artifact v3 composite
  • pypa/cibuildwheel v2.3.1 composite
  • pypa/gh-action-pypi-publish release/v1 composite
.github/workflows/flake8.yml actions
  • actions/checkout v3 composite
  • wntrblm/nox 2023.04.22 composite
.github/workflows/fortran.yml actions
  • actions/checkout v2 composite
  • fortran-lang/setup-fpm v4 composite
.github/workflows/python.yml actions
  • actions/checkout v3 composite
  • actions/download-artifact v3 composite
  • actions/setup-python v3 composite
  • actions/upload-artifact v3 composite
  • codecov/codecov-action v3 composite
pyproject.toml pypi
requirements-dev.txt pypi
  • black * development
  • darglint * development
  • flake8 * development
  • flake8-annotations * development
  • flake8-black * development
  • flake8-bugbear * development
  • flake8-docstrings * development
  • flake8-import-order * development
  • isort * development
  • mypy * development
  • nox * development
  • pip * development
  • pytest * development
  • pytest-cov * development
  • types-pkg_resources * development
requirements.txt pypi
  • cmake *
  • ninja *
  • numpy *
  • scikit-build *
setup.py pypi