/
_ParaMonteSampler.py
1875 lines (1478 loc) · 94.1 KB
/
_ParaMonteSampler.py
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
####################################################################################################################################
####################################################################################################################################
####
#### MIT License
####
#### ParaMonte: plain powerful parallel Monte Carlo library.
####
#### Copyright (C) 2012-present, The Computational Data Science Lab
####
#### This file is part of the ParaMonte library.
####
#### 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.
####
#### ACKNOWLEDGMENT
####
#### ParaMonte is an honor-ware and its currency is acknowledgment and citations.
#### As per the ParaMonte library license agreement terms, if you use any parts of
#### this library for any purposes, kindly acknowledge the use of ParaMonte in your
#### work (education/research/industry/development/...) by citing the ParaMonte
#### library as described on this page:
####
#### https://github.com/cdslaborg/paramonte/blob/main/ACKNOWLEDGMENT.md
####
####################################################################################################################################
####################################################################################################################################
import os
import sys
import typing as tp
import ctypes as ct
import _paramonte as pm
import _SpecBase as SpecBase
import _SpecMCMC as SpecMCMC
import _SpecDRAM as SpecDRAM
from _ReportFileContents import ReportFileContents
from _RestartFileContents import RestartFileContents
from _TabularFileContents import TabularFileContents
Struct = pm.Struct
newline = pm.newline
####################################################################################################################################
#### ParaMonteSampler class
####################################################################################################################################
class ParaMonteSampler:
"""
This is the **ParaMonteSampler** base class for the ParaMonte
sampler routines. This class is NOT meant to be directly accessed
or called by the user of the ParaMonte library. However, its children,
such as the ParaDRAM sampler class will be directly accessible to the public.
**Parameters**
methodName
A string representing the name of the ParaMonte sampler
that is to be instantiated.
**Attributes**
buildMode
optional string argument with the default value "release".
possible choices are:
"debug"
to be used for identifying sources of bug
and causes of code crash.
"release"
to be used in all other normal scenarios
for maximum runtime efficiency.
mpiEnabled
optional logical (boolean) indicator which is ``False`` by default.
If it is set to ``True``, it will cause the ParaMonte simulation
to run in parallel on the requested number of processors.
See the class documentation guidelines in the above for
information on how to run a simulation in parallel.
reportEnabled
optional logical (boolean) indicator which is ``True`` by default.
If it is set to ``True``, it will cause extensive guidelines to be
printed on the standard output as the simulation or post-processing
continues with hints on the next possible steps that could be taken
in the process. If you do not need such help and information set
this variable to ``False`` to silence all output messages.
inputFile
optional string input representing the path to
an external input namelist of simulation specifications.
USE THIS OPTIONAL ARGUMENT WITH CAUTION AND
ONLY IF YOU KNOW WHAT YOU ARE DOING.
**WARNING**
Specifying an input file will cause the sampler to ignore
all other simulation specifications set by the user via
sampler instance's `spec`-component attributes.
spec
A Python structure containing all simulation specifications.
All simulation attributes are by default set to appropriate
values at runtime. To override the default simulation
specifications, set the ``spec`` attributes to some
desired values of your choice.
If you need help on any of the simulation specifications, try
the supplied ``helpme()`` function in this component.
If you wish to reset some specifications to the default values,
simply set them to ``None``.
**Methods**
See below for information on the methods.
**Returns**
Object of class ParaMonteSampler.
"""
################################################################################################################################
#### ParaMonteSampler constructor
################################################################################################################################
def __init__( self
, methodName : str
):
self._methodName = methodName
self._libName = []
self._ndim = []
self._method = Struct()
self._method.isParaDRAM = False
self._method.isParaNest = False
self._method.isParaTemp = False
if self._methodName=="ParaDRAM":
self._method.isParaDRAM = True
self._objectName = "pmpd"
else:
pm.abort( msg = "Internal error occurred. No sampling method other than ParaDRAM is currently " + newline
+ "supported. Among its output files or simply, the path to the specific file " + newline
+ "to be read. Please report this error at:" + newline
+ newline
+ " " + pm.website.github.issues.url
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
self.buildMode = "release"
self.mpiEnabled = False
self.reportEnabled = not self.mpiEnabled
self.inputFile = ""
############################################################################################################################
#### ParaMonte specifications
############################################################################################################################
self.spec = pm.utils.FrozenClass()
# ParaMonte variables
self.spec.sampleSize = None
self.spec.randomSeed = None
self.spec.description = None
self.spec.outputFileName = None
self.spec.outputDelimiter = None
self.spec.chainFileFormat = None
self.spec.variableNameList = None
self.spec.restartFileFormat = None
self.spec.outputColumnWidth = None
self.spec.overwriteRequested = None
self.spec.outputRealPrecision = None
self.spec.silentModeRequested = None
self.spec.domainLowerLimitVec = None
self.spec.domainUpperLimitVec = None
self.spec.parallelizationModel = None
self.spec.progressReportPeriod = None
self.spec.targetAcceptanceRate = None
self.spec.mpiFinalizeRequested = None
self.spec.maxNumDomainCheckToWarn = None
self.spec.maxNumDomainCheckToStop = None
if self._method.isParaDRAM:
# ParaMCMC variables
self.spec.chainSize = None
self.spec.scaleFactor = None
self.spec.startPointVec = None
self.spec.proposalModel = None
self.spec.proposalStartCovMat = None
self.spec.proposalStartCorMat = None
self.spec.proposalStartStdVec = None
self.spec.sampleRefinementCount = None
self.spec.sampleRefinementMethod = None
self.spec.randomStartPointRequested = None
self.spec.randomStartPointDomainLowerLimitVec = None
self.spec.randomStartPointDomainUpperLimitVec = None
# ParaDRAM variables
self.spec.adaptiveUpdateCount = None
self.spec.adaptiveUpdatePeriod = None
self.spec.greedyAdaptationCount = None
self.spec.delayedRejectionCount = None
self.spec.burninAdaptationMeasure = None
self.spec.delayedRejectionScaleFactorVec = None
self.spec.helpme = SpecDRAM.helpme
self.spec._freeze()
################################################################################################################################
#### _runSampler
################################################################################################################################
def _runSampler ( self
, ndim : int
, getLogFuncRaw : tp.Callable[[int,tp.List[float]], float]
, inputFile : tp.Optional[str] = None
) -> None:
"""
Run ParaMonte sampler and return nothing. This method is identical to
the ``runSampler()`` method, except that the input ``point`` parameter to
the user-provided input objective function ``getLogFuncRaw(ndim,point)`` is
a C-style raw pointer. This requires the user to guarantee that ``point`` will
be always used with array bounds in their implementation of the objective function.
The use of ``_runSampler()`` in place of ``runSampler()`` might lead to a slight
performance gain in the simulations, that is often negligible.
**Example serial usage**
Copy and paste the following code enclosed between the
two comment lines in your python/ipython/jupyter session
(ensure the indentations of the pasted lines comply with Python rules):
.. code-block:: python
:linenos:
##################################
import paramonte as pm
import numpy as np
def getLogFuncRaw(ndim,point):
# return the log of the standard multivariate
# Normal density function with ndim dimensions
return -0.5 * np.sum( np.double( point[0:ndim] )**2 )
pmpd = pm.ParaDRAM()
pmpd._runSampler( ndim = 4 # length of point
, getLogFuncRaw = getLogFuncRaw # the objective function
)
##################################
where,
ndim
represents the number of dimensions of the domain of
the user's objective function ``getLogFuncRaw(ndim, point)``
and,
getLogFuncRaw(ndim, point)
represents the user's objective function to be sampled,
where,
ndim
is a 32-bit integer, representing the number of
dimensions of the domain of the user-provided
objective function.
point
is a C-style array-pointer of length ``ndim``
and type float64. Note that the bounds of
``point`` must be always specified wherever
it is used within the objective function.
On output, it must return the natural logarithm of
the objective function.
**Parameters**
All input parameters have the same meaning as the parameters
of ``runSampler()``. The only difference is in the input
parameters to the objective function ``getLogFuncRaw``.
**Returns**
None
"""
#### verify ndim
if not isinstance(ndim,int) or ndim<1:
pm.abort( msg = "The input argument ndim must be a positive integer," + newline
+ "representing the number of dimensions of the domain of" + newline
+ "the user's objective function ``getLogFunc()``." + newline
+ "You have entered ndim = " + str(ndim)
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
#### verify getLogFuncRaw
if not callable(getLogFuncRaw):
pm.abort( msg = "The input argument ``getLogFuncRaw`` must be a callable function." + newline
+ "It represents the user's objective function to be sampled," + newline
+ "which must take an input integer ndim representing the number of" + newline
+ "dimensions of the domain of the objective function to be samples and," + newline
+ "a second input argument of type numpy float64 array of length ndim." + newline
+ "On return it must return the natural logarithm of the objective function."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
#### verify mpiEnabled
if not isinstance(self.mpiEnabled,bool):
pm.abort( msg = "The sampler attribute ``mpiEnabled`` must be of type bool." + newline
+ "It is an optional logical (boolean) indicator which is False by default." + newline
+ "If it is set to True, it will cause the ParaMonte simulation" + newline
+ "to run in parallel on the requested number of processors." + newline
+ "See the ParaMonte class information on how to run a simulation " + newline
+ "in parallel. You have entered mpiEnabled = " + str(self.mpiEnabled)
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
if self.mpiEnabled: self.reportEnabled = False
#### verify buildMode
cstype = None
dummyList = None
parallelism = None
errorOccurred = True
memList = ["heap", "stack"]
btypeList = ["release","testing","debug"]
if isinstance(self.buildMode,str):
errorOccurred = False
dummyList = self.buildMode.lower().split("-")
for item in dummyList:
if item in ["debug","testing","release"]:
btypeList.pop(btypeList.index(item))
btypeList.insert(0,item)
elif item in ["impi","mpich","openmpi"]:
parallelism = "_" + item
elif item in ["stack","heap"]:
memList = [item]
elif item in ["intel","gnu"]:
cstype = item
else:
errorOccurred = True
break
if errorOccurred:
pm.abort( msg = "The object's attribute ``buildMode`` must be of type ``str``." + newline
+ "It is an optional string argument with default value \"release\"." + newline
+ "possible choices are:" + newline
+ newline
+ " \"debug\":" + newline
+ newline
+ " to be used for identifying sources of bug" + newline
+ " and causes of code crash." + newline
+ newline
+ " \"release\":" + newline
+ newline
+ " to be used in all other normal scenarios" + newline
+ " for maximum runtime efficiency." + newline
+ newline
+ "You have entered buildMode = " + str(self.buildMode)
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
#### verify inputFile
if inputFile is not None and not isinstance(inputFile,str):
pm.abort( msg = "The input argument ``inputFile`` must be of type str." + newline
+ "It is an optional string input representing the path to" + newline
+ "an external input namelist of simulation specifications." + newline
+ "USE THIS OPTIONAL ARGUMENT WITH CAUTION AND" + newline
+ "ONLY IF YOU KNOW WHAT YOU ARE DOING." + newline
+ "Specifying this option will cause the ParaMonte sampler " + newline
+ "to ignore all other simulation specifications set by " + newline
+ "the user via sampler's instance ``spec`` attributes." + newline
+ "You have entered inputFile = " + str(inputFile)
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
inputFileVec_pntr, inputFileLen = self._getInputFile(inputFile)
#if len(sys.argv)>1:
# if sys.argv[1]=="p":
# pm.note( msg = Running sampler in parallel mode...
# , methodName = self._methodName
# )
# print("\nRunning sampler in parallel mode..." + newline)
# libName += "_mpi"
#else:
# print("\nRunning ParaMonte sampler in serial mode..." + newline)
#try:
# from mpi4py import MPI
# comm = MPI.COMM_WORLD
# libName += "_mpi"
# if comm.size==1:
# print("\nRunning ParaMonte sampler in serial mode..." + newline)
# if MPI.Is_initialized():
# print("Hello")
# MPI.Finalize()
# elif comm.rank==0:
# print("\nRunning ParaMonte sampler in parallel mode on {} processes..." + newline.format(comm.size))
# comm.barrier()
#except ImportError:
# print("\nImportError occurred..." + newline)
# print("\nRunning ParaMonte sampler in serial mode..." + newline)
sys.stdout.flush()
#if pm.platform.isLinux:
# from _pmreqs import getLocalInstallDir
# localInstallDir = getLocalInstallDir()
#
# if localInstallDir.gnu.root is not None:
# for object in os.scandir(localInstallDir.gnu.root):
# if object.is_dir() and ("lib" in object.name) and object not in os.environ["LD_LIBRARY_PATH"]:
# os.environ["LD_LIBRARY_PATH"] = object.path + os.pathsep + os.environ["LD_LIBRARY_PATH"]
# if localInstallDir.mpi.root is not None:
# if localInstallDir.mpi.bin is not None:
# if localInstallDir.mpi.bin not in os.environ["PATH"]: os.environ["PATH"] = localInstallDir.mpi.bin + os.pathsep + os.environ["PATH"]
# for object in os.scandir(localInstallDir.mpi.root):
# if object.is_dir() and ("lib" in object.name):
# os.environ["LD_LIBRARY_PATH"] = object.path + os.pathsep + os.environ["LD_LIBRARY_PATH"]
# if localInstallDir.mpi.lib is not None: os.environ["LD_LIBRARY_PATH"] = localInstallDir.mpi.lib + os.pathsep + os.environ["LD_LIBRARY_PATH"]
#### determine the mpi library brand. @todo: This could be later moved to pmreqs as it does not need to be executed every time.
if parallelism is None:
if self.mpiEnabled:
import subprocess
cmdout = subprocess.getoutput("mpiexec --version").lower()
if "intel" in cmdout:
parallelism = "_impi"
elif "hydra" in cmdout or "mpich" in cmdout:
parallelism = "_mpich"
elif "openrte" in cmdout or "open-mpi" in cmdout or "openmpi" in cmdout:
parallelism = "_openmpi"
else: # assume defaults
if self.platform.isWin32 or self.platform.isLinux:
parallelism = "_impi"
elif self.platform.isMacOS:
parallelism = "_openmpi"
else:
parallelism = ""
pm.note( msg = "Running the " + self._methodName + " sampler in serial mode..." + newline
+ "To run the " + self._methodName + " sampler in parallel mode visit:" + newline
+ newline
+ " " + pm.website.home.url + newline
+ newline
+ "If you are using Jupyter notebook, check the Jupyter's " + newline
+ "terminal window for realtime simulation progress and report."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
# import ParaMonte dll define result (None) AND argument (pointer to a c function) type
pmcsList = ["intel","gnu"]
if cstype is None:
if parallelism=="_impi":
cstype = "intel"
else:
cstype = "gnu"
else:
pmcsList.pop(pmcsList.index(cstype))
pmcsList.insert(0,cstype)
libNameSuffix = { "windows" : ".dll"
, "cygwin" : ".dll"
, "mingw" : ".dll"
, "linux" : ".so"
, "darwin" : ".dylib"
}.get(pm.platform.osname, ".so")
libPath = None
libFound = False
libNamePrefix = "libparamonte_python_" + pm.platform.osname.lower() + "_" + pm.platform.arch + "_"
from ctypes.util import find_library
for btype in btypeList:
for pmcs in pmcsList:
#### Build the library name
for mem in memList:
libName = libNamePrefix + pmcs + "_" + btype + "_shared_" + mem + parallelism + libNameSuffix
libPath = find_library(libName)
if libPath is None: libPath = os.path.join( pm.path.lib[pm.platform.arch][pmcs], libName )
libFound = os.path.isfile(libPath)
if libFound: break
if libFound: break
# exist the loop if the library has been found
if libFound:
break
#else:
# if self.reportEnabled:
# pm.warn( msg = "The ParaMonte shared library for the requested build mode " + btype + " not found." + newline
# + "Searching for the ParaMonte shared library in other build modes..."
# , methodName = self._methodName
# , marginTop = 1
# , marginBot = 1
# )
# #libName = libName.replace(btype,mode)
# #btype = mode
if pm.platform.isWin32:
from _pmreqs import buildInstructionNoteWindows
buildInstructionNote = buildInstructionNoteWindows
else:
from _pmreqs import buildInstructionNoteUnix
buildInstructionNote = newline + newline + buildInstructionNoteUnix
if not libFound:
if self.mpiEnabled:
parallelMsg = ("This happens frequently with parallel simulations and the " + newline
+ "most likely reason is that the user did NOT carefully follow " + newline
+ "the ParaMonte instructions to successfully install and define " + newline
+ "the variables of the MPI runtime library on their system. " + newline
+ "To learn these about these instructions, type the following " + newline
+ "in your Python session, " + newline
+ newline
+ " import paramonte as pm" + newline
+ " pm.verify()" + newline
+ newline
+ "Then, carefully follow the instructions provided to define " + newline
+ "the MPI runtime variables in your current Python session. " + newline
+ "If the error still persists, please report this issue at: " + newline
)
else:
parallelMsg = "Please report this issue at:" + newline
pm.abort( msg = "Exhausted all possible ParaMonte shared library search" + newline
+ "names but could not find any compatible library." + newline
#+ "Last search:" + newline
#+ newline
#+ " " + libPath + newline
#+ newline
+ "It appears your ParaMonte library is missing some files. " + newline
+ parallelMsg
+ newline
+ " " + pm.website.github.issues.url + newline
+ newline
+ "Visit," + newline
+ newline
+ " " + pm.website.home.url + newline
+ newline
+ "for instructions on how to build the ParaMonte library" + newline
+ "object files on your system."
+ buildInstructionNote
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
# define ctypes wrapper function, with the proper result and argument types
_getLogFuncRaw_proc = ct.CFUNCTYPE ( ct.c_double # function result
#, ct.POINTER(ct.c_int32) # ndim
, ct.c_int32 # ndim
, ct.POINTER(ct.c_double) # point
)
getLogFuncRaw_pntr = _getLogFuncRaw_proc(getLogFuncRaw)
try:
pmdll = ct.CDLL(libPath)
except Exception as e:
import logging
logger = logging.Logger("catch_all")
logger.error(e, exc_info=True)
pm.abort( msg = "Failed to load the required ParaMonte shared library. " + newline
+ "This is either due to the incompatibility of the DLL with your " + newline
+ "platform or due to missing some required dependent libraries. " + newline
+ "In either case, you can likely resolve this error by building. " + newline
+ "the required ParaMonte shared libraries on your system. " + newline
+ newline
+ "Visit," + newline
+ newline
+ " " + pm.website.home.url + newline
+ newline
+ "for instructions to build the ParaMonte library on your system. " + newline
+ newline
+ "Please report this issue at: " + newline
+ newline
+ " " + pm.website.github.issues.url
+ buildInstructionNote
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
pmdll.runParaDRAM.restype = ct.c_int32
#pmdll.runParaDRAM.restype = None
#pmdll.runParaDRAM.argtypes = [ ct.POINTER(ct.c_int32) # ndim
pmdll.runParaDRAM.argtypes = [ ct.c_int32 # ndim
, _getLogFuncRaw_proc # procedure
, ct.POINTER(ct.c_char) # inputFile byte object
, ct.c_int32 # lenInpuFile
#, ct.POINTER(ct.c_size_t) # lenInpuFile
, ]
#def getLogFuncRawWrapper(ndim_pntr,point): return getLogFuncRaw(ndim[0],point)
# construct procedure pointer
#def getLogFuncRawWrapper(ndim,point): return getLogFuncRaw(np.array(point[0:ndim]))
#getLogFuncRaw_pntr = _getLogFuncRaw_proc(getLogFuncRawWrapper)
# construct ndim pointer
#ndim_pntr = ct.byref(ct.c_int32(ndim))
# call ParaMonte
#pmdll.runParaDRAM ( ndim_pntr
#pmdll.runParaDRAM ( ct.c_int32(ndim)
if self._method.isParaDRAM:
errFlag = pmdll.runParaDRAM ( ct.c_int32(ndim)
, getLogFuncRaw_pntr
, inputFileVec_pntr
, ct.c_int32(inputFileLen)
#, inputFileLen_pntr
)
if errFlag!=0:
# first check for old existing files:
existingFileList = []
outputFileName = os.path.abspath(self.spec.outputFileName)
if not os.path.isdir(outputFileName):
import glob
existingFileList = glob.glob(outputFileName+"*")
if self._method.isParaDRAM and len(existingFileList)>1:
existingSimulationMsg = ( "It appears that an old " + self._methodName + " simulation with " + newline
+ "the same output file names exists in the specified path:" + newline
+ newline
+ newline.join(existingFileList)
+ newline + newline
+ "Keep in mind that old simulation files CANNOT BE OVERWRITTEN " + newline
+ "and attempting to do so will cause the new simulation to crash. " + newline
+ "If this is the case, specify a new filename prefix for the simulation " + newline
+ "output files or set it to `None` in the simulation's input specifications " + newline
+ "so that the sampler can automatically generate unique output " + newline
+ "filenames for your simulation."
)
else:
existingSimulationMsg = ""
pm.abort( msg = "The simulation failed. For more information, checkout the " + newline
+ "simulation output error message on your your Bash / Python " + newline
+ "terminal or command-prompt, also at the end of the output report " + newline
+ "file, if it has been generated:" + newline
+ newline
+ " " + outputFileName + "_report.txt" + newline
+ newline
+ existingSimulationMsg
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
#def isLoaded(libPath):
# abslibPath =
# return os.system("lsof -p {} | grep {} > /dev/null".format( os.getpid(), os.path.abspath(libPath) )) == 0
#def dlclose(libdll): libdll.dlclose(libdll._handle)
if pm.platform.isWin32:
handle = ct.windll.kernel32.LoadLibraryA(libPath)
ct.windll.kernel32.FreeLibrary(handle)
else:
#while isLoaded(libPath):
# dlclose(pmdll._handle)
try:
#ct.dlclose(pmdll._handle)
_dlclose_func = ct.cdll.LoadLibrary('').dlclose
_dlclose_func.argtypes = [ct.c_void_p]
_dlclose_func(pmdll._handle)
del pmdll
except:
if self.reportEnabled:
pm.warn ( msg = "Failed to properly close the ParaMonte shared library file. " + newline
+ "This should not cause any major problems, unless you intend to " + newline
+ "run a new ParaMonte simulation, in which case, you may want to " + newline
+ "exit and re-enter your Python environment."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
if self.reportEnabled:
pm.note( msg = "To read the generated output files, try:" + newline
+ newline
+ " " + self._objectName + ".readReport() # to read the summary report from the output report file." + newline
+ " " + self._objectName + ".readSample() # to read the final i.i.d. sample from the output sample file." + newline
+ " " + self._objectName + ".readChain() # to read the uniquely-accepted points from the output chain file." + newline
+ " " + self._objectName + ".readMarkovChain() # to read the Markov Chain. NOT recommended for very large chains." + newline
+ " " + self._objectName + ".readRestart() # to read the contents of an ASCII-format output restart file." + newline
+ " " + self._objectName + ".readProgress() # to read the contents of an output progress file." + newline
+ newline
+ "where you should replace `" + self._objectName + "` with your " + self._methodName + " sampler's object name." + newline
+ "For more information and examples on the usage, visit:" + newline
+ newline
+ " " + pm.website.home.url
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
return None
################################################################################################################################
#### _getInputFile()
################################################################################################################################
def _getInputFile(self, inputFile):
if inputFile is None:
########################################################################################################################
#### begin namelist generation from arguments
########################################################################################################################
nameList = ""
# setup outputFileName if it is None
if self.spec.outputFileName is None:
self.spec.outputFileName = os.path.join( os.getcwd() , SpecBase.genOutputFileName(self._methodName) )
else:
if self.spec.outputFileName[-1] == "\\" or self.spec.outputFileName[-1] == "/":
self.spec.outputFileName = os.path.join ( os.path.abspath( self.spec.outputFileName ) , SpecBase.genOutputFileName(self._methodName) )
# ParaMonte variables
if self.spec.sampleSize is not None: nameList += SpecBase.sampleSize (self.spec.sampleSize )
if self.spec.randomSeed is not None: nameList += SpecBase.randomSeed (self.spec.randomSeed )
if self.spec.description is not None: nameList += SpecBase.description (self.spec.description )
if self.spec.outputFileName is not None: nameList += SpecBase.outputFileName (self.spec.outputFileName )
if self.spec.outputDelimiter is not None: nameList += SpecBase.outputDelimiter (self.spec.outputDelimiter )
if self.spec.chainFileFormat is not None: nameList += SpecBase.chainFileFormat (self.spec.chainFileFormat )
if self.spec.variableNameList is not None: nameList += SpecBase.variableNameList (self.spec.variableNameList )
if self.spec.restartFileFormat is not None: nameList += SpecBase.restartFileFormat (self.spec.restartFileFormat )
if self.spec.outputColumnWidth is not None: nameList += SpecBase.outputColumnWidth (self.spec.outputColumnWidth )
if self.spec.overwriteRequested is not None: nameList += SpecBase.overwriteRequested (self.spec.overwriteRequested )
if self.spec.outputRealPrecision is not None: nameList += SpecBase.outputRealPrecision (self.spec.outputRealPrecision )
if self.spec.silentModeRequested is not None: nameList += SpecBase.silentModeRequested (self.spec.silentModeRequested )
if self.spec.domainLowerLimitVec is not None: nameList += SpecBase.domainLowerLimitVec (self.spec.domainLowerLimitVec )
if self.spec.domainUpperLimitVec is not None: nameList += SpecBase.domainUpperLimitVec (self.spec.domainUpperLimitVec )
if self.spec.parallelizationModel is not None: nameList += SpecBase.parallelizationModel (self.spec.parallelizationModel )
if self.spec.progressReportPeriod is not None: nameList += SpecBase.progressReportPeriod (self.spec.progressReportPeriod )
if self.spec.targetAcceptanceRate is not None: nameList += SpecBase.targetAcceptanceRate (self.spec.targetAcceptanceRate )
if self.spec.mpiFinalizeRequested is not None: nameList += SpecBase.mpiFinalizeRequested (self.spec.mpiFinalizeRequested )
if self.spec.maxNumDomainCheckToWarn is not None: nameList += SpecBase.maxNumDomainCheckToWarn (self.spec.maxNumDomainCheckToWarn )
if self.spec.maxNumDomainCheckToStop is not None: nameList += SpecBase.maxNumDomainCheckToStop (self.spec.maxNumDomainCheckToStop )
if self._method.isParaDRAM:
# ParaMCMC variables
if self.spec.chainSize is not None: nameList += SpecMCMC.chainSize (self.spec.chainSize )
if self.spec.scaleFactor is not None: nameList += SpecMCMC.scaleFactor (self.spec.scaleFactor )
if self.spec.startPointVec is not None: nameList += SpecMCMC.startPointVec (self.spec.startPointVec )
if self.spec.proposalModel is not None: nameList += SpecMCMC.proposalModel (self.spec.proposalModel )
if self.spec.proposalStartCovMat is not None: nameList += SpecMCMC.proposalStartCovMat (self.spec.proposalStartCovMat )
if self.spec.proposalStartCorMat is not None: nameList += SpecMCMC.proposalStartCorMat (self.spec.proposalStartCorMat )
if self.spec.proposalStartStdVec is not None: nameList += SpecMCMC.proposalStartStdVec (self.spec.proposalStartStdVec )
if self.spec.sampleRefinementCount is not None: nameList += SpecMCMC.sampleRefinementCount (self.spec.sampleRefinementCount )
if self.spec.sampleRefinementMethod is not None: nameList += SpecMCMC.sampleRefinementMethod (self.spec.sampleRefinementMethod )
if self.spec.randomStartPointRequested is not None: nameList += SpecMCMC.randomStartPointRequested (self.spec.randomStartPointRequested )
if self.spec.randomStartPointDomainLowerLimitVec is not None: nameList += SpecMCMC.randomStartPointDomainLowerLimitVec (self.spec.randomStartPointDomainLowerLimitVec)
if self.spec.randomStartPointDomainUpperLimitVec is not None: nameList += SpecMCMC.randomStartPointDomainUpperLimitVec (self.spec.randomStartPointDomainUpperLimitVec)
# ParaDRAM variables
if self.spec.adaptiveUpdateCount is not None: nameList += SpecDRAM.adaptiveUpdateCount (self.spec.adaptiveUpdateCount )
if self.spec.adaptiveUpdatePeriod is not None: nameList += SpecDRAM.adaptiveUpdatePeriod (self.spec.adaptiveUpdatePeriod )
if self.spec.greedyAdaptationCount is not None: nameList += SpecDRAM.greedyAdaptationCount (self.spec.greedyAdaptationCount )
if self.spec.delayedRejectionCount is not None: nameList += SpecDRAM.delayedRejectionCount (self.spec.delayedRejectionCount )
if self.spec.burninAdaptationMeasure is not None: nameList += SpecDRAM.burninAdaptationMeasure (self.spec.burninAdaptationMeasure )
if self.spec.delayedRejectionScaleFactorVec is not None: nameList += SpecDRAM.delayedRejectionScaleFactorVec (self.spec.delayedRejectionScaleFactorVec )
nameList = "&" + self._methodName + " " + nameList + SpecBase.interfaceType() + SpecBase.systemInfoFilePath(pm.platform.systemInfoFilePath) + "/"
############################################################################################################################
#### end namelist generation from arguments
############################################################################################################################
inputFileVec_pntr = nameList.encode("utf-8") # create byte-object from the internal input file
else:
if not self.mpiEnabled:
pm.warn ( msg = "Input namelist file is given by the user. " + newline
+ "All simulation specifications will be read from the input file."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
inputFileVec_pntr = inputFile.encode("utf-8") # create byte-object from the external input file
inputFileLen = len(inputFileVec_pntr) # byte-object length
#inputFileLen_pntr = ct.byref( ct.c_size_t( len(inputFileVec_pntr) ) ) # pointer to byte-object length
inputFileVec_pntr = ct.c_char_p( inputFileVec_pntr ) # pointer to byte-object
return inputFileVec_pntr, inputFileLen #_pntr
################################################################################################################################
#### _setFileToRead()
################################################################################################################################
def _setFileToRead(self, file, fileType, fileSuffix):
if self.spec.outputFileName is None:
file = os.getcwd()
if self.reportEnabled:
pm.warn ( msg = "The ``file`` is neither given as input to ``read" + fileType.capitalize() + "()``" + newline
+ "nor set as a simulation specification of the " + self._methodName + " object. " + newline
+ "This information is essential, otherwise how could the output files be found?" + newline
+ "All that is needed is the unique name (including path) of the simulation name " + newline
+ "shared among its output files or simply, the path to the specific " + fileSuffix + newline
+ " file to be read. For now, the " + self._methodName + " sampler will search " + newline
+ "the current working directory for simulation output files that match the " + newline
+ "filename pattern of " + fileSuffix + " files."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
else:
file = self.spec.outputFileName
return file
################################################################################################################################
#### _setDelimiterToRead()
################################################################################################################################
def _setDelimiterToRead(self, delimiter, fileType, fileSuffix):
if self.spec.outputDelimiter is None:
delimiter = ","
if self.reportEnabled:
pm.warn ( msg = "The ``delimiter`` is neither given as input to ``read" + fileType.capitalize() + "()``" + newline
+ "nor set as a simulation specification of the " + self._methodName + " object. " + newline
+ "This information is essential, otherwise how could the output files be parsed?" + newline
+ "For now, the " + self._methodName + " sampler will assume a comma-separated " + newline
+ "file format for the contents of the " + fileSuffix + " file(s) to be parsed."
, methodName = self._methodName
, marginTop = 1
, marginBot = 1
)
else:
delimiter = self.spec.outputDelimiter
return delimiter
################################################################################################################################
#### readTabular()
################################################################################################################################
def _readTabular( self
, file : str
, fileType : str
, delimiter : str
, parseContents : bool
, renabled : bool
) -> tp.List[TabularFileContents] :
"""
Read the contents of the file(s) whose path is given by the input argument ``file``.
This function is not to be directly accessible to and callable by the users
of the ParaMonte library.
**Parameters**
file
A string representing the path to the tabular file with
the default value of ``None``.
The path only needs to uniquely identify the simulation
to which the tabular file belongs. For example, specifying
``"./mydir/mysim"`` as input will lead to a search for a
file that begins with ``"mysim"`` and ends with the tabular file
name's prefix, such as, ``"_sample.txt"``, inside the directory
``"./mydir/"``. If there are multiple files with such name,
then all of them will be read and returned as a list.
The path can be also a world wide web address.
If this input argument is not provided by the user, the
value of the object attribute ``outputFileName`` will be
used instead. At least one of the two mentioned routes
must provide the path to the tabular file otherwise,
this method will break by calling ``sys.exit()``.
fileType
A string containing the type of the file to be parsed.
Current options include but are not limited to:
``sample``, ``chain``, ``markovChain``, ``progress``
delimiter
An input string representing the delimiter used in the
output tabular file. If it is not provided as input argument,
the value of the corresponding object attribute outputDelimiter
will be used instead. If none of the two are available,
the default comma delimiter "," will be assumed and used.
parseContents
If set to True, the contents of the file will be parsed and
stored in a component of the object named ``contents``.
The default value is ``True``.
renabled
If set to ``False``, the contents of the file(s) will be
stored as a list in a (new) component of the object with a
name that ends with the prefix ``List``. Otherwise, ``None``
will be the return value of the method. If set to ``True``,
the reverse will done. The default value is ``False``.
**Returns**
List
A Python list of ``TabularFileContents`` objects, each
of which corresponds to the contents of a unique restart
file. The contents of each object is dependent on the
type of the file that has been parsed.
"""
if fileType=="sample":
fileSuffix = "sample"
elif fileType=="chain" or fileType=="markovChain":
fileSuffix = "chain"
elif fileType=="progress":
fileSuffix = "progress"
else:
fileSuffix = None
pm.abort( msg = "Internal error occurred. The input fileType is not recognized." + newline
+ "Please report this error at:" + newline
+ newline