fargopy 0.4.0__py3-none-any.whl → 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fargopy/__init__.py CHANGED
@@ -1,358 +1,20 @@
1
1
  ###############################################################
2
- # Version
2
+ # Package Base
3
3
  ###############################################################
4
- from fargopy.version import *
5
-
6
- ###############################################################
7
- # External modules
8
- ###############################################################
9
- import warnings
10
- import os
11
- import json
12
- import sys
13
- import numpy as np
14
-
15
- ###############################################################
16
- # Aliases
17
- ###############################################################
18
-
19
- ###############################################################
20
- # Constants
21
- ###############################################################
22
- DEG = np.pi/180
23
- RAD = 1/DEG
24
-
25
- # Check if we are in colab
26
- IN_COLAB = 'google.colab' in sys.modules
27
-
28
- ###############################################################
29
- # Base classes
30
- ###############################################################
31
- class Debug(object):
32
- """The Debug class control the Debugging messages of the package.
33
-
34
- Attribute:
35
- VERBOSE: bool, default = False:
36
- If True all the trace messages are shown.
37
-
38
- Static methods:
39
- trace(msg):
40
- Show a debugging message if VERBOSE=True
41
- Example:
42
- >>> import fargopy as fp
43
- >>> fp.Debug.VERBOSE = True
44
- >>> fp.initialize('configure')
45
- """
46
- VERBOSE = False
47
- @staticmethod
48
- def trace(msg):
49
- if Debug.VERBOSE:
50
- print("::"+msg)
51
-
52
- class Dictobj(object):
53
- """Convert a dictionary to an object
54
-
55
- Initialization attributes:
56
- dict: dictionary:
57
- Dictionary containing the attributes.
58
-
59
- Attributes:
60
- All the keys in the initialization dictionary.
61
-
62
- Examples:
63
- Three ways to initialize the same `Dictobj`:
64
- >>> ob = Dictobj(a=2,b=3)
65
- >>> ob = Dictobj(dict=dict(a=2,b=3))
66
- >>> ob = Dictobj(dict={'a':2,'b':3})
67
-
68
- In the three cases you may access the attributes using:
69
- >>> print(ob.a,ob.b)
70
-
71
- Methods:
72
- keys():
73
- It works like the keys() method of a dictionary.
74
- item(key):
75
- Recover the value of an attribute as it was a dictionary.
76
- Example:
77
- >>> ob.item('a')
78
- print_keys():
79
- Print a list of keys
80
-
81
- """
82
-
83
- def __init__(self, **kwargs):
84
- if 'dict' in kwargs.keys():
85
- kwargs.update(kwargs['dict'])
86
- for key, value in kwargs.items():
87
- if key == 'dict':continue
88
- setattr(self, key, value)
89
-
90
- def __getitem__(self,key):
91
- return self.item(str(key))
92
-
93
- def keys(self):
94
- """Show the list of attributes of Dictobj
95
-
96
- This method works as the keys() method of a regular dictionary.
97
- """
98
- props = []
99
- for i,prop in enumerate(self.__dict__.keys()):
100
- if '__' in prop:
101
- continue
102
- props += [prop]
103
- return props
104
-
105
- def item(self,key):
106
- """Get the value of an item of a Dictobj.
107
- """
108
- if key not in self.keys():
109
- raise ValueError(f"Key 'key' not in Dictobj")
110
- return self.__dict__[key]
111
-
112
- def __getitem__(self,key):
113
- return self.item(str(key))
114
-
115
- def print_keys(self):
116
- """Print all the keys of a Dictobj.
117
- """
118
- prop_list=''
119
- for i,prop in enumerate(self.keys()):
120
- prop_list += f"{prop}, "
121
- if ((i+1)%10) == 0:
122
- prop_list += '\n'
123
- print(prop_list.strip(', '))
124
-
125
- def __str__(self):
126
- return str(self.__dict__)
127
-
128
- def __repr__(self):
129
- return self.__str__()
130
-
131
- class Fargobj(object):
132
- def __init__(self,**kwargs):
133
- self.fobject = True
134
- self.kwargs = kwargs
135
-
136
- def save_object(self,filename=None,verbose=False):
137
- """Save Fargobj into a filename in JSON format
138
-
139
- Args:
140
- filename: string, default = None:
141
- Path of the file where the object will be saved.
142
- If None the filename will be '/tmp/fargobj_{hash}.json'
143
- where {hash} is the hash of the object attributes dictionary.
144
- """
145
- if filename is None:
146
- object_hash = str(abs(hash(str(self.__dict__))))
147
- filename = f"/tmp/fargobj_{object_hash}.json"
148
- if verbose:
149
- print(f"Saving object to {filename}...")
150
- with open(filename,'w') as file_object:
151
- file_object.write(json.dumps(self.__dict__,default=lambda obj:'<not serializable>'))
152
- file_object.close()
153
-
154
- def set_property(self,property,default,method=lambda prop:prop):
155
- """Set a property of object using a given method
156
-
157
- Examples:
158
- Simple example
159
- >>> obj = Fargobj()
160
- >>> obj.set_property('a',1)
161
- >>> print(obj.a)
162
- 1
163
-
164
- Using a special method:
165
- >>> obj = Fargobj()
166
- >>> obj.set_property('a',2,lambda x:x**2)
167
- >>> print(obj.a)
168
- 4
169
- """
170
- if property in self.kwargs.keys():
171
- method(self.kwargs[property])
172
- self.__dict__[property] = self.kwargs[property]
173
- return True
174
- else:
175
- method(default)
176
- self.__dict__[property] = default
177
- return False
178
-
179
- def has(self,key):
180
- """Check if a key is an attribute of Fargobj object
181
-
182
- Examples:
183
- >>> obj = Fargobj(a=1)
184
- >>> print(obj.has('a'))
185
- True
186
- """
187
- if key in self.__dict__.keys():
188
- return True
189
- else:
190
- return False
191
-
192
- ###############################################################
193
- # Package configuration
194
- ###############################################################
195
- # Basic (unmodifiable) variables
196
- Conf = Dictobj()
197
- Conf.FP_HOME = os.environ['HOME']
198
- Conf.FP_DOTDIR = f"{Conf.FP_HOME}/.fargopy"
199
- Conf.FP_RCFILE = f"{Conf.FP_DOTDIR}/fargopyrc"
200
-
201
- # Default configuration file content
202
- Conf.FP_CONFIGURATION = f"""# This is the configuration variables for FARGOpy
203
- # Package
204
- FP_VERSION = '{version}'
205
- # System
206
- FP_HOME = '{Conf.FP_HOME}/'
207
- # Directories
208
- FP_DOTDIR = '{Conf.FP_DOTDIR}'
209
- FP_RCFILE = '{Conf.FP_RCFILE}'
210
- # Behavior
211
- FP_VERBOSE = False
212
- # FARGO3D variablles
213
- FP_FARGO3D_CLONECMD = 'git clone https://bitbucket.org/fargo3d/public.git'
214
- FP_FARGO3D_BASEDIR = '{Conf.FP_HOME}'
215
- FP_FARGO3D_PACKDIR = 'fargo3d/'
216
- FP_FARGO3D_BINARY = 'fargo3d'
217
- FP_FARGO3D_HEADER = 'src/fargo3d.h'
218
- """
219
-
220
- # Default initialization script
221
- Conf.FP_INITIAL_SCRIPT = """
222
- import sys
223
- import fargopy as fp
224
- get_ipython().run_line_magic('load_ext','autoreload')
225
- get_ipython().run_line_magic('autoreload','2')
226
- fp.initialize(' '.join(sys.argv))
227
- """
228
-
229
- def initialize(options='', force=False, **kwargs):
230
- """Initialization routine
231
-
232
- Args:
233
- options: string, default = '':
234
- Action(s) to be performed. Valid actions include:
235
- 'configure': configure the package.
236
- 'download': download FARGO3D directory.
237
- 'check': attempt to compile FARGO3D in the machine.
238
- 'all': all actions.
239
-
240
- force: bool, default = False:
241
- If True, force any action that depends on a previous condition.
242
- For instance if options = 'configure' and force = True it will
243
- override FARGOpy directory.
244
- """
245
- if ('configure' in options) or ('all' in options):
246
- # Create configuration directory
247
- if not os.path.isdir(Conf.FP_DOTDIR) or force:
248
- Debug.trace(f"Configuring FARGOpy at {Conf.FP_DOTDIR}...")
249
- # Create directory
250
- os.system(f"mkdir -p {Conf.FP_DOTDIR}")
251
- # Create configuration variables
252
- f = open(f"{Conf.FP_DOTDIR}/fargopyrc",'w')
253
- f.write(Conf.FP_CONFIGURATION)
254
- f.close()
255
- # Create initialization script
256
- f = open(f"{Conf.FP_DOTDIR}/ifargopy.py",'w')
257
- f.write(Conf.FP_INITIAL_SCRIPT)
258
- f.close()
259
- else:
260
- Debug.trace(f"Configuration already in place.")
261
-
262
- if ('download' in options) or ('all' in options):
263
- fargo_dir = f"{Conf.FP_FARGO3D_BASEDIR}/{Conf.FP_FARGO3D_PACKDIR}".replace('//','/')
264
-
265
- print("Downloading FARGOpy...")
266
- if not os.path.isdir(fargo_dir) or force:
267
- if os.path.isdir(fargo_dir):
268
- print(f"Directory '{fargo_dir}' already exists. Removing it...")
269
- os.system(f"rm -rf {fargo_dir}")
270
- fargopy.Sys.simple(f"cd {Conf.FP_FARGO3D_BASEDIR};{Conf.FP_FARGO3D_CLONECMD} {Conf.FP_FARGO3D_PACKDIR}")
271
- print(f"\tFARGO3D downloaded to {fargo_dir}")
272
- else:
273
- print(f"\tFARGO3D directory already present in '{fargo_dir}'")
274
-
275
- fargo_header = f"{fargo_dir}/{Conf.FP_FARGO3D_HEADER}"
276
- if not os.path.isfile(fargo_header):
277
- print(f"No header file for fargo found in '{fargo_header}'")
278
- else:
279
- print(f"Header file for FARGO3D found in the fargo directory {fargo_dir}")
280
-
281
- if ('check' in options) or ('all' in options):
282
- fargo_dir = f"{Conf.FP_FARGO3D_BASEDIR}/{Conf.FP_FARGO3D_PACKDIR}".replace('//','/')
283
-
284
- print("Test compilation of FARGO3D")
285
- if not os.path.isdir(fargo_dir):
286
- print(f"Directory '{fargo_dir}' does not exist. Please download it with fargopy.initialize('download')")
287
-
288
- cmd_fun = lambda options,mode:f"make -C {fargo_dir} clean mrproper all {options} 2>&1 |tee /tmp/fargo_{mode}.log"
289
-
290
- for option,mode in zip(['PARALLEL=0 GPU=0','PARALLEL=0 GPU=1','PARALLEL=1 GPU=0'],
291
- ['regular','gpu','parallel']):
292
- # Verify if you want to check this mode
293
- if (mode in kwargs.keys()) and (kwargs[mode]==0):
294
- print(f"\tSkipping {mode} compilation")
295
- exec(f"Conf.FP_FARGO3D_{mode.upper()} = 0")
296
- continue
297
-
298
- cmd = cmd_fun(option,mode)
299
- print(f"\tChecking normal compilation.\n\tRunning '{cmd}':")
300
- error,output = Sys.run(cmd)
301
- if not os.path.isfile(f"{fargo_dir}/{Conf.FP_FARGO3D_BINARY}"):
302
- print(f"\t\tCompilation failed for '{mode}'. Check log file '/tmp/fargo_{mode}.log'")
303
- exec(f"Conf.FP_FARGO3D_{mode.upper()} = 0")
304
- else:
305
- print(f"\t\tCompilation in mode {mode} successful.")
306
- exec(f"Conf.FP_FARGO3D_{mode.upper()} = 1")
307
-
308
- print(f"Summary of compilation modes:")
309
- print(f"\tRegular: {Conf.FP_FARGO3D_REGULAR}")
310
- print(f"\tGPU: {Conf.FP_FARGO3D_GPU}")
311
- print(f"\tParallel: {Conf.FP_FARGO3D_PARALLEL}")
312
-
313
- ###############################################################
314
- # Initialization
315
- ###############################################################
316
- # Avoid warnings
317
- warnings.filterwarnings("ignore")
318
-
319
- # Read FARGOpy configuration variables
320
- if not os.path.isdir(Conf.FP_DOTDIR):
321
- print(f"Configuring FARGOpy for the first time")
322
- initialize('configure')
323
- Debug.trace(f"::Reading configuration variables")
324
-
325
- # Load configuration variables into Conf
326
- conf_dict = dict()
327
- exec(open(f"{Conf.FP_RCFILE}").read(),dict(),conf_dict)
328
- Conf.__dict__.update(conf_dict)
329
-
330
- # Derivative configuration variables
331
- Debug.VERBOSE = Conf.FP_VERBOSE
332
- Conf.FP_FARGO3D_DIR = (Conf.FP_FARGO3D_BASEDIR + '/' + Conf.FP_FARGO3D_PACKDIR).replace('//','/')
333
- Conf.FP_FARGO3D_LOCKFILE = f"{Conf.FP_DOTDIR}/fargopy.lock"
334
-
335
- # Check if version in RCFILE is different from installed FARGOpy version
336
- if Conf.FP_VERSION != version:
337
- print(f"Your configuration file version '{Conf.FP_VERSION}' it is different than the installed version of FARGOpy '{version}'")
338
- ans = input(f"Do you want to update configuration file '{Conf.FP_RCFILE}'? [Y/n]: ")
339
- if ans and ('Y' not in ans.upper()):
340
- if 'N' in ans.upper():
341
- print("We will keeping asking you this until you update it, sorry!")
342
- else:
343
- os.system(f"cp -rf {Conf.FP_RCFILE} {Conf.FP_RCFILE}.save")
344
- initialize('configure',force=True)
4
+ from .base import *
345
5
 
346
6
  ###############################################################
347
7
  # Import package modules
348
8
  ###############################################################
349
- from fargopy.util import *
9
+ # Now we can import submodules at the top level because base is loaded
350
10
  from fargopy.sys import *
351
11
  from fargopy.fields import *
352
12
  from fargopy.simulation import *
353
13
  from fargopy.plot import *
354
- #from fargopy.fsimulation import *
355
14
  from fargopy.flux import *
356
15
 
357
- # Showing version
358
- print(f"Running FARGOpy version {version}")
16
+ # Show version
17
+ _welcome()
18
+
19
+ # Clean up namespace if needed (optional)
20
+ del _welcome