Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 840-unit-test-testtimeline-fails
  • 875-wendland-c6-missing-neighbour-contributions
  • 887-code-does-not-compile-with-parmetis-installed-locally-but-without-metis
  • CubeTest
  • FS_Del
  • GEARRT_Iliev1
  • GEARRT_Iliev3
  • GEARRT_Iliev4
  • GEARRT_Iliev5
  • GEARRT_Iliev5-fixed-nr-subcycles
  • GEARRT_Iliev7
  • GEARRT_Iliev_static
  • GEARRT_Ivanova
  • GEARRT_fixed_nr_subcycles
  • GEARRT_injection_tests_Iliev0
  • GPU_swift
  • GrackleCoolingUpdates2
  • Lambda-T-table
  • MAGMA2
  • MAGMA2_matthieu
  • MHD_FS
  • MHD_FS_TESTs
  • MHD_FS_VP_AdvectGauge
  • MHD_Orestis
  • MHD_canvas
  • MHD_canvas_RF_128
  • MHD_canvas_RF_growth_rate
  • MHD_canvas_RobertsFlow
  • MHD_canvas_SPH_errors
  • MHD_canvas_matthieu
  • MHD_canvas_nickishch
  • MHD_canvas_nickishch_Lorentz_force_test
  • MHD_canvas_nickishch_track_everything
  • MHD_canvas_sid
  • OAK/CPAW_updates
  • OAK/LoopAdvectionTest
  • OAK/adaptive_divv
  • OAK/kinetic_dedner
  • REMIX_cosmo
  • RT_dualc
  • RT_recombination_radiation
  • RT_test_mladen
  • SIDM
  • SIDM_wKDSDK
  • SNdust
  • SPHM1RT_CosmologicalStromgrenSphere
  • SPHM1RT_bincheck
  • SPHM1RT_smoothedRT
  • TangoSIDM
  • TestPropagation3D
  • Test_fixedhProb
  • activate_fewer_comms
  • active_h_max_optimization
  • adaptive_softening_Lieuwe
  • add_2p5D
  • add_black_holes_checks
  • adding_sidm_to_master
  • agn_crksph
  • agn_crksph_subtask_speedup
  • amd-optimization
  • arm_vec
  • automatic_tasks
  • better_ray_RNG
  • black_holes_accreted_angular_momenta_from_gas
  • burkert-potential
  • c11
  • c11_atomics_copy
  • cancel_all_sorts
  • cell_exchange_improvements
  • cell_types
  • cherry-pick-cd1c39e0
  • comm_tasks_are_special
  • conduction_velocities
  • cpp-fixes
  • cuda_test
  • darwin/adaptive_softening
  • darwin/gear_chemistry_fluxes
  • darwin/gear_mechanical_feedback
  • darwin/gear_preSN_feedback
  • darwin/gear_radiation
  • darwin/simulations
  • darwin/sink_formation_proba
  • darwin/sink_mpi
  • darwin/sink_mpi_physics
  • dead-time-stats
  • derijcke_cooling
  • dev_cms
  • do-not-activate-empty-star-pairs
  • domain_zoom_nometis
  • drift_flag_debug_check
  • driven_turbulence
  • driven_turbulence_forcings
  • engineering
  • eos_updates
  • evrard_disc
  • expand_fof_2022
  • explict_bkg_cdim
  • fewer_gpart_comms
  • fewer_star_comms
  • fewer_timestep_comms_no_empty_pairs
  • v0.0
  • v0.1
  • v0.1.0-pre
  • v0.2.0
  • v0.3.0
  • v0.4.0
  • v0.5.0
  • v0.6.0
  • v0.7.0
  • v0.8.0
  • v0.8.1
  • v0.8.2
  • v0.8.3
  • v0.8.4
  • v0.8.5
  • v0.9.0
  • v1.0.0
  • v2025.01
  • v2025.04
119 results

Target

Select target project
  • dc-oman1/swiftsim
  • swift/swiftsim
  • pdraper/swiftsim
  • tkchan/swiftsim
  • dc-turn5/swiftsim
5 results
Select Git revision
  • 743-planetary-eos-selection-improvements
  • CubeTest
  • GPU_swift
  • Lambda-T-table
  • SIDM
  • SIDM_wKDSDK
  • TangoSIDM
  • Test_fixedhProb
  • active_h_max_optimization
  • add_light_cone
  • arm_vec
  • automatic_tasks
  • better_ray_RNG
  • c11
  • c11_atomics_copy
  • comm_tasks_are_special
  • cuda_test
  • debug-1558-5a66e81a-schedfix
  • dev_cms
  • dev_planetary
  • domain_zoom_nometis
  • drift_flag_debug_check
  • driven_turbulence
  • engineering
  • evrard_disc
  • expand_fof
  • fix_timestep_zoom
  • fixed_hSIDM
  • fof_improvements
  • foreign_gpart
  • generic_cache
  • genetic_partitioning2
  • gizmo
  • gizmo_entropy_switch
  • gizmo_mfv_entropy
  • hashmap_mesh
  • hbt_otf
  • ivanova-testing
  • jsw/6dfof
  • kahip
  • lean_gparts2
  • lightcone
  • lightcone_healpix
  • load-balance-testing
  • locked_hydro
  • logger_force_dump
  • logger_mat
  • loic_active_h_max
  • mass_dependent_h_max
  • master
  • merge-yb-varsndt
  • mpi-one-thread
  • mpi-packed-parts
  • mpi-send-subparts
  • mpi-send-subparts-vector
  • mpi-subparts-vector-grav
  • mpi-testsome
  • mpi-threads
  • mpi_force_checks
  • multi-lightcones
  • numa_awareness
  • parallel_exchange_cells
  • paranoid
  • phantom
  • planetary_boundary
  • planetary_example
  • planetary_imbalance
  • remove_logger
  • rename_logger
  • restart-empty-ranks
  • reweight-fitted-costs
  • reweight-scaled-costs
  • rgb-engineering
  • scheduler_determinism
  • search-window-tests
  • shadowswift
  • signal-handler-dump
  • simba-stellar-feedback
  • skeleton
  • smarter_sends
  • snipes_data
  • space_rebuild_investigation
  • spiral_potential
  • star_ghost_depth
  • subtask_speedup
  • swift_zoom_support
  • sync-send
  • task_lock_rtd
  • thread-dump-extract-waiters
  • threadpool_rmapper
  • time_sf_task
  • traphic
  • turbulence-driving
  • turbulent-potential
  • variable_hSIDM
  • whe-nu-df
  • whe-nu-flag
  • when_to_proxy
  • yb-sndev
  • yb-sndev-dev
  • v0.0
  • v0.1
  • v0.1.0-pre
  • v0.2.0
  • v0.3.0
  • v0.4.0
  • v0.5.0
  • v0.6.0
  • v0.7.0
  • v0.8.0
  • v0.8.1
  • v0.8.2
  • v0.8.3
  • v0.8.4
  • v0.8.5
  • v0.9.0
