Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

#! python 

#-*- coding: utf-8 -*- 

# 

# Copyright 2015 European Commission (JRC); 

# Licensed under the EUPL (the 'Licence'); 

# You may not use this work except in compliance with the Licence. 

# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl 

""" 

Defines the building-blocks of a "model": 

 

components and assemblies: 

    See :class:`Component`, :class:`FuncComponent` and :class:`Assembly`. 

 

paths and path-mappings (pmods): 

    See :class:`Pmod`, :func:`pmods_from_tuples` and :class:`Pstep`. 

 

TODO 

---- 

 

1. Assembly use ComponentLoader collecting components with: 

 

   - `gatattr()` and 

   - `filter_predicate` default to ``attr.__name__.startswith('cfunc_')``. 

   - enforce a `disable` flag on them. 

 

2. Component/assembly should have a stackable or common cwd? 

 

3. Components should be easy to run without "framework". 

   - `_build()` --> `run()` 

   - pmods on init OR `run()`? 

   - As ContextManager? 

 

4. Imply a default Assembly. 

""" 

 

from __future__ import division, unicode_literals 

 

from abc import ABCMeta, abstractmethod 

import logging 

from pandalone.mappings import Pstep 

 

try: 

    from unittest.mock import MagicMock 

except ImportError: 

    from mock import MagicMock  # @UnusedImport 

 

 

__commit__ = "" 

 

log = logging.getLogger(__name__) 

 

 

name_uniqueizer = None  # TODO: Handle clashes on component-names. 

 

 

class Component(object): 

 

    """ 

    Encapsulates a function and its its inputs/outputs dependencies. 

 

    It should be callable, and when executed it may read/modify 

    the data-tree given as its 1st input. 

 

    An opportunity to fix the internal-state (i.e. inputs/output/name) 

    is when the  :meth:`_build()` is invoked. 

 

    :ivar list _name:    identifier 

    :ivar list _inp:     list/of/paths required on the data-tree (must not overlap with `out`) 

    :ivar list _out:     list/of/paths modified on the data-tree (must not overlap with `inp`) 

 

    Mostly defined through *cfuncs*, which provide for defining a component 

    with a single function with a special signature, see :class:`FuncComponent`. 

    """ 

 

    __metaclass__ = ABCMeta 

 

    def __init__(self, name): 

        if name_uniqueizer: 

            name = name_uniqueizer(name) 

        self._name = name 

        self._inp = None 

        self._out = None 

 

    @abstractmethod 

    def __call__(self, *agrs, **kws): 

        pass 

 

    @abstractmethod 

    def _build(self, pmod=None): 

        """Invoked once before run-time and should apply `pmaps` when given.""" 

        pass 

 

    def _iter_validations(self): 

        """ Yields a msg for each failed validation rule. 

 

        Invoke it after :meth:`_build()` component. 

        """ 

        # TODO: Implement Component's validation. 

 

        if False: 

            yield 

#         expected_attrs = ['name', 'inp', 'out'] 

#         for attr in expected_attrs: 

#             if not hasattr(self, attr): 

#                 yield "`%s` is unset!" % attr 

 

 

