results.py 15.3 KB
Newer Older
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
1
2
from abc import ABC, abstractmethod
import copy
3
4
import datetime
import os
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
5

6
7
8
import h5py
import numpy as np

9
10
from fluegg.resultsrecorder import QuantileResultsRecorder

11

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
12
class Results(ABC):
13

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
14
    def __init__(self, results):
15

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
16
17
        self._configuration = results.configuration()
        self._domain_length = results.domain_length()
18
        self._time = results.time(slice(None))
19

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
20
21
    def configuration(self):
        """Returns the configuration dictionary
22

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
23
24
25
        Returns
        -------
        dict
26

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
        """

        return copy.deepcopy(self._configuration)

    def domain_length(self):
        """Returns the length of the computational domain

        Returns
        -------
        float

        """

        return self._domain_length
41

42
43
44
45
46
47
48
49
    def frac_below_depth(self, time, depth):
        """Fraction of particles below given depth at a time

        Parameters
        ----------
        time : float
            Simulation time, in seconds
        depth : float
50
            Fractional position along the z-axis, where 0 is the
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
            water surface and 1 is the bottom of the channel.
        bins : int or array_like, optional
            Number of bins or array of bin edges. The default is 20.

        Returns
        -------
        float
            Fraction of eggs below position

        """
        # calculate quantiles of every particle location
        positions, quantiles = self.position_cfrac(time, 2)
        # make positions positive, so 0 is the surface and 1 is the bottom
        positions = np.abs(positions)
        # find index of position closest to desired depth
        quantile_index = (np.abs(positions - depth)).argmin()
        # use found index to get quantile of depth position
        fraction_below = quantiles[quantile_index]

        return fraction_below

72
73
74
75
76
77
78
79
80
81
82
83
84
85
    @classmethod
    def from_hdf(cls, file_path):
        """Initialize a results instance from an HDF file

        Parameters
        ----------
        file_path : str
            Path to HDF file containing results data

        Returns
        -------
        QuantileResults

        """
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
86
87
88
        members = cls.__dict__['_members']
        attrib = {}

89
        with h5py.File(file_path, 'r') as f:
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            for k in members:
                attrib[k] = f.get(k[1:])[()]

        if '_configuration' in members:
            configuration = attrib['_configuration']
            config_split = configuration.split(", '")
            configuration = []
            for pair in config_split:
                pair = pair.replace('{', '')
                pair = pair.replace('}', '')
                pair = pair.replace('"', '')
                pair = pair.replace("'", '')
                configuration.append(pair.split(': '))
            configuration = dict(configuration)
            attrib['_configuration'] = configuration
105
106

        results = cls.__new__(cls)
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
107
108
        for k, v in attrib.items():
            setattr(results, k, v)
109
110
111

        return results

112
113
114
115
116
117
118
119
120
121
    def particle_count(self):
        """Returns the number of particles.

        Returns
        -------
        int
            Number of particles
        """
        return int(self._configuration["num_eggs"])

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
122
123
124
125
126
127
    @abstractmethod
    def position_cfrac(self, time, position_axis=0):

        pass

    def position_frac(self, time, position_axis=0, bins=20):
128
129
        """Fraction of particles within bins defined by position
        at a given time
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
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
        Parameters
        ----------
        time : float
            Simulation time, in seconds
        position_axis : {0, 1, 2}, optional
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.
        bins : int or array_like, optional
            Number of bins or array of bin edges. The default is 20.

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            edges, frac

        """

        pos, cfrac = self.position_cfrac(time, position_axis)

        if np.isscalar(bins):
            edges = np.linspace(pos.min(), pos.max(), bins + 1)
        else:
            edges = np.array(bins)

        interp_p = np.interp(edges, pos, cfrac)
        frac = np.diff(interp_p)

        return edges, frac
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
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

    @abstractmethod
    def quantile(self, q, position_axis=0):

        pass

    def time(self, index):
        """Simulation time

        Parameters
        ----------
        index : int or slice
            Index of time to return

        Returns
        -------
        float
            Simulation time, in seconds

        """

        return self._time[index]

    @abstractmethod
    def time_cfrac(self, position, position_axis=0):

        pass

187
    def time_frac(self, position, bin_width, position_axis=0):
188
        """Fraction of particles within a position bin through time
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
189

190
191
192
        Parameters
        ----------
        position : float
193
            Fractional position in simulation domain
194
195
196
197
198
199
200
201
202
203
        bin_width : float
            Width of position bin, in meters

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            time, frac_in_bin

        """

204
205
        pos_lo = position - bin_width / 2 / self.domain_length()
        pos_hi = position + bin_width / 2 / self.domain_length()
