File: test_surface.py

package info (click to toggle)
mystic 0.4.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,656 kB
  • sloc: python: 40,894; makefile: 33; sh: 9
file content (172 lines) | stat: -rw-r--r-- 6,248 bytes parent folder | download
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
#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2010-2016 California Institute of Technology.
# Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
# License: 3-clause BSD.  The full license text is available at:
#  - https://github.com/uqfoundation/mystic/blob/master/LICENSE
"""
an example of using an interpolator within a surface object
""" #XXX: use interpolator, plotter, and sampler (instead of Surface)?

from surface import Surface
import time


if __name__ == '__main__':
    start = time.time()
    """
    from mystic.models import griewangk
    from mystic.termination import NormalizedChangeOverGeneration as NCOG

    stop = NCOG(1e-4)
    bounds = 2*[(-9.5,9.5)]

    self = Surface(griewangk, maxpts=1000)

    # self.doit(bounds, stop)
    step=100; scale=False; shift=False; density=9; kwds={}

    if not self.sampler.traj: self.sampler.UseTrajectories()
    # get trajectories
    self.Sample(bounds, stop)
    # get interpolated function
    self.Interpolate(**kwds)
    # check extrema  #XXX: put _min,_max in Interpolate? (downsampled)
    f = lambda x,z: (z,self.surrogate(*x))
    print("min: {}; min@f: {}".format(*f(*self._min())))
    print("max: {}; max@f: {}".format(*f(*self._max())))
    # plot surface
    self.Plot(step=step, scale=scale, shift=shift, density=density)
    """

    # parallel configuration
    try:
        from pathos.helpers import freeze_support, shutdown
        freeze_support()
        from pathos.pools import ProcessPool as Pool
       #from pathos.pools import ThreadPool as Pool
       #from pathos.pools import ParallelPool as Pool
    except ImportError:
        from mystic.pools import SerialPool as Pool
        shutdown = lambda x=None:None

    _map = Pool().map

    # tools
    from mystic.termination import VTR, ChangeOverGeneration as COG
    from mystic.termination import NormalizedChangeOverGeneration as NCOG
    from mystic.monitors import LoggingMonitor, VerboseMonitor, Monitor
    from klepto.archives import dir_archive

    stop = NCOG(1e-4)
    disp = True # print optimization summary
    monitor = True # use LoggingMonitor (uses much less memory)
    archive = False # save an archive
    all = True # use EvalMonitor (instead of StepMonitor only)

    traj = not monitor # save all trajectories internally, if no logs

    # cost function
    from mystic.models import griewangk as model
    ndim = 2  # model dimensionality
    bounds = ndim * [(-9.5,9.5)] # griewangk

    # the ensemble solvers
    from mystic.solvers import BuckshotSolver, LatticeSolver, SparsitySolver
    # the local solvers
    from mystic.solvers import PowellDirectionalSolver

    sprayer = BuckshotSolver
    seeker = PowellDirectionalSolver
    npts = 25    # number of solvers
    retry = 1    # max consectutive iteration retries without a cache 'miss'
    repeat = 0   # number of times to repeat the search
    tol = 8      # rounding precision
    mem = 1      # cache rounding precision
    size = 0     # max in-memory cache size

    #CUTE: 'configure' monitor and archive if they are desired
    if monitor:
        monitor = LoggingMonitor(1) # montor for all runs
        costmon = LoggingMonitor(1, filename='inv.txt') #XXX: log.txt?
    else:
        monitor = costmon = None
    if archive:
        name = getattr(model,'__name__','model')
        ar_name = '__%s_%sD_cache__' % (name,ndim)
        archive = dir_archive(ar_name, serialized=True, cached=False)
        ar_name = '__%s_%sD_invcache__' % (name,ndim)
        ivcache = dir_archive(ar_name, serialized=True, cached=False)
    else:
        archive = ivcache = None

    from mystic.search import Searcher #XXX: init w/ archive, then UseArchive?
    expts,evals = (None,archive) if all else (archive, None)
    #expts,evals = (archive, None) #XXX: don't override the sample archive
    sampler = Searcher(npts, retry, tol, mem, size, _map, evals, expts, sprayer, seeker, repeat=repeat)
    sampler.Verbose(disp)
    sampler.UseTrajectories(traj)

    ### doit ###
    maxpts = 1000. #10000.
    surface = Surface(model, sampler, maxpts=maxpts, dim=ndim)
    surface.UseMonitor(monitor, costmon)
    surface.UseArchive(archive, ivcache)

    density = 9
    shift = 0
    scale = 0
    step = 200
    args = {
   #'smooth': 0,
    'method': 'thin_plate',
    'extrap': False,
    'arrays': False,
    }
    #surface.doit(bounds, stop, step=step)
   #'multiquadric','inverse','gaussian','linear','cubic','quintic','thin_plate'

    # impose data filter (so X >= 0 and Y >= 0) 
    from mystic.filters import generate_mask, generate_filter
    from mystic.constraints import impose_bounds
    _bounds = impose_bounds((0.0, None))(lambda x:x)
    filter = generate_filter(generate_mask(_bounds, _bounds))
    # from numpy import round as _round
    #############

    # get trajectories
    surface.Sample(bounds, stop, all=all, filter=filter)#, constraints=_round)
    print("TOOK: %s" % (time.time() - start))
#   exit()
    # get interpolated function
    surface.Interpolate(**args)
    # check extrema  #XXX: put _min,_max in Interpolate? (downsampled)
    f = lambda x,z: (z,surface.surrogate(*x))
    print("min: {}; min@f: {}".format(*f(*surface._min())))
    print("max: {}; max@f: {}".format(*f(*surface._max())))
    # shutdown worker pool
    shutdown()
#   print("TOOK: %s" % (time.time() - start))

    # plot interpolated surface
    axes = (0,1)
    vals = () # use remaining minima as the fixed values
    surface.Plot(step=step, scale=scale, shift=shift, density=density, axes=axes, vals=vals)

    """
    try:
        from klepto.archives import file_archive
        archive = file_archive('models.pkl', serialized=True, cached=False)
        archive[model.im_class.__name__.lower()] = surface.surrogate
    except Exception:
        print("serialization failed")
    """
    # some testing of interpolated model
    #import numpy as np
    #actual = np.asarray(surface.z)           # downsample?
    #interp = surface.surrogate(*surface.x.T) # downsample? #NOTE: SLOW
    #print("sum diff squares") #NOTE: is *worse* than with test_searcher.py
    #print("actual and interp: %s" % np.sum((actual - interp)**2))

# EOF