class FuncComponent(Component): 

 

    """ 

    Converts a "cfunc" into a component. 

 

    A cfunc is a function that modifies the values-tree with this signature:: 

 

        cfunc_XXXX(comp, vtree) 

 

    where: 

 

    comp: 

        the  :class:`FuncComponent` associated with the cfunc 

 

    vtree: 

        the part of the data-tree involving the values to be modified 

        by the cfunc 

 

    It works also as a utility to developers of a cfuncs, since it is passed 

    as their 1st arg. 

 

    The cfuncs may use :meth:`pinp` and :meth:`pout` when accessing 

    its input and output data-tree values respectively. 

    Note that accessing any of those attributes from outside of cfunc, 

    would result in an error. 

 

    If a cfunc access additional values with "fixed' paths, then it has to 

    manually add those paths into the :attr:`_inp` and :attr:`_out` 

    lists. 

 

 

    Example: 

 

    This would be a fully "relocatable" cfunc:: 

 

        >>> def cfunc_calc_foobar_rate(comp, value_tree): 

        ...     pi = comp.pinp() 

        ...     po = comp.pout() 

        ... 

        ...     df = value_tree.get(pi) 

        ... 

        ...     df[po.Acc] = df[pi.V] / df[pi.T] 

 

    To get the unmodified component-paths, use:: 

 

        >>> comp = FuncComponent(cfunc_calc_foobar_rate) 

        >>> comp._build() 

        >>> assert list(comp._iter_validations()) == [] 

        >>> sorted(comp._inp + comp._out) 

        ['calc_foobar_rate/Acc', 'calc_foobar_rate/T', 'calc_foobar_rate/V'] 

 

    To get the path-modified component-paths, use:: 

 

        >>> from pandalone.mappings import pmods_from_tuples 

 

        >>> pmods = pmods_from_tuples([ 

        ...     ('~.*', '/A/B'), 

        ... ]) 

        >>> comp._build(pmods) 

 

        >>> sorted(comp.pinp()._paths()) 

        ['/A/B/T', '/A/B/V'] 

 

        >>> comp.pout()._paths() 

        ['/A/B/Acc'] 

 

        >>> sorted(comp._inp + comp._out) 

        ['/A/B/Acc', '/A/B/T', '/A/B/V'] 

 

        >>> comp._build(pmods) 

        >>> sorted(comp._inp + comp._out) 

        ['/A/B/Acc', '/A/B/T', '/A/B/V'] 

 

    """ 

 

    def __init__(self, cfunc, name=None): 

        self._cfunc = cfunc 

        if name is None: 

            name = cfunc.__name__ 

            prefix = 'cfunc_' 

            if name.startswith(prefix): 

                name = name[len(prefix):] 

        Component.__init__(self, name=name) 

 

        # The following are initialized in _build(): 

        # self._inp = None 

        # self._out = None 

        # self._pmod = None 

        # self._pinp = None 

        # self._pout = None 

 

    def __call__(self, *args, **kws): 

        self._cfunc(self, *args, **kws) 

 

    def _fetch_all_paths(self, pstep): 

        return pstep._paths() if pstep else [] 

 

    def pinp(self, path=None): 

        """The suggested :class:`Pstep` for cfunc to use to access inputs.""" 

        p = self._pinp 

        if p is None: 

            self._pinp = p = Pstep(path or self._name, 

                                   _proto_or_pmod=self._pmod) 

        return p 

 

    def pout(self, path=None): 

        """The suggested :class:`Pstep` for cfunc to use to access outputs.""" 

        p = self._pout 

        if p is None: 

            self._pout = p = Pstep(path or self._name, 

                                   _proto_or_pmod=self._pmod) 

        return p 

 

    def _build(self, pmod=None): 

        """Extracts inputs/outputs from cfunc. """ 

        vtree = MagicMock() 

        self._inp = [] 

        self._out = [] 

        self._pinp = None 

        self._pout = None 

        self._pmod = pmod 

 

        self._cfunc(self, vtree) 

 

        self._inp.extend(self._fetch_all_paths(self._pinp)) 

        self._out.extend(self._fetch_all_paths(self._pout)) 

 

 

class Assembly(Component):  # TODO: Assembly inherit Component 

 

    """ 

    Example: 

 

        >>> def cfunc_f1(comp, value_tree): 

        ...     comp.pinp().A 

        ...     comp.pout().B 

        >>> def cfunc_f2(comp, value_tree): 

        ...     comp.pinp().B 

        ...     comp.pout().C 

        >>> ass = Assembly(FuncComponent(cfunc) for cfunc in [cfunc_f1, cfunc_f2]) 

        >>> ass._build() 

        >>> assert list(ass._iter_validations()) == [] 

        >>> ass._inp 

        ['f1/A', 'f2/B'] 

        >>> ass._out 

        ['f1/B', 'f2/C'] 

 

        >>> from pandalone.mappings import pmods_from_tuples 

 

        >>> pmod = pmods_from_tuples([ 

        ...     ('~.*',  '/root'), 

        ... ]) 

        >>> ass._build(pmod) 

        >>> sorted(ass._inp + ass._out) 

        ['/root/A', '/root/B', '/root/B', '/root/C'] 

 

    """ 

 

    def __init__(self, components, name=None): 

        Component.__init__(self, name=name or 'assembly') 

        self._comps = list(components) 

 

    def __call__(self, *args, **kws): 

        pass  # TODO: Invoke Dispatcher with Assembly's child-components. 

 

    def _build(self, pmod=None): 

        inp = set() 

        out = set() 

        for c in self._comps: 

            c._build(pmod) 

            inp.update(c._inp) 

            out.update(c._out) 

        self._inp = sorted(inp) 

        self._out = sorted(out) 

 

 

if __name__ == '__main__':  # pragma: no cover 

    raise NotImplementedError