206

207
208
        _, cfrac_lo = self.time_cfrac(pos_lo, position_axis=position_axis)
        _, cfrac_hi = self.time_cfrac(pos_hi, position_axis=position_axis)
209
210
211
212

        frac_in_bin = cfrac_lo - cfrac_hi

        return self._time.copy(), frac_in_bin
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
213
214
215
216
217
218
219
220
221
222
223

    def to_hdf(self, file_path):
        """Store results data in an HDF file

        Parameters
        ----------
        file_path : str
            Path to HDF file

        """

224
225
226
227
228
        if os.path.exists(file_path):
            now = datetime.datetime.now()
            date_string = now.strftime('%Y-%m-%d-%H-%M-%S')
            file_path = file_path[:-3] + str(date_string) + file_path[-3:]

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
229
        with h5py.File(file_path, 'w') as f:
230
            f.create_dataset('type', data=self.__class__.__name__)
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
231
232
233
234
235
236
237
238
            for k in self.__class__.__dict__['_members']:
                data = self.__dict__[k]
                if isinstance(data, dict):
                    data = str(data)
                f.create_dataset(k[1:], data=data)


class FullResults(Results):
239
240
241
242
    """Simulation results stored with full information

    Parameters
    ----------
243
    results : FullResultsRecorder
244
245

    """
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
246
247
248
249
250
251

    _members = (
        '_positions',
        '_depth',
        '_width',
        '_domain_length',
252
253
        '_configuration',
        '_time')
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
254
255
256

    def __init__(self, results):

257
258
        super().__init__(results)

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
259
260
261
262
        self._positions = results.positions()
        self._depth = results.depth()
        self._width = results.width()

263
264
265
    def _normalize_axis(self, position_axis):

        if position_axis == 0:
266
267
            positions = \
                self._positions[:, :, position_axis] / self._domain_length
268
        elif position_axis == 1:
269
270
            positions = \
                self._positions[:, :, position_axis] / self._width + 0.5
271
        elif position_axis == 2:
272
273
274
            positions = \
                self._positions[:, :, position_axis] / self._depth

275
276
        return positions

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
    def in_domain(self, time):
        """Returns a results instance containing particles that are
        in the simulation domain at a given time

        Parameters
        ----------
        time : float
            Simulation time, in seconds. `time` must be finite.

        Returns
        -------
        Full Results or None
            Returns None if no particles are in the domain at `time`

        """

        if not np.isfinite(time):
            raise ValueError("time must be a finite value")

        positions_at_time = np.apply_along_axis(
            lambda p: np.interp(
                time,
                self._time,
                p),
            0,
            self._positions)

        particles_in_domain = positions_at_time[:, 0] <= self._domain_length

306
307
308
        new_config = self.configuration()
        new_config['num_eggs'] = sum(x for x in particles_in_domain)

309
310
311
312
313
314
315
        if np.any(particles_in_domain):
            cls = self.__class__
            res = cls.__new__(cls)
            res._positions = self._positions[:, particles_in_domain, :]
            res._depth = self._depth[:, particles_in_domain]
            res._width = self._width[:, particles_in_domain]
            res._domain_length = self._domain_length
316
            res._configuration = new_config
317
318
319
320
321
322
            res._time = self._time.copy()
        else:
            res = None

        return res

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    def positions(self, normalize=()):
        """Returns particle position array

        Parameters
        ----------
        normalize : tuple of int, optional
            Normalize position array axes (the default is an empty,
            tuple, which doesn't normalize any axes).

        Returns
        -------
        numpy.ndarray
            Position array

        """

        axes = {0, 1, 2}

        # keep these axes in absolute length
        absolute = axes.difference(normalize)

        positions = np.zeros_like(self._positions)

        for a in normalize:
347
            positions[:, :, a] = self._normalize_axis(a)
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
348
349
350
351
352
353

        for a in absolute:
            positions[:, :, a] = self._positions[:, :, a]

        return positions

354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    def position_cfrac(self, time, position_axis=0):
        """Cumulative fraction of particles past positions at a
        given time

        Paramters
        ---------
        time : float
            Simulation time, in seconds
        position_axis : {0, 1, 2}, optional
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            position, cfrac

        """

373
        particle_positions = self._normalize_axis(position_axis)
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

        positions = np.apply_along_axis(
            lambda p: np.interp(
                time,
                self._time,
                p,
                left=np.nan,
                right=np.nan),
            0,
            particle_positions)

        position = np.sort(positions)
        n_particles = position.shape[0]
        cfrac = np.arange(1, n_particles + 1) / n_particles

        return position, cfrac

    def quantile(self, q, position_axis=0):
