-
Notifications
You must be signed in to change notification settings - Fork 161
/
firedrake-install
executable file
·2119 lines (1838 loc) · 91.1 KB
/
firedrake-install
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
import logging
import platform
import subprocess
import sys
import os
import shutil
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import argparse
from collections import OrderedDict
import atexit
import json
import pprint
import shlex
from glob import iglob
from itertools import chain
import re
import importlib
try:
from pkg_resources.extern.packaging.version import Version, InvalidVersion
except ModuleNotFoundError:
from packaging.version import Version, InvalidVersion
osname = platform.uname().system
arch = platform.uname().machine
# Packages which we wish to ensure are always recompiled
wheel_blacklist = ["mpi4py", "randomgen", "numpy"]
# Packages for which we set CC=mpicc, CXX=mpicxx, F90=mpif90.
parallel_packages = ["h5py", "petsc4py", "slepc", "slepc4py", "PyOP2", "libsupermesh", "firedrake"]
# Firedrake application installation shortcuts.
firedrake_apps = {
"gusto": ("""Atmospheric dynamical core library. http://firedrakeproject.org/gusto""",
"git+ssh://github.com/firedrakeproject/gusto.git@main#egg=gusto"),
"thetis": ("""Coastal ocean model. http://thetisproject.org""",
"git+ssh://github.com/thetisproject/thetis#egg=thetis"),
"icepack": ("""Glacier and ice sheet model. https://icepack.github.io""",
"git+ssh://github.com/icepack/icepack.git#egg=icepack"),
"irksome": ("""Implicit Runge-Kutta methods. https://github.com/firedrakeproject/Irksome/""",
"git+ssh://github.com/firedrakeproject/Irksome.git#egg=Irksome"),
"femlium": ("""Interactive visualization of finite element simulations on geographic maps with folium. https://femlium.github.io/""",
"git+ssh://github.com/FEMlium/FEMlium.git@main#egg=FEMlium"),
"fascd": ("""Full approximation scheme constraint decomposition solver for variational inequalities. https://bitbucket.org/pefarrell/fascd""",
"git+ssh://bitbucket.org/pefarrell/fascd.git@master#egg=fascd"),
"defcon": ("""Deflated continuation algorithm for bifurcation analysis. https://bitbucket.org/pefarrell/defcon""",
"git+ssh://bitbucket.org/pefarrell/defcon.git@master#egg=defcon"),
"gadopt": ("""Geodynamic Adjoint Optimization Platform. http://g-adopt.github.io""",
"git+ssh://github.com/g-adopt/g-adopt.git@master#egg=gadopt"),
"asQ": ("""ParaDiag parallel-in-time methods. http://firedrakeproject.org/asQ""",
"git+ssh://github.com/firedrakeproject/asQ.git@master#egg=asQ"),
}
class InstallError(Exception):
# Exception for generic install problems.
pass
class FiredrakeConfiguration(dict):
"""A dictionary extended to facilitate the storage of Firedrake
configuration information."""
def __init__(self, args=None):
super(FiredrakeConfiguration, self).__init__()
'''A record of the persistent options in force.'''
self["options"] = {}
'''Relevant environment variables.'''
self["environment"] = {}
'''Additional packages installed via the plugin interface.'''
self["additions"] = []
if args:
for o in self._persistent_options:
if o in args.__dict__.keys():
self["options"][o] = args.__dict__[o]
_persistent_options = ["package_manager",
"minimal_petsc", "mpicc", "mpicxx", "mpif90", "mpiexec", "disable_ssh",
"honour_petsc_dir", "with_parmetis",
"slepc", "packages", "honour_pythonpath",
"opencascade", "torch", "jax",
"petsc_int_type", "cache_dir", "complex", "remove_build_files", "with_blas", "netgen"]
def deep_update(this, that):
from collections import abc
for k, v in that.items():
if isinstance(v, abc.Mapping) and k in this.keys():
this[k] = deep_update(this.get(k, {}), v)
else:
this[k] = v
return this
if os.path.basename(__file__) == "firedrake-install":
mode = "install"
logfile_directory = os.path.abspath(os.getcwd())
logfile_mode = "w"
elif os.path.basename(__file__) == "firedrake-update":
mode = "update"
os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../..")
try:
logfile_directory = os.environ["VIRTUAL_ENV"]
except KeyError:
quit("Unable to retrieve venv name from the environment.\n Please ensure the venv is active before running firedrake-update.")
logfile_mode = "a" if "--no-update-script" in sys.argv else "w"
else:
sys.exit("Script must be invoked either as firedrake-install or firedrake-update")
# Set up logging
# Log to file at DEBUG level
if ("-h" in sys.argv) or ("--help" in sys.argv):
# Don't log if help displayed to avoid overwriting an existing log
logfile = os.devnull
else:
logfile = os.path.join(logfile_directory, 'firedrake-%s.log' % mode)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-6s %(message)s',
filename=logfile,
filemode=logfile_mode)
# Log to console at INFO level
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
log = logging.getLogger()
log.info("Running %s" % " ".join(sys.argv))
if sys.version_info >= (3, 14):
print("""\nCan not install Firedrake with Python 3.14 at the moment:
Some wheels are not yet available for Python 3.14 for some required package(s).
Please install with Python 3.13 (or an earlier version >= 3.10).""")
sys.exit(1)
elif sys.version_info < (3, 10):
if mode == "install":
print("""\nInstalling Firedrake requires Python 3, at least version 3.10.
You should run firedrake-install with python3.""")
if mode == "update":
if hasattr(sys, "real_prefix"):
# sys.real_prefix exists iff we are in an active virtualenv.
#
# Existing install trying to update past the py2/py3 barrier
print("""\nFiredrake is now Python 3 only. You cannot upgrade your existing installation.
Please follow the instructions at http://www.firedrakeproject.org/download.html to reinstall.""")
sys.exit(1)
else:
# Accidentally (?) running firedrake-update with python2.
print("""\nfiredrake-update must be run with Python 3, did you accidentally use Python 2?""")
sys.exit(1)
branches = {}
def resolve_doi_branches(doi):
import requests
import hashlib
log.info("Installing Firedrake components specified by {}".format(doi))
# Zenodo updated their API to use elastic search so simply querying with
# ?q=doi:10.5281/zenodo.<id> now returns multiple results (not ideal)
# Instead use
# /<id>
# as documented here https://developers.zenodo.org/#retrieve
id_ = doi.split('.')[-1]
response = requests.get("https://zenodo.org/api/records/{}".format(id_))
if not response.ok:
log.error("Unable to obtain Zenodo record for doi {}".format(doi))
log.error("Response was {}".format(response.json()))
sys.exit(1)
record = response.json()
files = record["files"]
try:
componentjson, = (f for f in files if f["key"] == "components.json")
except ValueError:
log.error("Expecting to find exactly one 'components.json' in record")
sys.exit(1)
download = requests.get(componentjson["links"]["self"])
if download.status_code >= 400:
log.error("Unable to download 'components.json'")
log.error("Response was {}".format(download.json()))
sys.exit(1)
# component response has checksum as "md5:HEXDIGEST", strip the md5.
if hashlib.md5(download.content).hexdigest() != componentjson["checksum"][4:]:
log.error("Download failed checksum, expecting {expect}, got {got}".format(
expect=componentjson["checksum"][4:],
got=hashlib.md5(download.content).hexdigest()))
sys.exit(1)
componentjson = download.json()
branches = {}
for record in componentjson["components"]:
commit = record["commit"]
component = record["component"]
package = component[component.find("/")+1:].lower()
branches[package] = commit
log.info("Using commit {commit} for component {comp}".format(
commit=commit, comp=component))
return branches
def honour_petsc_dir_get_petsc_dir():
try:
petsc_dir = os.environ["PETSC_DIR"]
except KeyError:
raise InstallError("Unable to find installed PETSc (did you forget to set PETSC_DIR?)")
petsc_arch = os.environ.get("PETSC_ARCH", "")
return petsc_dir, petsc_arch
def honour_petsc_dir_fetch_petscconf(name):
# Return the line in "petscconf.h" that starts with name.
petsc_dir, petsc_arch = honour_petsc_dir_get_petsc_dir()
petscconf_h = os.path.join(petsc_dir, petsc_arch, "include", "petscconf.h")
with open(petscconf_h) as fh:
for line in fh.readlines():
if line.startswith(name):
return line
def honour_petsc_dir_get_petsc_int_type():
line = honour_petsc_dir_fetch_petscconf("#define PETSC_USE_64BIT_INDICES")
if line and line.split()[2] == '1':
return "int64"
else:
return "int32"
def honour_petsc_dir_get_petsc_packages():
line = honour_petsc_dir_fetch_petscconf("#define PETSC_HAVE_PACKAGES")
return set(line.split()[2].strip().strip(':"').split(':'))
if mode == "install":
# Handle command line arguments.
parser = ArgumentParser(description="""Install firedrake and its dependencies.""",
epilog="""The install process has three steps.
1. Any required system packages are installed using brew (MacOS) or apt (Ubuntu
and similar Linux systems). On a Linux system without apt, the installation
will fail if a dependency is not found.
2. A set of standard and/or third party Python packages is installed to the
specified install location.
3. The core set of Python packages is downloaded to ./firedrake/src/ and
installed to the specified location.
The install creates a venv in ./firedrake (or in ./name where name is the
parameter given to --venv-name) and installs inside that venv.
The installer will ensure that the required configuration options are
passed to PETSc. In addition, any configure options which you provide
in the PETSC_CONFIGURE_OPTIONS environment variable will be
honoured.""",
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("--slepc", action="store_true",
help="Install SLEPc along with PETSc.")
parser.add_argument("--opencascade", action="store_true",
help="Install OpenCASCADE for CAD integration.")
parser.add_argument("--torch", const="cpu", default=False, nargs='?', choices=["cpu", "cuda"],
help="Install PyTorch for a CPU or CUDA backend (default: CPU).")
parser.add_argument("--jax", const="cpu", default=False, nargs='?', choices=["cpu", "cuda"],
help="Install JAX for a CPU or CUDA backend (default: CPU).")
parser.add_argument("--disable-ssh", action="store_true",
help="Do not attempt to use ssh to clone git repositories: fall immediately back to https.")
parser.add_argument("--no-package-manager", action='store_false', dest="package_manager",
help="Do not attempt to use apt or homebrew to install operating system packages on which we depend.")
group = parser.add_mutually_exclusive_group()
group.add_argument("--minimal-petsc", action="store_true",
help="Minimise the set of petsc dependencies installed. This creates faster build times (useful for build testing).")
group.add_argument("--with-parmetis", action="store_true",
help="Install PETSc with ParMETIS? (Non-free license, see http://glaros.dtc.umn.edu/gkhome/metis/parmetis/download)")
parser.add_argument("--honour-petsc-dir", action="store_true",
help="Usually it is best to let Firedrake build its own PETSc. If you wish to use another PETSc, set PETSC_DIR and pass this option.")
parser.add_argument("--petsc-int-type", choices=["int32", "int64"],
default="int32", type=str,
help="The integer type used by PETSc. Use int64 if you need to solve problems with more than 2 billion degrees of freedom. Only takes effect if firedrake-install builds PETSc.")
parser.add_argument("--honour-pythonpath", action="store_true",
help="Pointing to external Python packages is usually a user error. Set this option if you know that you want PYTHONPATH set.")
parser.add_argument("--rebuild-script", action="store_true",
help="Only rebuild the firedrake-install script. Use this option if your firedrake-install script is broken and a fix has been released in upstream Firedrake. You will need to specify any other options which you wish to be honoured by your new update script.")
parser.add_argument("--doi", type=str, nargs=1,
help="Install a set of components matching a particular Zenodo DOI. The record should have been created with firedrake-zenodo.")
# Used for testing if Zenodo broke the API
# Tries to resolve to a known DOI and immediately exits.
parser.add_argument("--test-doi-resolution", action="store_true",
help=argparse.SUPPRESS)
parser.add_argument("--package-branch", type=str, nargs=2, action="append", metavar=("PACKAGE", "BRANCH"),
help="Specify which branch of a package to use. This takes two arguments, the package name and the branch.")
parser.add_argument("--verbose", "-v", action="store_true", help="Produce more verbose debugging output.")
parser.add_argument("--mpicc", type=str,
action="store", default=None,
help="C compiler to use when building with MPI. If not set, MPICH will be downloaded and used.")
parser.add_argument("--mpicxx", type=str,
action="store", default=None,
help="C++ compiler to use when building with MPI. If not set, MPICH will be downloaded and used.")
parser.add_argument("--mpif90", type=str,
action="store", default=None,
help="Fortran compiler to use when building with MPI. If not set, MPICH will be downloaded and used.")
parser.add_argument("--mpiexec", type=str,
action="store", default=None,
help="MPI launcher. If not set, MPICH will be downloaded and used.")
parser.add_argument("--mpi4py-version", help="Specify an exact version of mpi4py to install")
parser.add_argument("--show-petsc-configure-options", action="store_true",
help="Print out the configure options passed to PETSc and exit")
parser.add_argument("--show-dependencies", action="store_true",
help="Print out the package manager used and packages installed/required.")
parser.add_argument("--venv-name", default="firedrake",
type=str, action="store",
help="Name of the venv to create and the name of the install directory relative to this install script (default is 'firedrake' with directory ./firedrake)")
parser.add_argument("--install", action="append", dest="packages",
help="Additional packages to be installed. The address should be in format vcs+protocol://repo_url/#egg=pkg&subdirectory=pkg_dir . Some additional packages have shortcut install options for more information see --install-help.")
parser.add_argument("--pip-install", action="append", dest="pip_packages",
help="Pip install additional packages into the venv")
parser.add_argument("--install-help", action="store_true",
help="Provide information on packages which can be installed using shortcut names.")
parser.add_argument("--cache-dir", type=str,
action="store",
help="Directory to use for disk caches of compiled code (default is the .cache subdirectory of the Firedrake installation).")
parser.add_argument("--complex", action="store_true",
help="Installs the complex version of Firedrake; rebuilds PETSc in complex mode.")
parser.add_argument("--documentation-dependencies", action="store_true",
help="Install the dependencies required to build the documentation")
parser.add_argument("--remove-build-files", action="store_true",
help="Cleans up build artefacts from Firedrake venv. Unless you really cannot spare the disk space, this option is not recommended")
parser.add_argument("--with-blas", default=("download" if osname == "Darwin" else None),
help="Specify path to system BLAS directory. Use '--with-blas=download' to download openblas")
parser.add_argument("--netgen", action="store_true",
help="Install NGSolve/Netgen and ngsPETSc.")
parser.add_argument("--no-vtk", action="store_true",
help="Do not install VTK into the Firedrake virtualenv")
args = parser.parse_args()
# If the user has set any MPI info, they must set them all
if args.mpicc or args.mpicxx or args.mpif90 or args.mpiexec:
if not (args.mpicc and args.mpicxx and args.mpif90 and args.mpiexec):
log.error("If you set any MPI information, you must set all of {mpicc, mpicxx, mpif90, mpiexec}.")
sys.exit(1)
if args.package_branch:
branches = {package.lower(): branch for package, branch in args.package_branch}
if args.test_doi_resolution:
actual = resolve_doi_branches("10.5281/zenodo.1322546")
expect = {'coffee': '87e50785d3a05b111f5423a66d461cd44cc4bdc9',
'finat': 'aa74fd499304c8363a4520555fd62ef21e8e5e1f',
'fiat': '184601a46c24fb5cbf8fd7961d22b16dd26890e7',
'firedrake': '6a30b64da01eb587dcc0e04e8e6b84fe4839bdb7',
'petsc': '413f72f04f5cb0a010c85e03ed029573ff6d4c63',
'petsc4py': 'ac2690070a80211dfdbab04634bdb3496c14ca0a',
'tsfc': 'fe9973eaacaa205fd491cd1cc9b3743b93a3d076',
'ufl': 'c5eb7fbe89c1091132479c081e6fa9c182191dcc',
'pyop2': '741a21ba9a62cb67c0aa300a2e199436ea8cb61c'}
if actual != expect:
log.error("Unable to resolve DOI correctly.")
log.error("You'll need to figure out how Zenodo have changed their API.")
sys.exit(1)
else:
log.info("DOI resolution test passed.")
sys.exit(0)
if args.doi:
branches = resolve_doi_branches(args.doi[0])
if args.honour_petsc_dir:
petsc_int_type = honour_petsc_dir_get_petsc_int_type()
if petsc_int_type != args.petsc_int_type:
petsc_dir, petsc_arch = honour_petsc_dir_get_petsc_dir()
log.warning("Provided PETSc (PETSC_DIR=%s, PETSC_ARCH=%s) was compiled for %s, but given --petsc-int-type = %s: setting --petsc-int-type %s." % (petsc_dir, petsc_arch, petsc_int_type, args.petsc_int_type, petsc_int_type))
args.petsc_int_type = petsc_int_type
args.prefix = False # Disabled as untested
args.packages = args.packages or []
config = FiredrakeConfiguration(args)
else:
# This duplicates code from firedrake_configuration in order to avoid the module dependency and allow for installation recovery.
try:
with open(os.path.join(os.environ["VIRTUAL_ENV"],
".configuration.json"), "r") as f:
config = json.load(f)
except FileNotFoundError:
# Fall back to the old location.
import firedrake_configuration
config = firedrake_configuration.get_config()
if config is None:
raise InstallError("Failed to find existing Firedrake configuration")
parser = ArgumentParser(description="""Update this firedrake install to the latest versions of all packages.""",
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("--no-update-script", action="store_false", dest="update_script",
help="Do not update script before updating Firedrake.")
parser.add_argument("--rebuild", action="store_true",
help="Rebuild all packages even if no new version is available. Usually petsc and petsc4py are only rebuilt if they change. All other packages are always rebuilt.")
parser.add_argument("--rebuild-script", action="store_true",
help="Only rebuild the firedrake-install script. Use this option if your firedrake-install script is broken and a fix has been released in upstream Firedrake. You will need to specify any other options which you wish to be honoured by your new update script.")
parser.add_argument("--slepc", action="store_true", dest="slepc", default=config["options"]["slepc"],
help="Install SLEPc along with PETSc")
parser.add_argument("--opencascade", action="store_true", dest="opencascade", default=config["options"].get("opencascade", False),
help="Install OpenCASCADE for CAD integration.")
parser.add_argument("--torch", const="cpu", nargs='?', choices=["cpu", "cuda"], default=config["options"].get("torch", False),
help="Install PyTorch for a CPU or CUDA backend (default: CPU).")
parser.add_argument("--jax", const="cpu", nargs='?', choices=["cpu", "cuda"], default=config["options"].get("jax", False),
help="Install JAX for a CPU or CUDA backend (default: CPU).")
parser.add_argument("--honour-petsc-dir", action="store_true",
default=config["options"]["honour_petsc_dir"],
help="Usually it is best to let Firedrake build its own PETSc. If you wish to use another PETSc, set PETSC_DIR and pass this option.")
parser.add_argument("--petsc-int-type", choices=["int32", "int64"],
default=config["options"]["petsc_int_type"], type=str,
help="The integer type used by PETSc. Use int64 if you need to solve problems with more than 2 billion degrees of freedom. Only takes effect if firedrake-install builds PETSc.")
parser.add_argument("--honour-pythonpath", action="store_true", default=config["options"].get("honour_pythonpath", False),
help="Pointing to external Python packages is usually a user error. Set this option if you know that you want PYTHONPATH set.")
parser.add_argument("--clean", action='store_true',
help="Delete any remnants of obsolete Firedrake components.")
parser.add_argument("--verbose", "-v", action="store_true", help="Produce more verbose debugging output.")
parser.add_argument("--install", action="append", dest="packages", default=config["options"].get("packages", []),
help="Additional packages to be installed. The address should be in format vcs+protocol://repo_url/#egg=pkg&subdirectory=pkg_dir. Some additional packages have shortcut install options for more information see --install-help.")
parser.add_argument("--pip-install", action="append", dest="pip_packages",
help="Pip install additional packages into the venv")
parser.add_argument("--install-help", action="store_true",
help="Provide information on packages which can be installed using shortcut names.")
parser.add_argument("--cache-dir", type=str,
action="store", default=config["options"].get("cache_dir", ""),
help="Directory to use for disk caches of compiled code (default is the .cache subdirectory of the Firedrake installation).")
complex_group = parser.add_mutually_exclusive_group()
complex_group.add_argument("--complex", action="store_true",
help="Updates to the complex version of Firedrake; rebuilds PETSc in complex mode.")
complex_group.add_argument("--real", action="store_true",
help="Updates to the real version of Firedrake; rebuilds PETSc in real mode.")
parser.add_argument("--documentation-dependencies", action="store_true",
help="Install the dependencies required to build the documentation")
parser.add_argument("--show-dependencies", action="store_true",
help="Print out the package manager used and packages installed/required.")
parser.add_argument("--remove-build-files", action="store_true",
help="Cleans up build artefacts from Firedrake venv. Unless you really cannot spare the disk space, this option is not recommended")
parser.add_argument("--with-blas", default=("download" if osname == "Darwin" else None),
help="Specify path to system BLAS directory. Use '--with-blas=download' to download openblas")
parser.add_argument("--netgen", action="store_true", dest="netgen", default=config["options"].get("netgen", False),
help="Install Netgen.")
parser.add_argument("--mpi4py-version", help="Specify an exact version of mpi4py to install")
args = parser.parse_args()
args.packages = list(set(args.packages)) # remove duplicates
if args.honour_petsc_dir != config["options"]["honour_petsc_dir"]:
log.error("You installed Firedrake with --honour-petsc-dir=%s, but are trying to update it with --honour-petsc-dir=%s." % (config["options"]["honour_petsc_dir"], args.honour_petsc_dir))
exit(1)
if args.honour_petsc_dir:
# Set int_type to the one found in petscconf.h
petsc_int_type = honour_petsc_dir_get_petsc_int_type()
if petsc_int_type != args.petsc_int_type:
petsc_dir, petsc_arch = honour_petsc_dir_get_petsc_dir()
log.warning("Provided PETSc (PETSC_DIR=%s, PETSC_ARCH=%s) was compiled for %s, but given --petsc-int-type = %s: setting --petsc-int-type %s." % (petsc_dir, petsc_arch, petsc_int_type, args.petsc_int_type, petsc_int_type))
args.petsc_int_type = petsc_int_type
petsc_int_type_changed = False
if config["options"]["petsc_int_type"] != args.petsc_int_type:
petsc_int_type_changed = True
args.rebuild = True
if config["options"].get("with_blas") is not None:
if config["options"].get("with_blas") != args.with_blas:
# Rebuild if BLAS library explicitly changed at command line
args.rebuild = True
else:
# Prevent deep_update overwriting BLAS options if they exist in the config, but are unspecified at the command line
args.with_blas = config["options"].get("with_blas")
petsc_complex_type_changed = False
previously_complex = config["options"].get("complex", False)
now_complex = not args.real and (args.complex or previously_complex)
if previously_complex != now_complex:
petsc_complex_type_changed = True
args.rebuild = True
args.complex = now_complex
config = deep_update(config, FiredrakeConfiguration(args))
if args.install_help:
help_string = """
You can install the following packages by passing --install shortname
where shortname is one of the names given below:
"""
componentformat = "|{:10}|{:70}|\n"
header = componentformat.format("Name", "Description")
line = "-" * (len(header) - 1) + "\n"
help_string += line + header + line
for package, d in firedrake_apps.items():
help_string += componentformat.format(package, d[0])
help_string += line
print(help_string)
sys.exit(0)
def sniff_compiler(exe):
"""Obtain the correct compiler class by calling the compiler executable.
Attempt to determine the compiler version number.
:arg cpp: If set to True will use the C++ compiler rather than
the C compiler to determine the version number.
:arg exe: String with name or path to compiler executable
:returns: A compiler class
"""
# NAME
try:
output = subprocess.run(
[exe, "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
encoding="utf-8"
).stdout
except (subprocess.CalledProcessError, UnicodeDecodeError):
output = ""
# Find the name of the compiler family
if output.startswith("gcc") or output.startswith("g++") or output.startswith("GNU"):
name = "GNU"
elif output.startswith("clang"):
name = "clang"
elif output.startswith("Apple LLVM") or output.startswith("Apple clang"):
name = "clang"
elif output.startswith("icc"):
name = "Intel"
elif "Cray" in output.split("\n")[0]:
# Cray is more awkward eg:
# Cray clang version 11.0.4 (<some_hash>)
# gcc (GCC) 9.3.0 20200312 (Cray Inc.)
name = "Cray"
else:
name = "unknown"
# VERSION
version = None
for dumpstring in ["-dumpfullversion", "-dumpversion"]:
try:
output = subprocess.run(
[exe, dumpstring],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
encoding="utf-8"
).stdout
version = Version(output)
break
except (subprocess.CalledProcessError, UnicodeDecodeError, InvalidVersion):
continue
return name, version
# Temporary catch for tigerlake processors with gcc/g++/gfortran 9.3
if platform.system() == "Linux" and mode == "install":
# Get the cpu information
try:
cpuinfostring = subprocess.run(
["lscpu"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
encoding="utf-8"
).stdout
except (subprocess.CalledProcessError, UnicodeDecodeError):
output = ""
# Check if it is a tigerlake processor ie: "i3-11", "i5-11", "i7-11"
if any(bad_cpu in cpuinfostring for bad_cpu in ["i3-11", "i5-11", "i7-11"]):
# Get the compiler names and versions
try:
cc = sniff_compiler(args.mpicc or "gcc")
cxx = sniff_compiler(args.mpicxx or "g++")
fortran = sniff_compiler(args.mpif90 or "gfortran")
# Check if the combination is a problem
if any(map(lambda compiler: compiler[0] == "GNU" and compiler[1] < Version("9.4"), [cc, cxx, fortran])):
log.info(
"\nUsing a Tiger Lake (or newer) CPU with gcc, g++ and gfortran version<=9.3 is not possible."
" Please install at least gcc, g++ and gfortran version 9.4.0 or later"
)
sys.exit(1)
except (subprocess.CalledProcessError, FileNotFoundError):
log.info(
"\nFailed to sniff compiler version, perhaps there is no compiler installed.\n"
"You can ignore this if you are not using a Tiger Lake (or newer) CPU with gcc, g++ or gfortran version<=9.3\n"
)
@atexit.register
def print_log_location():
log.info("\n\n%s log saved in %s" % (mode.capitalize(), logfile))
class directory(object):
"""Context manager that executes body in a given directory"""
def __init__(self, dir):
self.dir = os.path.abspath(dir)
def __enter__(self):
self.olddir = os.path.abspath(os.getcwd())
log.debug("Old path '%s'" % self.olddir)
log.debug("Pushing path '%s'" % self.dir)
os.chdir(self.dir)
def __exit__(self, *args):
log.debug("Popping path '%s'" % self.dir)
os.chdir(self.olddir)
log.debug("New path '%s'" % self.olddir)
class environment(object):
def __init__(self, **env):
self.old = os.environ.copy()
self.new = env
def __enter__(self):
os.environ.update(self.new)
def __exit__(self, *args):
os.environ = self.old
options = config["options"]
# Apply short cut package names. pyadjoint shoud no longer turn up the packages list because it is a hard dependency.
options["packages"] = [firedrake_apps.get(p, (None, p))[1] for p in options["packages"] if not p.endswith("pyadjoint")]
# Record of obsolete packages which --clean should remove from old installs.
old_git_packages = ["dolfin-adjoint", "libadjoint"]
if mode == "install":
firedrake_env = os.path.abspath(args.venv_name)
else:
firedrake_env = os.environ["VIRTUAL_ENV"]
if "cache_dir" not in config["options"] or not config["options"]["cache_dir"]:
config["options"]["cache_dir"] = os.path.join(firedrake_env, ".cache")
# venv install
python = "%s/bin/python" % firedrake_env
# Use the pip from the venv
pip = [python, "-m", "pip"]
pipinstall = pip + ["install",
"--no-build-isolation",
"--no-binary", ",".join(wheel_blacklist)]
if mode == "install":
# "petsc4py" is in `branches` when we are explicitly asking for a petsc4py
# branch that lives in firedrake-project/petsc4py. This happens when we do:
# python3 firedrake-install --doi some_old_zenodo_doi ...
# or:
# python3 firedrake-install --package-branch petsc4py some_old_branch ...
use_petsc4py_in_petsc = "petsc4py" not in branches
use_slepc4py_in_slepc = "slepc4py" not in branches
else:
use_petsc4py_in_petsc = True
use_slepc4py_in_slepc = True
# This context manager should be used whenever arguments should be temporarily added to pipinstall.
class pipargs(object):
def __init__(self, *args):
self.args = args
def __enter__(self):
self.save = pipinstall.copy()
pipinstall.extend(self.args)
def __exit__(self, *args, **kwargs):
global pipinstall
pipinstall = self.save
def check_call(arguments):
try:
log.debug("Running command '%s'", " ".join(arguments))
log.debug(subprocess.check_output(arguments, stderr=subprocess.STDOUT, env=os.environ).decode())
except subprocess.CalledProcessError as e:
log.debug(e.output.decode())
raise
def check_output(args):
try:
log.debug("Running command '%s'", " ".join(args))
return subprocess.check_output(args, stderr=subprocess.STDOUT, env=os.environ).decode()
except subprocess.CalledProcessError as e:
log.debug(e.output.decode())
raise
if "PYTHONPATH" in os.environ and not args.honour_pythonpath:
quit("""The PYTHONPATH environment variable is set. This is probably an error.
If you really want to use your own Python packages, please run again with the
--honour-pythonpath option.
""")
def brew_gcc_libdir():
brew_gcc_prefix = check_output(["brew", "--prefix", "gcc"])[:-1]
brew_gcc_info = json.loads(check_output(["brew", "info", "--json", "gcc"])[:-1])
gcc_major_version = brew_gcc_info[0]["installed"][0]["version"].split(".")[0]
return brew_gcc_prefix + "/lib/gcc/" + gcc_major_version
# See .github/workflows/docker.yml to see the PETSc options used on CI.
# Edit these as appropriate if PETSc external packages are added or removed.
def get_minimal_petsc_packages():
pkgs = set()
# File format
pkgs.add("hdf5")
# Parallel mesh partitioner
pkgs.add("ptscotch")
# Sparse direct solver
pkgs.add("scalapack") # Needed for mumps
pkgs.add("mumps")
return pkgs
def get_petsc_options(minimal=False):
# The logic in this function is getting out of hand...
petsc_options = {"--with-fortran-bindings=0",
"--with-debugging=0",
"--with-shared-libraries=1",
"--with-c2html=0",
# Parser generator
"--download-bison"}
for pkg in get_minimal_petsc_packages():
petsc_options.add("--download-" + pkg)
if osname == "Darwin":
petsc_options.add("--with-x=0")
# These three lines are used to inspect the MacOS Command Line Tools (CLT) version
cmd = ["pkgutil", "--pkg-info=com.apple.pkg.CLTools_Executables"]
output = subprocess.run(cmd, stdout=subprocess.PIPE, encoding="UTF-8")
clt = {k.strip(): v.strip() for k, v in [line.split(':') for line in output.stdout.split('\n') if line]}
elif osname == "Linux":
# PETSc requires cmake version 3.18.1 or higher.
petsc_options.add("--download-cmake")
if (not options["minimal_petsc"]) and (not minimal):
# Another sparse direct solver
petsc_options.add("--download-superlu_dist")
petsc_options.add("--with-zlib")
# File formats
petsc_options.add("--download-netcdf")
petsc_options.add("--download-pnetcdf")
# Sparse direct solvers
petsc_options.add("--download-suitesparse")
petsc_options.add("--download-pastix")
# Required by pastix
petsc_options.add("--download-hwloc")
if osname == "Darwin":
petsc_options.add("--download-hwloc-configure-arguments=--disable-opencl")
# Serial mesh partitioner
petsc_options.add("--download-metis")
if options.get("with_parmetis", None):
# Non-free license.
petsc_options.add("--download-parmetis")
if options["petsc_int_type"] != "int32":
petsc_options.add("--with-64-bit-indices")
if options["complex"]:
petsc_options.add('--with-scalar-type=complex')
else:
# AMG
petsc_options.add("--download-hypre")
if options.get("mpiexec") is not None:
petsc_options.add("--with-mpiexec={}".format(options["mpiexec"]))
petsc_options.add("--with-cc={}".format(options["mpicc"]))
petsc_options.add("--with-cxx={}".format(options["mpicxx"]))
petsc_options.add("--with-fc={}".format(options["mpif90"]))
else:
# Download mpich if the user does not tell us about an MPI.
petsc_options.add("--download-mpich")
if osname == "Darwin":
petsc_options.add("--download-mpich-configure-arguments=--disable-opencl")
if options.get("with_blas") == "download":
# Download openblas if the user specifies.
petsc_options.add("--download-openblas")
petsc_options.add("--download-openblas-make-options='USE_THREAD=0 USE_LOCKING=1 USE_OPENMP=0'")
if osname == "Darwin":
petsc_options.add("--CFLAGS=-Wno-implicit-function-declaration")
if Version(clt["version"]) >= Version("15"):
# CLT >= 15 requires legacy linking behaviour (-ld_classic flag)
# The -dead_strip_dylibs flag is a workaround for MUMPS issues
# on macOS with parallel solvers. Its necessity is unclear, so a
# review in the future may be required.
petsc_options.add("--LDFLAGS=-Wl,-ld_classic,-dead_strip_dylibs")
elif options.get("with_blas") is not None:
petsc_options.add("--with-blaslapack-dir={}".format(options["with_blas"]))
if osname == "Darwin":
petsc_options.add("--CFLAGS=-I{}/include -Wno-implicit-function-declaration".format(options["with_blas"]))
if Version(clt["version"]) >= Version("15"):
# CLT >= 15 requires legacy linking behaviour (-ld_classic flag)
# The -dead_strip_dylibs flag is a workaround for MUMPS issues
# on macOS with parallel solvers. Its necessity is unclear, so a
# review in the future may be required.
petsc_options.add("--LDFLAGS=-Wl,-ld_classic,-dead_strip_dylibs,-rpath,{0}/lib -L{0}/lib".format(options["with_blas"]))
else:
petsc_options.add("--CFLAGS=-I{}/include".format(options["with_blas"]))
petsc_options.add("--LDFLAGS=-Wl,-rpath,{0}/lib -L{0}/lib".format(options["with_blas"]))
elif osname == "Darwin":
brew_blas_prefix = check_output(["brew", "--prefix", "openblas"])[:-1]
petsc_options.add("--with-blaslapack-dir={}".format(brew_blas_prefix))
petsc_options.add("--CFLAGS=-I{}/include -Wno-implicit-function-declaration".format(brew_blas_prefix))
if Version(clt["version"]) >= Version("15"):
# CLT >= 15 requires legacy linking behaviour (-ld_classic flag)
# The -dead_strip_dylibs flag is a workaround for MUMPS issues
# on macOS with parallel solvers. Its necessity is unclear, so a
# review in the future may be required.
petsc_options.add("--LDFLAGS=-Wl,-ld_classic,-dead_strip_dylibs,-rpath,{0}/lib -L{0}/lib -L{1}".format(brew_blas_prefix, brew_gcc_libdir()))
else:
petsc_options.add("--LDFLAGS=-Wl,-rpath,{0}/lib -L{0}/lib -L{1}".format(brew_blas_prefix, brew_gcc_libdir()))
if not minimal:
for option in shlex.split(os.environ.get("PETSC_CONFIGURE_OPTIONS", "")):
if option.startswith("--with-hdf5-dir"):
petsc_options.discard("--download-hdf5")
os.environ["HDF5_DIR"] = option.replace("--with-hdf5-dir=", "")
petsc_options.add(option)
if "HDF5_DIR" in os.environ and "--download-hdf5" in petsc_options:
del os.environ["HDF5_DIR"]
log.info("\nWarning: HDF5_DIR environment variable set, but ignored; "
"use PETSC_CONFIGURE_OPTIONS=\"--with-hdf5-dir=$HDF5_DIR\" "
"to have PETSc built against $HDF5_DIR.")
return list(petsc_options)
def get_petsc_config():
petsc_dir, petsc_arch = get_petsc_dir()
with open(os.path.join(petsc_dir, petsc_arch, "include", "petscconfiginfo.h")) as fh:
for line in fh.readlines():
if line.startswith("static const char *petscconfigureoptions"):
info = line.split("=", maxsplit=1)[1].strip(' ";\n').split('--')[1:]
break
return ["--" + arg for arg in info]
if mode == "update" and petsc_int_type_changed:
log.warning("""Force rebuilding all packages because PETSc int type changed""")
if mode == "update" and petsc_complex_type_changed:
log.warning("""Force rebuilding all packages because PETSc scalar type changed between real and complex""")
def brew_install(name, options=None):
arguments = [name]
if options:
arguments = options + arguments
if args.verbose:
arguments = ["--verbose"] + arguments
check_call(["brew", "install"] + arguments)
def apt_check(name):
log.info("Checking for presence of package %s..." % name)
# Note that subprocess return codes have the opposite logical
# meanings to those of Python variables.
try:
check_call(["dpkg-query", "-s", name])
log.info(" installed.")
return True
except subprocess.CalledProcessError:
log.info(" missing.")
return False
def apt_install(names):
log.info("Installing missing packages: %s." % ", ".join(names))
if sys.stdin.isatty():
subprocess.check_call(["sudo", "apt-get", "install"] + names)
else:
log.info("Non-interactive stdin detected; installing without prompts")
subprocess.check_call(["sudo", "apt-get", "-y", "install"] + names)
def split_requirements_url(url):
name = url.split(".git")[0].split("#")[0].split("/")[-1]
spliturl = url.split("://")[1].split("#")[0].split("@")
try:
plain_url, branch = spliturl
except ValueError:
plain_url = spliturl[0]
branch = "master"
return name, plain_url, branch
def git_url(plain_url, protocol):
if protocol == "ssh":
return "git@%s:%s" % tuple(plain_url.split("/", 1))
elif protocol == "https":
return "https://%s" % plain_url
else:
raise ValueError("Unknown git protocol: %s" % protocol)
def git_clone(url):
name, plain_url, branch = split_requirements_url(url)
if name == "petsc" and args.honour_petsc_dir:
log.info("Using existing PETSc installation\n")
return name
elif name == "petsc4py" and use_petsc4py_in_petsc:
log.info("Not cloning petsc4py from firedrake-project repo: using petsc4py in PETSc source tree.\n")
return name
log.info("Cloning %s\n" % name)
branch = branches.get(name.lower(), branch)
try:
if options["disable_ssh"]:
raise InstallError("Skipping ssh clone because --disable-ssh")
# note: so far only loopy requires submodule
check_call(["git", "clone", "-q", "--recursive", git_url(plain_url, "ssh")])
log.info("Successfully cloned repository %s" % name)
except (subprocess.CalledProcessError, InstallError):
if not options["disable_ssh"]:
log.warning("Failed to clone %s using ssh, falling back to https." % name)
try:
check_call(["git", "clone", "-q", "--recursive", git_url(plain_url, "https")])
log.info("Successfully cloned repository %s." % name)
except subprocess.CalledProcessError:
log.error("Failed to clone %s branch %s." % (name, branch))
raise
with directory(name):
try:
log.info("Checking out branch %s" % branch)
check_call(["git", "checkout", "-q", branch])
log.info("Successfully checked out branch %s" % branch)
except subprocess.CalledProcessError:
log.error("Failed to check out branch %s" % branch)
raise
try:
log.info("Updating submodules.")
check_call(["git", "submodule", "update", "--recursive"])
log.info("Successfully updated submodules.")
except subprocess.CalledProcessError:
log.error("Failed to update submodules.")
raise
return name
def list_cloned_dependencies(name):
log.info("Finding dependencies of %s\n" % name)
deps = OrderedDict()
try:
for dep in open(name + "/requirements-git.txt", "r"):
name = split_requirements_url(dep.strip())[0]
deps[name] = dep.strip()
except IOError:
pass
return deps
def clone_dependencies(name):
log.info("Cloning the dependencies of %s" % name)
deps = []
try:
for dep in open(name + "/requirements-git.txt", "r"):
deps.append(git_clone(dep.strip()))
except IOError:
pass
return deps
def git_update(name, url=None):
# Update the named git repo and return true if the current branch actually changed.
log.info("Updating the git repository for %s" % name)
with directory(name):
git_sha = check_output(["git", "rev-parse", "HEAD"])
# Ensure remotes get updated if and when we move repositories.
if url:
_, plain_url, branch = split_requirements_url(url)
current_url = check_output(["git", "remote", "-v"]).split()[1]
current_branch = check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip()
protocol = "https" if current_url.startswith("https") else "ssh"
new_url = git_url(plain_url, protocol)
# Ensure we only change from bitbucket to github and not the reverse.
if (new_url != current_url
and ("bitbucket.org" in current_url)
and ("github.com/firedrakeproject" in plain_url
or "github.com/dolfin-adjoint" in plain_url)):
log.info("Updating git remote for %s" % name)
check_call(["git", "remote", "set-url", "origin", new_url])
# Ensure we only switch loopy branch if loopy is on firedrake and not on a feature branch.
elif name == "loopy" and current_branch != branch and current_branch == "firedrake":
log.info("Updating loopy branch to main")
check_call(["git", "checkout", "-q", branch])
check_call(["git", "pull", "--recurse-submodules"])
git_sha_new = check_output(["git", "rev-parse", "HEAD"])
return git_sha != git_sha_new
def run_pip(args):
check_call(pip + args)
def run_pip_install(pipargs):