116 results
Show changes
Commits on Source (14068)
---
Language: Cpp
BasedOnStyle: Google
KeepEmptyLinesAtTheStartOfBlocks: true
PenaltyBreakAssignment: 2
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 3
SortPriority: 3
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 4
- Regex: '<[[:alnum:].]+>'
Priority: 5
- Regex: '.*'
Priority: 2
SortPriority: 0
- Regex: config.h
Priority: 1
...
*~
*.hdf5
*.dirstamp
Makefile
Makefile.in
......@@ -10,28 +12,220 @@ config.h.in
config.sub
ltmain.sh
libtool
build
swift
swift_mpi
fof
fof_mpi
src/version.h
src/version_string.h
swift*.tar.gz
doc/doxyfile.stamp
doc/html/
doc/latex/
doc/man/
doc/Doxyfile
examples/swift
examples/swift_fixdt
examples/swift_fixdt_mpi
examples/swift_mindt
examples/swift_mindt_mpi
examples/swift_mpi
tests/testVectorize
tests/brute_force.dat
tests/swift_dopair.dat
doc/RTD/source/SubgridModels/*/*.png
doc/RTD/source/RadiativeTransfer/full_dependency_graph_RT.png
examples/*/*/*.xmf
examples/*/*/*.dat
examples/*/*/*.png
examples/*/*/*.pdf
examples/*/*/*.mp4
examples/*/*/*.txt
examples/*/*/*.rst
examples/*/*/*.hdf5
examples/*/*/*.csv
examples/*/*/*.dot
examples/**/cell_hierarchy.html
examples/*/*/energy.txt
examples/**/task_level.txt
examples/*/*/timesteps_*.txt
examples/**/timesteps.txt
examples/**/SFR.txt
examples/**/statistics.txt
examples/**/partition_fixed_costs.h
examples/*/*/memuse_report-step*.dat
examples/*/*/memuse_report-step*.log
examples/*/*/restart/*
examples/*/stf_output*
examples/*/stf.*
examples/*/fof_output*
examples/*/log*
examples/*/*/used_parameters.yml
examples/*/*/unused_parameters.yml
examples/*/*/fof_used_parameters.yml
examples/*/*/fof_unused_parameters.yml
examples/*/*.mpg
examples/*/*/gravity_checks_*.dat
examples/*/*/coolingtables.tar.gz
examples/*/*/coolingtables
examples/*/*/yieldtables.tar.gz
examples/*/*/yieldtables
examples/*/*/photometry.tar.gz
examples/*/*/photometry
examples/*/*/plots
examples/*/*/snapshots
examples/*/*/restart
examples/Cooling/CoolingRates/cooling_rates
examples/Cooling/CoolingRates/cooling_element_*.dat
examples/Cooling/CoolingRates/cooling_output.dat
examples/SubgridTests/StellarEvolution/StellarEvolutionSolution*
examples/SubgridTests/CosmologicalStellarEvolution/StellarEvolutionSolution*
examples/SmallCosmoVolume/SmallCosmoVolume_DM/power_spectra
examples/SmallCosmoVolume/SmallCosmoVolume_cooling/snapshots/
examples/SmallCosmoVolume/SmallCosmoVolume_hydro/snapshots/
examples/**/CloudyData_UVB=HM2012.h5
examples/**/CloudyData_UVB=HM2012_shielded.h5
examples/**/CloudyData_UVB=HM2012_high_density.h5
examples/**/chemistry-AGB+OMgSFeZnSrYBaEu-16072013.h5
examples/**/POPIIsw.h5
examples/**/GRACKLE_INFO
examples/**/snap/
examples/SinkParticles/HomogeneousBox/snapshot_0003restart.hdf5
tests/testActivePair
tests/testActivePair.sh
tests/brute_force_periodic_BC_standard.dat
tests/swift_periodic_BC_standard.dat
tests/brute_force_periodic_BC_pertrubed.dat
tests/swift_periodic_BC_perturbed.dat
tests/brute_force_standard.dat
tests/swift_dopair_standard.dat
tests/brute_force_perturbed.dat
tests/swift_dopair_perturbed.dat
tests/test27cells
tests/test27cells_subset
tests/test27cellsStars
tests/test27cellsStars_subset
tests/testPeriodicBC
tests/test125cells
tests/brute_force_27_standard.dat
tests/swift_dopair_27_standard.dat
tests/brute_force_27_perturbed.dat
tests/swift_dopair_27_perturbed.dat
tests/star_brute_force_27_standard.dat
tests/swift_star_dopair_27_standard.dat
tests/star_brute_force_27_perturbed.dat
tests/swift_star_dopair_27_perturbed.dat
tests/brute_force_125_standard.dat
tests/swift_dopair_125_standard.dat
tests/brute_force_125_perturbed.dat
tests/swift_dopair_125_perturbed.dat
tests/brute_force_pair_active.dat
tests/brute_force_dopair2_active.dat
tests/swift_dopair2_force_active.dat
tests/brute_force_periodic_BC_perturbed.dat
tests/swift_dopair_active.dat
tests/test_nonsym_density_serial.dat
tests/test_nonsym_density_vec.dat
tests/test_nonsym_force_serial.dat
tests/test_nonsym_density_1_vec.dat
tests/test_nonsym_density_2_vec.dat
tests/test_nonsym_force_1_vec.dat
tests/test_nonsym_force_2_vec.dat
tests/potential.dat
tests/testGreetings
tests/testSelectOutput
tests/testReading
tests/input.hdf5
tests/testSingle
tests/testTimeIntegration
tests/testSPHStep
tests/testExp
tests/testErfc
tests/testKernel
tests/testKernelGrav
tests/testKernelLongGrav
tests/testFFT
tests/testInteractions
tests/testInteractions.sh
tests/testSymmetry
tests/testDistance
tests/testHydroMPIrules
tests/testMaths
tests/testAtomic
tests/testRandom
tests/testRandomSpacing
tests/testRandomPoisson
tests/testRandomCone
tests/testThreadpool
tests/testParser
tests/testFeedback
tests/parser_output.yml
tests/testPeriodicBC.sh
tests/testPeriodicBCPerturbed.sh
tests/test27cells.sh
tests/test27cellsPerturbed.sh
tests/test27cellsStars.sh
tests/test27cellsStarsPerturbed.sh
tests/test125cells.sh
tests/test125cellsPerturbed.sh
tests/testParser.sh
tests/testReading.sh
tests/testNeutrinoCosmology.sh
tests/testSelectOutput.sh
tests/unused_parser_output.yml
tests/used_parser_output.yml
tests/output_list_params.yml
tests/testAdiabaticIndex
tests/testRiemannExact
tests/testRiemannTRRS
tests/testRiemannHLLC
tests/testMatrixInversion
tests/testVoronoi1D
tests/testVoronoi2D
tests/testVoronoi3D
tests/testDump
tests/testCSDS
tests/benchmarkInteractions
tests/testGravityDerivatives
tests/testGravitySpeed
tests/testPotentialSelf
tests/testPotentialPair
tests/testEOS
tests/testEOS*.txt
tests/testEOS*.png
tests/testUtilities
tests/testCosmology
tests/testOutputList
tests/testCbrt
tests/testFormat.sh
tests/testCooling
tests/testComovingCooling
tests/testHashmap
tests/testNeutrinoCosmology
tests/testNeutrinoFermiDirac
tests/testLog
tests/testTimeline
tests/*.png
tests/*.txt
theory/latex/swift.pdf
theory/SPH/Kernels/kernels.pdf
theory/SPH/Kernels/kernel_derivatives.pdf
theory/SPH/Kernels/kernel_definitions.pdf
theory/SPH/Flavours/sph_flavours.pdf
theory/SPH/EoS/eos.pdf
theory/SPH/*.pdf
theory/paper_pasc/pasc_paper.pdf
theory/Multipoles/alpha_derivatives.pdf
theory/Multipoles/alpha_powers.pdf
theory/Multipoles/chi_derivatives.pdf
theory/Multipoles/sigma_derivatives.pdf
theory/Multipoles/fmm.pdf
theory/Multipoles/fmm_standalone.pdf
theory/Multipoles/potential.pdf
theory/Multipoles/potential_long.pdf
theory/Multipoles/potential_short.pdf
theory/Multipoles/force_short.pdf
theory/Multipoles/mac_potential.pdf
theory/Cosmology/cosmology.pdf
theory/Cooling/eagle_cooling.pdf
theory/Gizmo/gizmo-implementation-details/gizmo-implementation-details.pdf
theory/RadiativeTransfer/GEARRT/GEARRT.pdf
m4/libtool.m4
m4/ltoptions.m4
......@@ -49,6 +243,12 @@ m4/lt~obsolete.m4
/stamp-h1
/test-driver
src/equation_of_state/planetary/*.txt
# Intel compiler optimization reports
*.optrpt
*.opt.yaml
# Object files
.deps/
*.o
......@@ -93,6 +293,9 @@ m4/lt~obsolete.m4
*.out
*.toc
## Figures
*.svg
## Intermediate documents:
*.dvi
*-converted-to.*
......@@ -183,9 +386,26 @@ _minted*
*.sympy
sympy-plots-for-*.tex/
# python
*.pyc
# todonotes
*.tdo
# xindy
*.xdy
# macOS
*.DS_Store
#ctags
*tags
# vim
*.swp
# black formatting
black_formatting_env
# vscode
*.json
[submodule "csds"]
path = csds
url = https://gitlab.cosma.dur.ac.uk/lhausammann/csds-reader.git
Matthieu Schaller schaller@strw.leidenuniv.nl
Pedro Gonnet gonnet@google.com
Matthieu Schaller matthieu.schaller@durham.ac.uk
Aidan Chalk aidan.chalk@durham.ac.uk
Peter W. Draper p.w.draper@durham.ac.uk
Bert Vandenbrouck bert.vandenbroucke@gmail.com
Bert Vandenbroucke bert.vandenbroucke@gmail.com
James S. Willis james.s.willis@durham.ac.uk
John A. Regan john.a.regan@durham.ac.uk
Angus Lepper angus.lepper@ed.ac.uk
Tom Theuns tom.theuns@durham.ac.uk
Richard G. Bower r.g.bower@durham.ac.uk
Stefan Arridge stefan.arridge@durham.ac.uk
Josh Borrow joshua.borrow@durham.ac.uk
Loic Hausammann loic.hausammann@epfl.ch
Yves Revaz yves.revaz@epfl.ch
Jacob Kegerreis jacob.kegerreis@durham.ac.uk
Mladen Ivkovic mladen.ivkovic@durham.ac.uk
Stuart McAlpine stuart.mcalpine@helsinki.fi
Folkert Nobels nobels@strw.leidenuniv.nl
John Helly j.c.helly@durham.ac.uk
Alexei Borissov alexei.borissov@ed.ac.uk
Yannick Bahe bahe@strw.leidenuniv.nl
Roi Kugel kugel@strw.leidenuniv.nl
Evgenii Chaikin chaikin@strw.leidenuniv.nl
Sylvia Ploeckinger ploeckinger@lorentz.leidenuniv.nl
Willem Elbers willem.h.elbers@durham.ac.uk
TK Chan chantsangkeung@gmail.com
Marcel van Daalen daalen@strw.leidenuniv.nl
Filip Husko filip.husko@durham.ac.uk
Orestis Karapiperis karapiperis@lorentz.leidenuniv.nl
Stan Verhoeve s06verhoeve@gmail.com
Nikyta Shchutskyi shchutskyi@lorentz.leidenuniv.nl
Will Roper w.roper@sussex.ac.uk
Darwin Roduit darwin.roduit@alumni.epfl.ch
Jonathan Davies j.j.davies@ljmu.ac.uk
cff-version: 1.2.0
title: >-
SWIFT: SPH With Inter-dependent Fine-grained
Tasking
message: 'If you use this software, please cite it as below'
type: software
authors:
- given-names: Matthieu
family-names: Schaller
email: schaller@strw.leidenuniv.nl
affiliation: Leiden University
orcid: 'https://orcid.org/0000-0002-2395-4902'
- given-names: Gonnet
family-names: Pedro
- given-names: Peter
family-names: Draper
- given-names: Aidan
family-names: Chalk
- given-names: Bert
family-names: Vandenbroucke
- given-names: James
family-names: Willis
- given-names: Richard
family-names: Bower
- given-names: Josh
family-names: Borrow
- given-names: Loic
family-names: Hausammann
- given-names: Yves
family-names: Revaz
- given-names: Jacob
family-names: Kegerreis
- given-names: Mladen
family-names: Ivkovic
- given-names: Stuart
family-names: McAlpine
- given-names: Folkert
family-names: Nobels
- given-names: John
family-names: Helly
- given-names: Yannick
family-names: Bahé
- given-names: Willem
family-names: Elbers
- given-names: Filip
family-names: Husko
The SWIFT source code is using a variation of the 'Google' formatting style.
The script 'format.sh' in the root directory applies the clang-format-18
tool with our style choices to all the SWIFT C source file. Please apply
the formatting script to the files before submitting a merge request.
The Python scripts in the repository use default formatting enforced by
'black'. Since 'black' formatting still strongly depends on the version,
we currently enforce use of 'black==19.3b0' using a virtual environment.
The setup of the virtual environment and formatting of all PYthon
scripts is done automatically by the Python formatting script
'format_python.sh'. Please apply this script before submitting a merge
request containing new or updated Python scripts.
The SWIFT code comes with a series of unit tests that are run automatically
when a push to the master branch occurs. The suite can be run by doing a `make
check` in the root directory. Please check that the test suite still
runs with your changes applied before submitting a merge request and add
relevant unit tests probing the correctness of new modules. An example of how
to add a test to the suite can be found by considering the tests/testGreeting
case.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
......@@ -30,16 +30,22 @@ or:
./configure CC=icc
to use an Intel compiler. The main "programs" can be found in the "examples/"
directory.
directory. See README for run parameters.
SWIFT has been successfully built and tested with the following compilers:
- GCC 4.8.x
- GCC 4.8.x
- Intel ICC 15.0.x
- clang 3.4.x
- clang 3.4.x
- aocc 3.x
- icx (oneAPI) 2022.x
More recent versions and slightly older ones should also be able to
built the software.
build the software.
It has also been built with Intel and GNU C++ compilers, but that currently
requires the --disable-vec and, for Intel, --disable-compiler-warnings
configure options.
By default an attempt to choose suitable set of optimizing compiler flags
will be made, targeted for the host machine of the build. If this doesn't
......@@ -61,40 +67,138 @@ You could also add some additional flags:
./configure --enable-debug --disable-optimization CFLAGS="-O2"
for instance. GCC address sanitizer flags can be included using the
for instance. GCC address sanitizer flags can be included using the
./configure --enable-sanitizer
option. Note this requires a GCC compiler version of at least 4.8.
By default vectorization is switched on. The highest instruction set
available on the platform will be automatically used. However, not all
implementations of SPH available in the code have vectorized
routines. Vectorization will have to be switched off for these. It can
also be switched off for benchmarking purposes. To do so, you can use:
Dependencies
============
./configure --disable-vec
SWIFT depends on a number of third party libraries that should be available
before you can build it.
Please note that to build SWIFT on MacOS, you will need to configure
using
./configure --disable-compiler-warnings
HDF5: a HDF5 library is required to read and write particle data. One of the
commands "h5cc" or "h5pcc" should be available. If "h5pcc" is located them a
parallel HDF5 built for the version of MPI located should be provided. If
the command is not available then it can be located using the "--with-hfd5"
configure option. The value should be the full path to the "h5cc" or "h5pcc"
commands.
due to the incorrect behaviour of the LLVM compiler on this platform
that raises warnings when the pthread flags are passed to the linker.
MPI: an optional MPI library that fully supports MPI_THREAD_MULTIPLE.
Before running configure the "mpirun" command should be available in the
shell. If your command isn't called "mpirun" then define the "MPIRUN"
environment variable, either in the shell or when running configure.
Dependencies
============
METIS: a build of the METIS library can be optionally used to optimize the
load between MPI nodes (requires an MPI library). This should be found in the
standard installation directories, or pointed at using the "--with-metis"
configuration option. In this case the top-level installation directory of
the METIS build should be given. Note to use METIS you should at least supply
"--with-metis".
SWIFT depends on a number of third party libraries that should be available
before you can build it.
DOXYGEN: the doxygen library is required to create the SWIFT API documentation.
- HDF5:
A HDF5 library (v. 1.10.x or higher) is required to read and
write particle data. One of the commands "h5cc" or "h5pcc"
should be available. If "h5pcc" is located then a parallel
HDF5 built for the version of MPI located should be
provided. If the command is not available then it can be
located using the "--with-hdf5" configure option. The value
should be the full path to the "h5cc" or "h5pcc" commands.
SWIFT makes effective use of parallel HDF5 when running on more than
one node, so this option is highly recommended.
- MPI:
To run on more than one node an MPI library that fully
supports MPI_THREAD_MULTIPLE is required. Before running configure
the "mpirun" command should be available in the shell. If your
command isn't called "mpirun" then define the "MPIRUN"
environment variable, either in the shell or when running
configure.
The MPI compiler can be controlled using the MPICC variable,
much like the CC one. Use this when your MPI compiler has a
none-standard name.
- GSL:
To use cosmological time integration, a version of the GSL
must be available.
- FFTW 3.x:
To run with periodic gravity forces, a build of the FFTW 3
library must be available. Note that SWIFT does not make use
of the parallel capability of FFTW. Calculations are done by
single MPI nodes independently.
- libtool:
The build system relies on libtool as well as the other autotools.
Optional Dependencies
=====================
- METIS/ParMETIS:
a build of the METIS or ParMETIS library should be used to
optimize the load between MPI nodes. This should be found in the
standard installation directories, or pointed at using the
"--with-metis" or "--with-parmetis" configuration options.
In this case the top-level installation directory of the build
should be given. Note to use METIS or ParMETIS you should supply at
least "--with-metis". ParMETIS is preferred over METIS when there
is a choice.
- libNUMA:
a build of the NUMA library can be used to pin the threads to
the physical core of the machine SWIFT is running on. This is
not always necessary as the OS scheduler may do a good job at
distributing the threads among the different cores on each
computing node.
Note that if you have libNUMA outside of the system include
directories it may fail to compile as the headers do not pass
the -Wstrict-prototype check of GCC. In that case you will need
to use --enable-compiler-warnings=yes configure option to stop
this being an error.
- tcmalloc / jemalloc / TBBmalloc:
a build of the tcmalloc library (part of gperftools), jemalloc
or TBBmalloc can be used be used to obtain faster and more
scalable allocations than the standard C malloc function part
of glibc. Using one of these is highly recommended on systems
with many cores per node. One of the options
"--with-tcmalloc", "--with-jemalloc" or "--with-tbbmalloc"
should be passed to the configuration script to use it.
- gperftools:
a build of gperftools can be used to obtain good profiling of
the code. The option "--with-profiler" needs to be passed to
the configuration script to use it.
- DOXYGEN:
the doxygen library is required to create the SWIFT API
documentation.
- python:
Examples and solution script use python 3 and rely on the numpy
library version 1.8.2 or higher.
SWIFT Coding style
==================
The SWIFT source code uses a variation of 'Google' style. The script
'format.sh' in the root directory applies the clang-format-18 tool with our
style choices to all the SWIFT C source file. Please apply the formatting
script to the files before submitting a merge request.
The Python scripts in the repository use default formatting enforced by
'black'. Since 'black' formatting still strongly depends on the version,
we currently enforce use of 'black==19.3b0' using a virtual environment.
The setup of the virtual environment and formatting of all PYthon
scripts is done automatically by the Python formatting script
'format_python.sh'. Please apply this script before submitting a merge
request containing new or updated Python scripts.
# This file is part of SWIFT.
# Copyright (c) 2012 pedro.gonnet@durham.ac.uk.
# 2015 matthieu.schaller@durham.ac.uk.
# Copyright (c) 2012 pedro.gonnet@durham.ac.uk
# 2015 schaller@strw.leidenuniv.nl
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
......@@ -20,7 +19,87 @@
ACLOCAL_AMFLAGS = -I m4
# Show the way...
SUBDIRS = src examples doc tests
if HAVECSDS
SUBDIRS = csds
else
SUBDIRS =
endif
SUBDIRS += src argparse examples doc tests tools
if HAVEEAGLECOOLING
SUBDIRS += examples/Cooling/CoolingRates
DIST_SUBDIRS = $(SUBDIRS)
else
DIST_SUBDIRS = $(SUBDIRS) examples/Cooling/CoolingRates
endif
# Common flags
MYFLAGS =
# Add the source directory and the non-standard paths to the included library headers to CFLAGS
AM_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/argparse $(HDF5_CPPFLAGS) \
$(GSL_INCS) $(FFTW_INCS) $(NUMA_INCS) $(GRACKLE_INCS) \
$(CHEALPIX_CFLAGS) $(LUSTREAPI_CFLAGS)
AM_LDFLAGS = $(HDF5_LDFLAGS)
# Extra libraries.
EXTRA_LIBS = $(GSL_LIBS) $(HDF5_LIBS) $(FFTW_LIBS) $(NUMA_LIBS) $(PROFILER_LIBS) \
$(TCMALLOC_LIBS) $(JEMALLOC_LIBS) $(TBBMALLOC_LIBS) $(GRACKLE_LIBS) \
$(CHEALPIX_LIBS) $(LUSTREAPI_LIBS)
# MPI libraries.
MPI_LIBS = $(PARMETIS_LIBS) $(METIS_LIBS) $(MPI_THREAD_LIBS) $(FFTW_MPI_LIBS)
MPI_FLAGS = -DWITH_MPI $(PARMETIS_INCS) $(METIS_INCS) $(FFTW_MPI_INCS)
# Programs.
bin_PROGRAMS = swift
# Also build the FOF tool?
if HAVESTANDALONEFOF
bin_PROGRAMS += fof
endif
# Do we have the CSDS?
if HAVECSDS
LD_CSDS = csds/src/.libs/libcsds_writer.a
else
LD_CSDS =
endif
# Build MPI versions as well?
if HAVEMPI
bin_PROGRAMS += swift_mpi
if HAVESTANDALONEFOF
bin_PROGRAMS += fof_mpi
endif
endif
# engine_policy_setaffinity is available?
if HAVESETAFFINITY
ENGINE_POLICY_SETAFFINITY=| engine_policy_setaffinity
else
ENGINE_POLICY_SETAFFINITY=
endif
# Sources for swift
swift_SOURCES = swift.c
swift_CFLAGS = $(MYFLAGS) $(AM_CFLAGS) -DENGINE_POLICY="engine_policy_keep $(ENGINE_POLICY_SETAFFINITY)"
swift_LDADD = src/libswiftsim.la argparse/libargparse.la $(VELOCIRAPTOR_LIBS) $(EXTRA_LIBS) $(LD_CSDS)
# Sources for swift_mpi, do we need an affinity policy for MPI?
swift_mpi_SOURCES = swift.c
swift_mpi_CFLAGS = $(MYFLAGS) $(AM_CFLAGS) $(MPI_FLAGS) -DENGINE_POLICY="engine_policy_keep $(ENGINE_POLICY_SETAFFINITY)"
swift_mpi_LDADD = src/libswiftsim_mpi.la argparse/libargparse.la $(MPI_LIBS) $(VELOCIRAPTOR_MPI_LIBS) $(EXTRA_LIBS) $(LD_CSDS)
# Sources for fof
fof_SOURCES = swift_fof.c
fof_CFLAGS = $(MYFLAGS) $(AM_CFLAGS) -DENGINE_POLICY="engine_policy_keep $(ENGINE_POLICY_SETAFFINITY)"
fof_LDADD = src/.libs/libswiftsim.a argparse/.libs/libargparse.a $(VELOCIRAPTOR_LIBS) $(EXTRA_LIBS) $(LD_CSDS)
# Sources for fof_mpi, do we need an affinity policy for MPI?
fof_mpi_SOURCES = swift_fof.c
fof_mpi_CFLAGS = $(MYFLAGS) $(AM_CFLAGS) $(MPI_FLAGS) -DENGINE_POLICY="engine_policy_keep $(ENGINE_POLICY_SETAFFINITY)"
fof_mpi_LDADD = src/.libs/libswiftsim_mpi.a argparse/.libs/libargparse.a $(MPI_LIBS) $(VELOCIRAPTOR_MPI_LIBS) $(EXTRA_LIBS) $(LD_CSDS)
# Non-standard files that should be part of the distribution.
EXTRA_DIST = INSTALL.swift
EXTRA_DIST = INSTALL.swift .clang-format format.sh
Welcome to the cosmological code
Welcome to the cosmological hydrodynamical code
______ _________________
/ ___/ | / / _/ ___/_ __/
\__ \| | /| / // // /_ / /
___/ /| |/ |/ // // __/ / /
/____/ |__/|__/___/_/ /_/
\__ \| | /| / // // /_ / /
___/ /| |/ |/ // // __/ / /
/____/ |__/|__/___/_/ /_/
SPH With Inter-dependent Fine-grained Tasking
Website: www.swiftsim.com
Twitter: @SwiftSimulation
Version : 2025.04
Website: www.swiftsim.com
Twitter: @SwiftSimulation
See INSTALL.swift for instructions.
See INSTALL.swift for install instructions.
Usage: swift [options] [[--] param-file]
or: swift [options] param-file
or: swift_mpi [options] [[--] param-file]
or: swift_mpi [options] param-file
Parameters:
-h, --help show this help message and exit
Simulation options:
-b, --feedback Run with stars feedback.
-c, --cosmology Run with cosmological time integration.
--temperature Run with temperature calculation.
-C, --cooling Run with cooling (also switches on --temperature).
-D, --drift-all Always drift all particles even the ones
far from active particles. This emulates
Gadget-[23] and GIZMO's default behaviours.
-F, --star-formation Run with star formation.
-g, --external-gravity Run with an external gravitational potential.
-G, --self-gravity Run with self-gravity.
-M, --multipole-reconstruction Reconstruct the multipoles every time-step.
-s, --hydro Run with hydrodynamics.
-S, --stars Run with stars.
-B, --black-holes Run with black holes.
-k, --sinks Run with sink particles.
-u, --fof Run Friends-of-Friends algorithm to
perform black hole seeding.
--lightcone Generate lightcone outputs.
-x, --velociraptor Run with structure finding.
--line-of-sight Run with line-of-sight outputs.
--limiter Run with time-step limiter.
--sync Run with time-step synchronization
of particles hit by feedback events.
--csds Run with the Continuous Simulation Data
Stream (CSDS).
-R, --radiation Run with radiative transfer.
--power Run with power spectrum outputs.
Simulation meta-options:
--quick-lyman-alpha Run with all the options needed for the
quick Lyman-alpha model. This is equivalent
to --hydro --self-gravity --stars --star-formation
--cooling.
--eagle Run with all the options needed for the
EAGLE model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback
--black-holes --fof.
--gear Run with all the options needed for the
GEAR model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback.
--agora Run with all the options needed for the
AGORA model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback.
Control options:
-a, --pin Pin runners using processor affinity.
--nointerleave Do not interleave memory allocations across
NUMA regions.
-d, --dry-run Dry run. Read the parameter file, allocates
memory but does not read the particles
from ICs. Exits before the start of time
integration. Checks the validity of
parameters and IC files as well as memory
limits.
-e, --fpe Enable floating-point exceptions (debugging
mode).
-f, --cpu-frequency=<str> Overwrite the CPU frequency (Hz) to be
used for time measurements.
-n, --steps=<int> Execute a fixed number of time steps.
When unset use the time_end parameter
to stop.
-o, --output-params=<str> Generate a parameter file with the options
for selecting the output fields.
-P, --param=<str> Set parameter value, overiding the value
read from the parameter file. Can be used
more than once {sec:par:value}.
-r, --restart Continue using restart files.
-t, --threads=<int> The number of task threads to use on each
MPI rank. Defaults to 1 if not specified.
--pool-threads=<int> The number of threads to use on each MPI
rank for the threadpool operations.
Defaults to the numbers of task threads
if not specified.
-T, --timers=<int> Print timers every time-step.
-v, --verbose=<int> Run in verbose mode, in MPI mode 2 outputs
from all ranks.
-y, --task-dumps=<int> Time-step frequency at which task graphs
are dumped.
--cell-dumps=<int> Time-step frequency at which cell graphs
are dumped.
-Y, --threadpool-dumps=<int> Time-step frequency at which threadpool
tasks are dumped.
--dump-tasks-threshold=<flt> Fraction of the total step's time spent
in a task to trigger a dump of the task plot
on this step
See the file examples/parameter_example.yml for an example of parameter file.
Various hints on settings needed to get various MPIs running with SWIFT.
Last update 5th May 2020.
## Intel MPI
_Intel MPI 2018_ usually runs without any needs for special settings.
_Intel MPI 2019 and 2020_ can run for small tests, but without flags will
generally deadlock in the MPI exchanges of the engine, or worse. In that case
try the following settings.
```
FI_OFI_RXM_RX_SIZE=4096
FI_OFI_RXM_TX_SIZE=4096
FI_UNIVERSE_SIZE=2048
```
If you want use the `release_mt` library, then you also need to use:
```
source $I_MPI_ROOT/intel64/bin/mpivars.sh release_mt
```
when initializing the library environment. Some success has also been seen
using the asynchronous progression settings:
```
I_MPI_ASYNC_PROGRESS=1
I_MPI_ASYNC_PROGRESS_THREADS=1
```
(note these are tested with `2019 update-4` and `2020 update-1` on Mellanox).
## OpenMPI
_Open MPI_ comes in many flavours with many combinations of underlying
transport libraries and running on many different fabrics. A complete
description of all combinations is beyond the scope of this guide.
On Mellanox hardware, we have had success running version 4.0 with the
UCX layer version 1.6 and using the following settings:
```
-mca coll_hcoll_enable 0
UCX_TLS=ud_x,shm,self
UCX_RC_MLX5_TM_ENABLE=n
UCX_DC_MLX5_TM_ENABLE=n
```
These environment variables (set on the Mellanox-base cosma system in Durham)
for version 4.0.5 with the UCX backend can also be useful:
```
OMPI_MCA_btl ^openib
OMPI_MCA_btl_openib_flags 1
OMPI_MCA_plm_rsh_num_concurrent 768
OMPI_MCA_mpool_rdma_rcache_size_limit 209715200
```
\ No newline at end of file
<a name="logo"/>
<div align="center">
<a href="https://www.swiftsim.com/" target="_blank">
<img src="https://swift.strw.leidenuniv.nl/SWIFT_banner.jpg" alt="SWIFT banner" width="1016" height="242"></img>
</a>
</div>
SWIFT: SPH WIth Fine-grained inter-dependent Tasking
====================================================
[![Build Status](https://gitlab.cosma.dur.ac.uk/jenkins/job/GNU%20SWIFT%20build/badge/icon)](https://gitlab.cosma.dur.ac.uk/jenkins/job/GNU%20SWIFT%20build/)
SWIFT is a gravity and SPH solver designed to run cosmological simulations
on peta-scale machines, scaling well up to 10's of thousands of compute
node.
More general information about SWIFT is available on the project
[webpages](http://www.swiftsim.com).
For information on how to _run_ SWIFT, please consult the onboarding guide
available [here](https://swift.strw.leidenuniv.nl/onboarding.pdf). This includes
dependencies, and a few examples to get you going.
We suggest that you use the latest release branch of SWIFT, rather than the
current master branch as this will change rapidly. We do, however, like to
ensure that the master branch will build and run.
This GitHub repository is designed to be an issue tracker, and a space for
the public to submit patches through pull requests. It is synchronised with
the main development repository that is available on the
[ICC](http://icc.dur.ac.uk)'s GitLab server which is available
[here](https://gitlab.cosma.dur.ac.uk/swift/swiftsim).
Please feel free to submit issues to this repository, or even pull
requests. We will try to deal with them as soon as possible, but as the
core development team is quite small this could take some time.
Disclaimer
----------
We would like to emphasise that SWIFT comes without any warranty of accuracy,
correctness or efficiency. As mentioned in the license, the software comes
`as-is` and the onus is on the user to get meaningful results. Whilst the
authors will endeavour to answer questions related to using the code, we
recommend users build and maintain their own copies. This documentation contains
the most basic information to get started. Reading it and possibly also the
source code is the best way to start running simulations.
The users are responsible to understand what the code is doing and for the
results of their simulation runs.
Note also that the values of the parameters given in the examples are only
indicative. We recommend users experiment by themselves and a campaign of
experimentation with various values is highly encouraged. Each problem will
likely require different values and the sensitivity to the details of the
physical model is something left to the users to explore.
Acknowledgement & Citation
-------------------------
The SWIFT code was last described in this paper:
https://ui.adsabs.harvard.edu/abs/2023arXiv230513380S. The core solver, the
numerical methods as well as many extensions where described there. We ask users
running SWIFT for their research to please cite this paper when they present
their results.
In order to keep track of usage and measure the impact of the software, we
kindly ask users publishing scientific results using SWIFT to add the following
sentence to the acknowledgement section of their papers:
"The research in this paper made use of the SWIFT open-source
simulation code (http://www.swiftsim.com, Schaller et al. 2018)
version X.Y.Z."
with the version number set to the version used for the simulations and the
reference pointing to the ASCL entry of the code: https://ascl.net/1805.020.
Contribution Guidelines
-----------------------
The SWIFT source code uses a variation of the 'Google' formatting style.
The script 'format.sh' in the root directory applies the clang-format-18
tool with our style choices to all the SWIFT C source file. Please apply
the formatting script to the files before submitting a pull request.
Please check that the test suite still runs with your changes applied before
submitting a pull request and add relevant unit tests probing the correctness
of new modules. An example of how to add a test to the suite can be found by
considering the tests/testGreeting case.
Any contributions that fail any of the automated tests will not be accepted.
Contributions that include tests of the proposed modules (or any current ones!)
are highly encouraged.
Runtime parameters
------------------
```
Welcome to the cosmological hydrodynamical code
______ _________________
/ ___/ | / / _/ ___/_ __/
\__ \| | /| / // // /_ / /
___/ /| |/ |/ // // __/ / /
/____/ |__/|__/___/_/ /_/
SPH With Inter-dependent Fine-grained Tasking
Version : 2025.04
Website: www.swiftsim.com
Twitter: @SwiftSimulation
See INSTALL.swift for install instructions.
Usage: swift [options] [[--] param-file]
or: swift [options] param-file
or: swift_mpi [options] [[--] param-file]
or: swift_mpi [options] param-file
Parameters:
-h, --help show this help message and exit
Simulation options:
-b, --feedback Run with stars feedback.
-c, --cosmology Run with cosmological time integration.
--temperature Run with temperature calculation.
-C, --cooling Run with cooling (also switches on --temperature).
-D, --drift-all Always drift all particles even the ones
far from active particles. This emulates
Gadget-[23] and GIZMO's default behaviours.
-F, --star-formation Run with star formation.
-g, --external-gravity Run with an external gravitational potential.
-G, --self-gravity Run with self-gravity.
-M, --multipole-reconstruction Reconstruct the multipoles every time-step.
-s, --hydro Run with hydrodynamics.
-S, --stars Run with stars.
-B, --black-holes Run with black holes.
-k, --sinks Run with sink particles.
-u, --fof Run Friends-of-Friends algorithm to
perform black hole seeding.
--lightcone Generate lightcone outputs.
-x, --velociraptor Run with structure finding.
--line-of-sight Run with line-of-sight outputs.
--limiter Run with time-step limiter.
--sync Run with time-step synchronization
of particles hit by feedback events.
--csds Run with the Continuous Simulation Data
Stream (CSDS).
-R, --radiation Run with radiative transfer.
--power Run with power spectrum outputs.
Simulation meta-options:
--quick-lyman-alpha Run with all the options needed for the
quick Lyman-alpha model. This is equivalent
to --hydro --self-gravity --stars --star-formation
--cooling.
--eagle Run with all the options needed for the
EAGLE model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback
--black-holes --fof.
--gear Run with all the options needed for the
GEAR model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback.
--agora Run with all the options needed for the
GEAR model. This is equivalent to --hydro
--limiter --sync --self-gravity --stars
--star-formation --cooling --feedback.
Control options:
-a, --pin Pin runners using processor affinity.
--nointerleave Do not interleave memory allocations across
NUMA regions.
-d, --dry-run Dry run. Read the parameter file, allocates
memory but does not read the particles
from ICs. Exits before the start of time
integration. Checks the validity of
parameters and IC files as well as memory
limits.
-e, --fpe Enable floating-point exceptions (debugging
mode).
-f, --cpu-frequency=<str> Overwrite the CPU frequency (Hz) to be
used for time measurements.
-n, --steps=<int> Execute a fixed number of time steps.
When unset use the time_end parameter
to stop.
-o, --output-params=<str> Generate a parameter file with the options
for selecting the output fields.
-P, --param=<str> Set parameter value, overiding the value
read from the parameter file. Can be used
more than once {sec:par:value}.
-r, --restart Continue using restart files.
-t, --threads=<int> The number of task threads to use on each
MPI rank. Defaults to 1 if not specified.
--pool-threads=<int> The number of threads to use on each MPI
rank for the threadpool operations.
Defaults to the numbers of task threads
if not specified.
-T, --timers=<int> Print timers every time-step.
-v, --verbose=<int> Run in verbose mode, in MPI mode 2 outputs
from all ranks.
-y, --task-dumps=<int> Time-step frequency at which task graphs
are dumped.
--cell-dumps=<int> Time-step frequency at which cell graphs
are dumped.
-Y, --threadpool-dumps=<int> Time-step frequency at which threadpool
tasks are dumped.
--dump-tasks-threshold=<flt> Fraction of the total step's time spent
in a task to trigger a dump of the task plot
on this step
See the file examples/parameter_example.yml for an example of parameter file.
```
# FAQs
## Why removing parsed command-line switches/options?
It destroys the original `argv` array, not compatible with other arguments parsing
library.
This is because this library is used for short-lived programs, e.g. cli tools
at beginning. It's very convenient to process remain arguments if we remove
parsed command-line arguments, e.g. `<comamnd> [-[s]|--switch]... arguments`.
If you want keep original `argc/argv`, you can make a copy, then pass them to
`argparse_parse`, e.g.
```c
int copy_argc = argc;
const char **copy_argv = argv;
copy_argv = malloc(copy_argc * sizeof(char *));
for (int i = 0; i < argc; i++) {
copy_argv[i] = (char *)argv[i];
}
argparse_parse(&argparse, copy_argc, copy_argv);
```
Issues:
- https://github.com/cofyc/argparse/issues/3
- https://github.com/cofyc/argparse/issues/9
## Why using `intptr_t` to hold associated data? Why not `void *`?
I choose `intptr_t` because it's a integer type which also can be used to hold
a pointer value. Most of the time, we only need a integer to hold
user-provided value, see `OPT_BIT` as example. If you want to provide a pointer
which points to a large amount of data, you can cast it to `intptr_t` and cast
it back to original pointer in callback function.
The MIT License (MIT)
Copyright (c) 2012-2013 Yecheng Fu <cofyc.jackson@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# This file is part of SWIFT.
# Copyright (c) 2018 Peter W. Draper (p.w.draper@durham.ac.uk)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
lib_LTLIBRARIES = libargparse.la
include_HEADERS = argparse.h
AM_SOURCES = argparse.c
# Sources and flags for regular library
libargparse_la_SOURCES = $(AM_SOURCES)
libargparse_la_CFLAGS = $(AM_CFLAGS)
libargparse_la_LDFLAGS = $(AM_LDFLAGS)
EXTRA_DIST = LICENSE README.md
approvers:
- cofyc
# argparse [![Build Status](https://travis-ci.org/cofyc/argparse.png)](https://travis-ci.org/cofyc/argparse)
argparse - A command line arguments parsing library in C (compatible with C++).
## Description
This module is inspired by parse-options.c (git) and python's argparse
module.
Arguments parsing is common task in cli program, but traditional `getopt`
libraries are not easy to use. This library provides high-level arguments
parsing solutions.
The program defines what arguments it requires, and `argparse` will figure
out how to parse those out of `argc` and `argv`, it also automatically
generates help and usage messages and issues errors when users give the
program invalid arguments.
## Features
- handles both optional and positional arguments
- produces highly informative usage messages
- issues errors when given invalid arguments
There are basically three types of options:
- boolean options
- options with mandatory argument
- options with optional argument
There are basically two forms of options:
- short option consist of one dash (`-`) and one alphanumeric character.
- long option begin with two dashes (`--`) and some alphanumeric characters.
Short options may be bundled, e.g. `-a -b` can be specified as `-ab`.
Options are case-sensitive.
Options and non-option arguments can clearly be separated using the `--` option.
## Examples
```c
#include "argparse.h"
static const char *const usage[] = {
"test_argparse [options] [[--] args]",
"test_argparse [options]",
NULL,
};
#define PERM_READ (1<<0)
#define PERM_WRITE (1<<1)
#define PERM_EXEC (1<<2)
int
main(int argc, const char **argv)
{
int force = 0;
int test = 0;
int num = 0;
const char *path = NULL;
int perms = 0;
struct argparse_option options[] = {
OPT_HELP(),
OPT_GROUP("Basic options"),
OPT_BOOLEAN('f', "force", &force, "force to do"),
OPT_BOOLEAN('t', "test", &test, "test only"),
OPT_STRING('p', "path", &path, "path to read"),
OPT_INTEGER('n', "num", &num, "selected num"),
OPT_GROUP("Bits options"),
OPT_BIT(0, "read", &perms, "read perm", NULL, PERM_READ, OPT_NONEG),
OPT_BIT(0, "write", &perms, "write perm", NULL, PERM_WRITE),
OPT_BIT(0, "exec", &perms, "exec perm", NULL, PERM_EXEC),
OPT_END(),
};
struct argparse argparse;
argparse_init(&argparse, options, usage, 0);
argparse_describe(&argparse, "\nA brief description of what the program does and how it works.", "\nAdditional description of the program after the description of the arguments.");
argc = argparse_parse(&argparse, argc, argv);
if (force != 0)
printf("force: %d\n", force);
if (test != 0)
printf("test: %d\n", test);
if (path != NULL)
printf("path: %s\n", path);
if (num != 0)
printf("num: %d\n", num);
if (argc != 0) {
printf("argc: %d\n", argc);
int i;
for (i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *(argv + i));
}
}
if (perms) {
printf("perms: %d\n", perms);
}
return 0;
}
```
/**
* Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
* All rights reserved.
*
* Use of this source code is governed by a MIT-style license that can be found
* in the LICENSE file.
*/
#include "argparse.h"
#include <config.h>
/* System includes */
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OPT_UNSET 1
#define OPT_LONG (1 << 1)
static const char *prefix_skip(const char *str, const char *prefix) {
size_t len = strlen(prefix);
return strncmp(str, prefix, len) ? NULL : str + len;
}
static int prefix_cmp(const char *str, const char *prefix) {
for (;; str++, prefix++)
if (!*prefix) {
return 0;
} else if (*str != *prefix) {
return (unsigned char)*prefix - (unsigned char)*str;
}
}
static void argparse_error(struct argparse *self,
const struct argparse_option *opt,
const char *reason, int flags) {
(void)self;
if (flags & OPT_LONG) {
fprintf(stderr, "error: option `--%s` %s\n", opt->long_name, reason);
} else {
fprintf(stderr, "error: option `-%c` %s\n", opt->short_name, reason);
}
exit(1);
}
static int argparse_getvalue(struct argparse *self,
const struct argparse_option *opt, int flags) {
const char *s = NULL;
if (!opt->value) goto skipped;
switch (opt->type) {
case ARGPARSE_OPT_BOOLEAN:
if (flags & OPT_UNSET) {
*(int *)opt->value = *(int *)opt->value - 1;
} else {
*(int *)opt->value = *(int *)opt->value + 1;
}
if (*(int *)opt->value < 0) {
*(int *)opt->value = 0;
}
break;
case ARGPARSE_OPT_BIT:
if (flags & OPT_UNSET) {
*(int *)opt->value &= ~opt->data;
} else {
*(int *)opt->value |= opt->data;
}
break;
case ARGPARSE_OPT_STRING:
if (self->optvalue) {
*(const char **)opt->value = self->optvalue;
self->optvalue = NULL;
} else if (self->argc > 1) {
self->argc--;
*(const char **)opt->value = *++self->argv;
} else {
argparse_error(self, opt, "requires a value", flags);
}
break;
case ARGPARSE_OPT_INTEGER:
errno = 0;
if (self->optvalue) {
*(int *)opt->value = strtol(self->optvalue, (char **)&s, 0);
self->optvalue = NULL;
} else if (self->argc > 1) {
self->argc--;
*(int *)opt->value = strtol(*++self->argv, (char **)&s, 0);
} else {
argparse_error(self, opt, "requires a value", flags);
}
if (errno) argparse_error(self, opt, strerror(errno), flags);
if (s[0] != '\0')
argparse_error(self, opt, "expects an integer value", flags);
break;
case ARGPARSE_OPT_FLOAT:
errno = 0;
if (self->optvalue) {
*(float *)opt->value = strtof(self->optvalue, (char **)&s);
self->optvalue = NULL;
} else if (self->argc > 1) {
self->argc--;
*(float *)opt->value = strtof(*++self->argv, (char **)&s);
} else {
argparse_error(self, opt, "requires a value", flags);
}
if (errno) argparse_error(self, opt, strerror(errno), flags);
if (s[0] != '\0')
argparse_error(self, opt, "expects a numerical value", flags);
break;
default:
assert(0);
}
skipped:
if (opt->callback) {
return opt->callback(self, opt);
}
return 0;
}
static void argparse_options_check(const struct argparse_option *options) {
for (; options->type != ARGPARSE_OPT_END; options++) {
switch (options->type) {
case ARGPARSE_OPT_END:
case ARGPARSE_OPT_BOOLEAN:
case ARGPARSE_OPT_BIT:
case ARGPARSE_OPT_INTEGER:
case ARGPARSE_OPT_FLOAT:
case ARGPARSE_OPT_STRING:
case ARGPARSE_OPT_GROUP:
continue;
default:
fprintf(stderr, "wrong option type: %d", options->type);
break;
}
}
}
static int argparse_short_opt(struct argparse *self,
const struct argparse_option *options) {
for (; options->type != ARGPARSE_OPT_END; options++) {
if (options->short_name == *self->optvalue) {
self->optvalue = self->optvalue[1] ? self->optvalue + 1 : NULL;
return argparse_getvalue(self, options, 0);
}
}
return -2;
}
static int argparse_long_opt(struct argparse *self,
const struct argparse_option *options) {
for (; options->type != ARGPARSE_OPT_END; options++) {
const char *rest;
int opt_flags = 0;
if (!options->long_name) continue;
rest = prefix_skip(self->argv[0] + 2, options->long_name);
if (!rest) {
// negation disabled?
if (options->flags & OPT_NONEG) {
continue;
}
// only OPT_BOOLEAN/OPT_BIT supports negation
if (options->type != ARGPARSE_OPT_BOOLEAN &&
options->type != ARGPARSE_OPT_BIT) {
continue;
}
if (prefix_cmp(self->argv[0] + 2, "no-")) {
continue;
}
rest = prefix_skip(self->argv[0] + 2 + 3, options->long_name);
if (!rest) continue;
opt_flags |= OPT_UNSET;
}
if (*rest) {
if (*rest != '=') continue;
self->optvalue = rest + 1;
}
return argparse_getvalue(self, options, opt_flags | OPT_LONG);
}
return -2;
}
int argparse_init(struct argparse *self, struct argparse_option *options,
const char *const *usages, int flags) {
memset(self, 0, sizeof(*self));
self->options = options;
self->usages = usages;
self->flags = flags;
self->description = NULL;
self->epilog = NULL;
return 0;
}
void argparse_describe(struct argparse *self, const char *description,
const char *epilog) {
self->description = description;
self->epilog = epilog;
}
int argparse_parse(struct argparse *self, int argc, const char **argv) {
self->argc = argc - 1;
self->argv = argv + 1;
self->out = argv;
argparse_options_check(self->options);
for (; self->argc; self->argc--, self->argv++) {
const char *arg = self->argv[0];
if (arg[0] != '-' || !arg[1]) {
if (self->flags & ARGPARSE_STOP_AT_NON_OPTION) {
goto end;
}
// if it's not option or is a single char '-', copy verbatim
self->out[self->cpidx++] = self->argv[0];
continue;
}
// short option
if (arg[1] != '-') {
self->optvalue = arg + 1;
switch (argparse_short_opt(self, self->options)) {
case -1:
break;
case -2:
goto unknown;
}
while (self->optvalue) {
switch (argparse_short_opt(self, self->options)) {
case -1:
break;
case -2:
goto unknown;
}
}
continue;
}
// if '--' presents
if (!arg[2]) {
self->argc--;
self->argv++;
break;
}
// long option
switch (argparse_long_opt(self, self->options)) {
case -1:
break;
case -2:
goto unknown;
}
continue;
unknown:
fprintf(stderr, "error: unknown option `%s`\n", self->argv[0]);
argparse_usage(self);
exit(1);
}
end:
memmove(self->out + self->cpidx, self->argv, self->argc * sizeof(*self->out));
self->out[self->cpidx + self->argc] = NULL;
return self->cpidx + self->argc;
}
void argparse_usage(struct argparse *self) {
if (self->usages) {
fprintf(stdout, "Usage: %s\n", *self->usages++);
while (*self->usages && **self->usages)
fprintf(stdout, " or: %s\n", *self->usages++);
} else {
fprintf(stdout, "Usage:\n");
}
// print description
if (self->description) fprintf(stdout, "%s\n", self->description);
fputc('\n', stdout);
const struct argparse_option *options;
// figure out best width
size_t usage_opts_width = 0;
size_t len;
options = self->options;
for (; options->type != ARGPARSE_OPT_END; options++) {
len = 0;
if ((options)->short_name) {
len += 2;
}
if ((options)->short_name && (options)->long_name) {
len += 2; // separator ", "
}
if ((options)->long_name) {
len += strlen((options)->long_name) + 2;
}
if (options->type == ARGPARSE_OPT_INTEGER) {
len += strlen("=<int>");
}
if (options->type == ARGPARSE_OPT_FLOAT) {
len += strlen("=<flt>");
} else if (options->type == ARGPARSE_OPT_STRING) {
len += strlen("=<str>");
}
len = (len + 3) - ((len + 3) & 3);
if (usage_opts_width < len) {
usage_opts_width = len;
}
}
usage_opts_width += 4; // 4 spaces prefix
options = self->options;
for (; options->type != ARGPARSE_OPT_END; options++) {
size_t pos = 0;
int pad = 0;
if (options->type == ARGPARSE_OPT_GROUP) {
fputc('\n', stdout);
fprintf(stdout, "%s", options->help);
fputc('\n', stdout);
continue;
}
pos = fprintf(stdout, " ");
if (options->short_name) {
pos += fprintf(stdout, "-%c", options->short_name);
}
if (options->long_name && options->short_name) {
pos += fprintf(stdout, ", ");
}
if (options->long_name) {
pos += fprintf(stdout, "--%s", options->long_name);
}
if (options->type == ARGPARSE_OPT_INTEGER) {
pos += fprintf(stdout, "=<int>");
}
if (options->type == ARGPARSE_OPT_FLOAT) {
pos += fprintf(stdout, "=<flt>");
} else if (options->type == ARGPARSE_OPT_STRING) {
pos += fprintf(stdout, "=<str>");
}
if (pos <= usage_opts_width) {
pad = usage_opts_width - pos;
} else {
fputc('\n', stdout);
pad = usage_opts_width;
}
if (options->help != NULL && strlen(options->help) > 0) {
char *str = strdup(options->help);
char *token = strtok(str, " ");
fprintf(stdout, "%*s%s ", pad + 2, "", token);
int count = strlen(token);
int dangling = 1;
while ((token = strtok(NULL, " ")) != NULL) {
if (count == 0) {
fprintf(stdout, "%*s", (int)pos + pad + 2, "");
dangling = 1;
}
printf("%s ", token);
count += strlen(token);
if (count > 30) {
count = 0;
fprintf(stdout, "\n");
dangling = 0;
}
}
if (dangling) fprintf(stdout, "\n");
free(str);
} else {
fprintf(stdout, "\n");
}
}
// print epilog
if (self->epilog) fprintf(stdout, "%s\n", self->epilog);
}
int argparse_help_cb(struct argparse *self,
const struct argparse_option *option) {
(void)option;
argparse_usage(self);
exit(0);
}
/**
* Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
* All rights reserved.
*
* Use of this source code is governed by a MIT-style license that can be found
* in the LICENSE file.
*/
#ifndef ARGPARSE_H
#define ARGPARSE_H
/* For c++ compatibility */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
struct argparse;
struct argparse_option;
typedef int argparse_callback(struct argparse *self,
const struct argparse_option *option);
enum argparse_flag {
ARGPARSE_STOP_AT_NON_OPTION = 1,
};
enum argparse_option_type {
/* special */
ARGPARSE_OPT_END,
ARGPARSE_OPT_GROUP,
/* options with no arguments */
ARGPARSE_OPT_BOOLEAN,
ARGPARSE_OPT_BIT,
/* options with arguments (optional or required) */
ARGPARSE_OPT_INTEGER,
ARGPARSE_OPT_FLOAT,
ARGPARSE_OPT_STRING,
};
enum argparse_option_flags {
OPT_NONEG = 1, /* disable negation */
};
/**
* argparse option
*
* `type`:
* holds the type of the option, you must have an ARGPARSE_OPT_END last in
* your array.
*
* `short_name`:
* the character to use as a short option name, '\0' if none.
*
* `long_name`:
* the long option name, without the leading dash, NULL if none.
*
* `value`:
* stores pointer to the value to be filled.
*
* `help`:
* the short help message associated to what the option does.
* Must never be NULL (except for ARGPARSE_OPT_END).
*
* `callback`:
* function is called when corresponding argument is parsed.
*
* `data`:
* associated data. Callbacks can use it like they want.
*
* `flags`:
* option flags.
*/
struct argparse_option {
enum argparse_option_type type;
const char short_name;
const char *long_name;
void *value;
const char *help;
argparse_callback *callback;
intptr_t data;
int flags;
};
/**
* argpparse
*/
struct argparse {
// user supplied
const struct argparse_option *options;
const char *const *usages;
int flags;
const char *description; // a description after usage
const char *epilog; // a description at the end
// internal context
int argc;
const char **argv;
const char **out;
int cpidx;
const char *optvalue; // current option value
};
// built-in callbacks
int argparse_help_cb(struct argparse *self,
const struct argparse_option *option);
// built-in option macros
#define OPT_END() {ARGPARSE_OPT_END, 0, NULL, NULL, 0, NULL, 0, 0}
#define OPT_BOOLEAN(...) {ARGPARSE_OPT_BOOLEAN, __VA_ARGS__}
#define OPT_BIT(...) {ARGPARSE_OPT_BIT, __VA_ARGS__}
#define OPT_INTEGER(...) {ARGPARSE_OPT_INTEGER, __VA_ARGS__}
#define OPT_FLOAT(...) {ARGPARSE_OPT_FLOAT, __VA_ARGS__}
#define OPT_STRING(...) {ARGPARSE_OPT_STRING, __VA_ARGS__}
#define OPT_GROUP(h) {ARGPARSE_OPT_GROUP, 0, NULL, NULL, h, NULL, 0, 0}
#define OPT_HELP() \
OPT_BOOLEAN('h', "help", NULL, "show this help message and exit", \
argparse_help_cb, 0, 0)
int argparse_init(struct argparse *self, struct argparse_option *options,
const char *const *usages, int flags);
void argparse_describe(struct argparse *self, const char *description,
const char *epilog);
int argparse_parse(struct argparse *self, int argc, const char **argv);
void argparse_usage(struct argparse *self);
#ifdef __cplusplus
}
#endif
#endif
#!/bin/bash
_version='1.02'
_plan_set=0
_no_plan=0
_skip_all=0
_test_died=0
_expected_tests=0
_executed_tests=0
_failed_tests=0
TODO=
usage(){
cat <<'USAGE'
tap-functions: A TAP-producing BASH library
PLAN:
plan_no_plan
plan_skip_all [REASON]
plan_tests NB_TESTS
TEST:
ok RESULT [NAME]
okx COMMAND
is RESULT EXPECTED [NAME]
isnt RESULT EXPECTED [NAME]
like RESULT PATTERN [NAME]
unlike RESULT PATTERN [NAME]
pass [NAME]
fail [NAME]
SKIP:
skip [CONDITION] [REASON] [NB_TESTS=1]
skip $feature_not_present "feature not present" 2 || {
is $a "a"
is $b "b"
}
TODO:
Specify TODO mode by setting $TODO:
TODO="not implemented yet"
ok $result "some not implemented test"
unset TODO
OTHER:
diag MSG
EXAMPLE:
#!/bin/bash
. tap-functions
plan_tests 7
me=$USER
is $USER $me "I am myself"
like $HOME $me "My home is mine"
like "`id`" $me "My id matches myself"
/bin/ls $HOME 1>&2
ok $? "/bin/ls $HOME"
# Same thing using okx shortcut
okx /bin/ls $HOME
[[ "`id -u`" != "0" ]]
i_am_not_root=$?
skip $i_am_not_root "Must be root" || {
okx ls /root
}
TODO="figure out how to become root..."
okx [ "$HOME" == "/root" ]
unset TODO
USAGE
exit
}
opt=
set_u=
while getopts ":sx" opt ; do
case $_opt in
u) set_u=1 ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
# Don't allow uninitialized variables if requested
[[ -n "$set_u" ]] && set -u
unset opt set_u
# Used to call _cleanup on shell exit
trap _exit EXIT
plan_no_plan(){
(( _plan_set != 0 )) && "You tried to plan twice!"
_plan_set=1
_no_plan=1
return 0
}
plan_skip_all(){
local reason=${1:-''}
(( _plan_set != 0 )) && _die "You tried to plan twice!"
_print_plan 0 "Skip $reason"
_skip_all=1
_plan_set=1
_exit 0
return 0
}
plan_tests(){
local tests=${1:?}
(( _plan_set != 0 )) && _die "You tried to plan twice!"
(( tests == 0 )) && _die "You said to run 0 tests! You've got to run something."
_print_plan $tests
_expected_tests=$tests
_plan_set=1
return $tests
}
_print_plan(){
local tests=${1:?}
local directive=${2:-''}
echo -n "1..$tests"
[[ -n "$directive" ]] && echo -n " # $directive"
echo
}
pass(){
local name=$1
ok 0 "$name"
}
fail(){
local name=$1
ok 1 "$name"
}
# This is the workhorse method that actually
# prints the tests result.
ok(){
local result=${1:?}
local name=${2:-''}
(( _plan_set == 0 )) && _die "You tried to run a test without a plan! Gotta have a plan."
_executed_tests=$(( $_executed_tests + 1 ))
if [[ -n "$name" ]] ; then
if _matches "$name" "^[0-9]+$" ; then
diag " You named your test '$name'. You shouldn't use numbers for your test names."
diag " Very confusing."
fi
fi
if (( result != 0 )) ; then
echo -n "not "
_failed_tests=$(( _failed_tests + 1 ))
fi
echo -n "ok $_executed_tests"
if [[ -n "$name" ]] ; then
local ename=${name//\#/\\#}
echo -n " - $ename"
fi
if [[ -n "$TODO" ]] ; then
echo -n " # TODO $TODO" ;
if (( result != 0 )) ; then
_failed_tests=$(( _failed_tests - 1 ))
fi
fi
echo
if (( result != 0 )) ; then
local file='tap-functions'
local func=
local line=
local i=0
local bt=$(caller $i)
while _matches "$bt" "tap-functions$" ; do
i=$(( $i + 1 ))
bt=$(caller $i)
done
local backtrace=
eval $(caller $i | (read line func file ; echo "backtrace=\"$file:$func() at line $line.\""))
local t=
[[ -n "$TODO" ]] && t="(TODO) "
if [[ -n "$name" ]] ; then
diag " Failed ${t}test '$name'"
diag " in $backtrace"
else
diag " Failed ${t}test in $backtrace"
fi
fi
return $result
}
okx(){
local command="$@"
local line=
diag "Output of '$command':"
$command | while read line ; do
diag "$line"
done
ok ${PIPESTATUS[0]} "$command"
}
_equals(){
local result=${1:?}
local expected=${2:?}
if [[ "$result" == "$expected" ]] ; then
return 0
else
return 1
fi
}
# Thanks to Aaron Kangas for the patch to allow regexp matching
# under bash < 3.
_bash_major_version=${BASH_VERSION%%.*}
_matches(){
local result=${1:?}
local pattern=${2:?}
if [[ -z "$result" || -z "$pattern" ]] ; then
return 1
else
if (( _bash_major_version >= 3 )) ; then
eval '[[ "$result" =~ "$pattern" ]]'
else
echo "$result" | egrep -q "$pattern"
fi
fi
}
_is_diag(){
local result=${1:?}
local expected=${2:?}
diag " got: '$result'"
diag " expected: '$expected'"
}
is(){
local result=${1:?}
local expected=${2:?}
local name=${3:-''}
_equals "$result" "$expected"
(( $? == 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && _is_diag "$result" "$expected"
return $r
}
isnt(){
local result=${1:?}
local expected=${2:?}
local name=${3:-''}
_equals "$result" "$expected"
(( $? != 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && _is_diag "$result" "$expected"
return $r
}
like(){
local result=${1:?}
local pattern=${2:?}
local name=${3:-''}
_matches "$result" "$pattern"
(( $? == 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && diag " '$result' doesn't match '$pattern'"
return $r
}
unlike(){
local result=${1:?}
local pattern=${2:?}
local name=${3:-''}
_matches "$result" "$pattern"
(( $? != 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && diag " '$result' matches '$pattern'"
return $r
}
skip(){
local condition=${1:?}
local reason=${2:-''}
local n=${3:-1}
if (( condition == 0 )) ; then
local i=
for (( i=0 ; i<$n ; i++ )) ; do
_executed_tests=$(( _executed_tests + 1 ))
echo "ok $_executed_tests # skip: $reason"
done
return 0
else
return
fi
}
diag(){
local msg=${1:?}
if [[ -n "$msg" ]] ; then
echo "# $msg"
fi
return 1
}
_die(){
local reason=${1:-'<unspecified error>'}
echo "$reason" >&2
_test_died=1
_exit 255
}
BAIL_OUT(){
local reason=${1:-''}
echo "Bail out! $reason" >&2
_exit 255
}
_cleanup(){
local rc=0
if (( _plan_set == 0 )) ; then
diag "Looks like your test died before it could output anything."
return $rc
fi
if (( _test_died != 0 )) ; then
diag "Looks like your test died just after $_executed_tests."
return $rc
fi
if (( _skip_all == 0 && _no_plan != 0 )) ; then
_print_plan $_executed_tests
fi
local s=
if (( _no_plan == 0 && _expected_tests < _executed_tests )) ; then
s= ; (( _expected_tests > 1 )) && s=s
local extra=$(( _executed_tests - _expected_tests ))
diag "Looks like you planned $_expected_tests test$s but ran $extra extra."
rc=-1 ;
fi
if (( _no_plan == 0 && _expected_tests > _executed_tests )) ; then
s= ; (( _expected_tests > 1 )) && s=s
diag "Looks like you planned $_expected_tests test$s but only ran $_executed_tests."
fi
if (( _failed_tests > 0 )) ; then
s= ; (( _failed_tests > 1 )) && s=s
diag "Looks like you failed $_failed_tests test$s of $_executed_tests."
fi
return $rc
}
_exit_status(){
if (( _no_plan != 0 || _plan_set == 0 )) ; then
return $_failed_tests
fi
if (( _expected_tests < _executed_tests )) ; then
return $(( _executed_tests - _expected_tests ))
fi
return $(( _failed_tests + ( _expected_tests - _executed_tests )))
}
_exit(){
local rc=${1:-''}
if [[ -z "$rc" ]] ; then
_exit_status
rc=$?
fi
_cleanup
local alt_rc=$?
(( alt_rc != 0 )) && rc=$alt_rc
trap - EXIT
exit $rc
}