392
        """Returns position quantiles over time
393

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
        Parameters
        ----------
        q : array_like of float
            Quantile or sequence of quantiles to compute
        position_axis : {0, 1, 2}, optional
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
        numpy.ndarray

        """

        particle_positions = self._normalize_axis(position_axis)

        quantiles = np.quantile(particle_positions, q, axis=1)

        return self._time.copy(), quantiles
413
414

    def time_cfrac(self, position, position_axis=0):
415
        """Cumulative fraction of particles with time past a given position
416

417
418
419
420
421
422
423
424
425
426
427
428
429
430
        Parameters
        ----------
        position : float
            Fractional position of simulation domain
        position_axis : {0, 1, 2}, optional
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            time, cumulative_fraction

        """
431
        particle_positions = self._normalize_axis(position_axis)
432
433
434
435
436
437
438
439
440
441

        particles_through_time = np.greater(
            particle_positions,
            position).sum(
            axis=1)

        n_particles = particle_positions.shape[1]
        cfrac = particles_through_time / n_particles

        return self._time.copy(), cfrac
442

Domanski, Marian M.'s avatar
Domanski, Marian M. committed
443
444
445
446
447
448

class QuantileResults(Results):
    """Simulation results stored as quantiles to optimize memory

    Parameters
    ----------
449
    results : ResultsRecorder,
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463

    """

    _members = (
        '_configuration',
        '_time',
        '_positions',
        '_quantiles',
        '_domain_length')

    def __init__(self, results):

        super().__init__(results)

464
465
466
467
468
469
470
471
472
473
        # if an AttributeError is raised, assume results is not a
        # QuantileResultsRecorder
        try:
            self._quantiles = results.quantiles()
            self._positions = results.positions()
        except AttributeError:
            # use same quantiles as QuantileResultsRecorder
            self._quantiles = QuantileResultsRecorder.quantiles()
            positions = results.positions((0, 1, 2))
            self._positions = np.quantile(positions, self._quantiles, axis=1)
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
474

475
476
477
478
479
480
481
482
    def position_cfrac(self, time, position_axis=0):
        """Cumulative fraction of particles past positions at a
        given time

        Paramters
        ---------
        time : float
            Simulation time, in seconds
483
        position_axis : {0, 1, 2}, optional
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
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            position, cfrac

        """

        time_axis = 1

        position = np.apply_along_axis(
            lambda p: np.interp(
                time,
                self._time,
                p,
                left=np.nan,
                right=np.nan),
            time_axis,
            self._positions[:, :, position_axis])

        return position, self._quantiles.copy()

    def quantile(self, q, position_axis=0):
        """Returns position quantiles over time

        Parameters
        ----------
        q : array_like of float
            Quantile or sequence of quantiles to compute
        position_axis : {0, 1, 2}, optional
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
Domanski, Marian M.'s avatar
Domanski, Marian M. committed
521
522
        numpy.ndarray, numpy.ndarray
            time, quantiles
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

        """

        quantile_axis = 0
        q = np.array(q)
        q_vs_time = np.apply_along_axis(
            lambda p: np.interp(
                q,
                self._quantiles,
                p,
                left=np.nan,
                right=np.nan),
            quantile_axis,
            self._positions[:, :, position_axis])

        return self._time.copy(), q_vs_time

    def time_cfrac(self, position, position_axis=0):
        """Cumulative fraction of particles with time past a given position

        Parameters
        ----------
        position : float
546
547
            Fractional position of simulation domain
        position_axis : {0, 1, 2}, optional
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
            Position axis of simulation domain. 0 for x, 1 for y,
            2 for z. The default is 0.

        Returns
        -------
        numpy.ndarray, numpy.ndarray
            time, cumulative_fraction

        """

        quantile_axis = 0

        q_through_time = np.apply_along_axis(
            lambda pq: np.interp(
                position,
                pq,
                self._quantiles,
                left=0,
                right=1),
            quantile_axis,
            self._positions[:, :, position_axis])
        cfrac = 1 - q_through_time

        return self._time.copy(), cfrac
572
573
574
575
576
577
578
579
580
581
582


def load_from_hdf(file_path):
    with h5py.File(file_path, 'r') as f:
        set_type = f.get('type')[()]
        if set_type == "FullResults":
            return FullResults.from_hdf(file_path)
        elif set_type == "QuantileResults":
            return QuantileResults.from_hdf(file_path)
        else:
            raise ValueError("Invalid results file type: {}".format(set_type))