fargopy 0.3.15__py3-none-any.whl → 0.4.0__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/simulation.py CHANGED
@@ -699,12 +699,130 @@ class Simulation(fargopy.Fargobj):
699
699
  file_list += "\n"
700
700
  print(file_list)
701
701
  return files
702
+
703
+
704
+ def load_macros(self, summaryfile='summary0.dat'):
705
+ """
706
+ Extracts global simulation parameters from the PREPROCESSOR MACROS SECTION in summary0.dat.
707
+ Returns a dictionary with the parameters found in the macros section.
708
+ Only the value after the last '=' is stored for each parameter.
709
+ """
710
+ summary_path = f"{self.output_dir}/{summaryfile}".replace('//', '/')
711
+ if not os.path.isfile(summary_path):
712
+ print(f"No summary file '{summary_path}' found.")
713
+ return {}
714
+
715
+ macros = {}
716
+ in_macros_section = False
717
+ with open(summary_path, 'r') as f:
718
+ for line in f:
719
+ # Detect the start of the macros section
720
+ if 'PREPROCESSOR MACROS SECTION' in line:
721
+ in_macros_section = True
722
+ continue
723
+ # Stop if another section starts
724
+ if in_macros_section and 'SECTION' in line and 'PREPROCESSOR MACROS SECTION' not in line:
725
+ break
726
+ if in_macros_section:
727
+ # Skip empty lines and lines that don't contain '='
728
+ if line.strip() == '' or '=' not in line or line.strip().startswith('=') or line.strip().startswith('#'):
729
+ continue
730
+ # Extract parameter name and value after the last '='
731
+ parts = line.split('=')
732
+ if len(parts) >= 2:
733
+ key = parts[0].strip()
734
+ value_str = parts[-1].strip()
735
+ # Try to convert to float if possible
736
+ try:
737
+ value = float(value_str)
738
+ except ValueError:
739
+ value = value_str
740
+ macros[key] = value
741
+ self.simulation_macros = macros
742
+ return macros
743
+
744
+
745
+ def load_planet_summary(self, summaryfile='summary0.dat'):
746
+ """
747
+ Loads planet information from summary.dat.
748
+ If not found, tries to extract from variables.par (PLANETMASS, ORBITALRADIUS, PLANETCONFIG).
749
+ Returns a list of dictionaries with name, distance, and mass.
750
+ """
751
+ summary_path = f"{self.output_dir}/{summaryfile}".replace('//', '/')
752
+ if os.path.isfile(summary_path):
753
+ planets = []
754
+ with open(summary_path, 'r') as f:
755
+ lines = f.readlines()
756
+ for line in lines:
757
+ # Skip comments, empty lines, and separators
758
+ if line.strip().startswith('#') or not line.strip() or set(line.strip()) == set('-'):
759
+ continue
760
+ parts = line.split()
761
+ if len(parts) >= 3:
762
+ # Only accept if the first field is NOT a number
763
+ try:
764
+ float(parts[0])
765
+ continue # If it's a number, skip the line
766
+ except ValueError:
767
+ pass # If not a number, it's a planet name
768
+ try:
769
+ planet = {
770
+ 'name': parts[0],
771
+ 'distance': float(parts[1]),
772
+ 'mass': float(parts[2])
773
+ }
774
+ planets.append(planet)
775
+ except ValueError:
776
+ continue
777
+ return planets
778
+
779
+ # If summary.dat does not exist, try to read from variables.par
780
+ varfile = f"{self.output_dir}/variables.par".replace('//', '/')
781
+ if not os.path.isfile(varfile):
782
+ print(f"No summary file '{summary_path}' or variables file '{varfile}' found.")
783
+ return []
784
+
785
+ planet_mass = None
786
+ orbital_radius = None
787
+ planet_config = None
788
+ with open(varfile, 'r') as f:
789
+ for line in f:
790
+ # Look for PLANETMASS, ORBITALRADIUS, PLANETCONFIG lines
791
+ if line.strip().startswith('PLANETMASS'):
792
+ try:
793
+ planet_mass = float(line.split()[1])
794
+ except Exception:
795
+ pass
796
+ elif line.strip().startswith('ORBITALRADIUS'):
797
+ try:
798
+ orbital_radius = float(line.split()[1])
799
+ except Exception:
800
+ pass
801
+ elif line.strip().startswith('PLANETCONFIG'):
802
+ try:
803
+ planet_config = line.split()[1]
804
+ except Exception:
805
+ pass
806
+
807
+ if planet_mass is not None and orbital_radius is not None:
808
+ # Use the config file name as planet name if available
809
+ planet_name = planet_config.split('/')[-1].split('.')[0] if planet_config else 'planet'
810
+ return [{
811
+ 'name': planet_name,
812
+ 'distance': orbital_radius,
813
+ 'mass': planet_mass
814
+ }]
815
+ else:
816
+ print("No planet data found in summary.dat or variables.par.")
817
+ return []
818
+
702
819
 
703
- def load_properties(self,quiet=False,
704
- varfile='variables.par',
705
- domain_prefix='domain_',
706
- dimsfile='dims.dat'
707
- ):
820
+ def load_properties(self, quiet=False,
821
+ varfile='variables.par',
822
+ domain_prefix='domain_',
823
+ dimsfile='dims.dat',
824
+ summaryfile='summary0.dat' # Nuevo parámetro opcional
825
+ ):
708
826
  if self.output_dir is None:
709
827
  print(f"You have to set first the outputs directory with <sim>.set_outputs('<directory>')")
710
828
  return
@@ -716,7 +834,7 @@ class Simulation(fargopy.Fargobj):
716
834
  print(f"Simulation in {vars.DIM} dimensions")
717
835
 
718
836
  # Read domains
719
- domains = self._load_domains(vars,domain_prefix)
837
+ domains = self._load_domains(vars, domain_prefix)
720
838
 
721
839
  # Store the variables in the object
722
840
  self.vars = vars
@@ -730,13 +848,22 @@ class Simulation(fargopy.Fargobj):
730
848
  # Read the summary files
731
849
  self.nsnaps = self._get_nsnaps()
732
850
  print(f"Number of snapshots in output directory: {self.nsnaps}")
733
-
851
+
852
+ # Leer planetas del summary.dat
853
+ self.planets = self.load_planet_summary(summaryfile)
854
+ if self.planets:
855
+ print("Planets found in summary.dat:")
856
+ for planet in self.planets:
857
+ print(f" Name: {planet['name']}, Distance: {planet['distance']}, Mass: {planet['mass']}")
858
+ else:
859
+ print("No planet data found in summary.dat.")
860
+
734
861
  print("Configuration variables and domains load into the object. See e.g. <sim>.vars")
735
862
 
736
863
  def _get_nsnaps(self):
737
864
  """Get the number of snapshots in an output directory
738
865
  """
739
- error,output = fargopy.Sys.run(f"ls {self.output_dir}/summary[0-9]*.dat")
866
+ error, output = fargopy.Sys.run(f"ls {self.output_dir}/summary[0-9]*.dat")
740
867
  if error == 0:
741
868
  files = output[:-1]
742
869
  nsnaps = len(files)
@@ -745,7 +872,7 @@ class Simulation(fargopy.Fargobj):
745
872
  print(f"No summary file in {self.output_dir}")
746
873
  return 0
747
874
 
748
- def _load_dims(self,dimsfile):
875
+ def _load_dims(self, dimsfile):
749
876
  """Parse the dim directory
750
877
  """
751
878
  dimsfile = f"{self.output_dir}/{dimsfile}".replace('//','/')
@@ -843,35 +970,96 @@ class Simulation(fargopy.Fargobj):
843
970
 
844
971
  return domains
845
972
 
846
- def load_field(self,field,snapshot=None,type='scalar'):
847
973
 
848
- if not self.has('vars'):
849
- # If the simulation has not loaded the variables
850
- dims, vars, domains = self.load_properties()
851
-
852
- # In case no snapshot has been provided use 0
853
- snapshot = 0 if snapshot is None else snapshot
854
-
855
- field_data = []
856
- if type == 'scalar':
857
- file_name = f"{field}{str(snapshot)}.dat"
858
- file_field = f"{self.output_dir}/{file_name}".replace('//','/')
859
- field_data = self._load_field_scalar(file_field)
860
- elif type == 'vector':
861
- field_data = []
862
- variables = ['x','y']
863
- if self.vars.DIM == 3:
864
- variables += ['z']
865
- for i,variable in enumerate(variables):
866
- file_name = f"{field}{variable}{str(snapshot)}.dat"
867
- file_field = f"{self.output_dir}/{file_name}".replace('//','/')
868
- field_data += [self._load_field_scalar(file_field)]
869
- else:
870
- raise ValueError(f"fargopy.Field type '{type}' not recognized.")
974
+ def load_field(self, fields, slice=None, snapshot=None, type=None, interpolate=False):
975
+ """
976
+ Load a field from the simulation.
977
+
978
+ Parameters:
979
+ fields (str or list of str): Field name(s) to load.
980
+ slice (str, optional): Slice for 2D data (e.g., 'theta=1.5').
981
+ snapshot (int, optional): Snapshot index to load.
982
+ type (str, optional): Type of the field ('scalar' or 'vector'). Default is 'scalar'.
983
+ interpolate (bool, optional): Whether to interpolate the field. Default is False.
984
+
985
+ Returns:
986
+ fargopy.Field or fargopy.DataHandler: The loaded field(s) or DataHandler object(s).
987
+ """
988
+ # Ensure fields is a list
989
+ if isinstance(fields, str):
990
+ fields = [fields]
991
+
992
+ # Interpolation case
993
+ if interpolate==True:
994
+ fields_data = []
995
+ for field in fields:
996
+ field_data = fargopy.FieldInterpolator(self)
997
+ # Pass the current field instead of the entire list
998
+ field_data.load_data(field, slice, snapshot)
999
+ fields_data.append(field_data)
1000
+ return fields_data if len(fields_data) > 1 else fields_data[0]
1001
+
1002
+ # Non-interpolation case
1003
+ else :
1004
+ if not self.has('vars'):
1005
+ # If the simulation has not loaded the variables
1006
+ dims, vars, domains = self.load_properties()
1007
+
1008
+ # Use snapshot 0 by default if not provided
1009
+ snapshot = 0 if snapshot is None else snapshot
1010
+
1011
+ loaded_fields = []
1012
+
1013
+ for field in fields:
1014
+ field_data = []
1015
+
1016
+ # Determine the field type if not specified
1017
+ field_type = type
1018
+ if field_type is None:
1019
+ if field in ['gasdens', 'gasenergy']:
1020
+ field_type = 'scalar'
1021
+ elif field == 'gasv':
1022
+ field_type = 'vector'
1023
+ else:
1024
+ raise ValueError(f"Field type for '{field}' could not be inferred. Please specify it explicitly.")
1025
+
1026
+ if field_type == 'scalar':
1027
+ file_name = f"{field}{str(snapshot)}.dat"
1028
+ file_field = f"{self.output_dir}/{file_name}".replace('//', '/')
1029
+ field_data = self._load_field_scalar(file_field)
1030
+ elif field_type == 'vector':
1031
+ field_data = []
1032
+ variables = ['x', 'y']
1033
+ if self.vars.DIM == 3:
1034
+ variables += ['z']
1035
+ for variable in variables:
1036
+ file_name = f"{field}{variable}{str(snapshot)}.dat"
1037
+ file_field = f"{self.output_dir}/{file_name}".replace('//', '/')
1038
+ field_data.append(self._load_field_scalar(file_field))
1039
+ else:
1040
+ raise ValueError(f"fargopy.Field type '{field_type}' not recognized.")
1041
+
1042
+ # Create the field object
1043
+ loaded_field = fargopy.Field(
1044
+ data=np.array(field_data),
1045
+ coordinates=self.vars.COORDINATES,
1046
+ domains=self.domains,
1047
+ type=field_type
1048
+ )
1049
+
1050
+ # Apply meshslice if a slice is provided
1051
+ if slice:
1052
+ sliced_data, mesh = loaded_field.meshslice(slice=slice)
1053
+ # Pass a single dictionary to Dictobj
1054
+ loaded_field = fargopy.Dictobj(dict=dict(data=sliced_data, mesh=mesh))
1055
+
1056
+
1057
+
1058
+ loaded_fields.append(loaded_field)
1059
+ #print(f'Slice: {slice}.')
1060
+ # Return a single field if only one was provided, or a list if multiple were provided
1061
+ return loaded_fields if len(loaded_fields) > 1 else loaded_fields[0]
871
1062
 
872
- field = fargopy.Field(data=np.array(field_data), coordinates=self.vars.COORDINATES, domains=self.domains, type=type)
873
- return field
874
-
875
1063
  def _load_field_scalar(self,file):
876
1064
  """Load scalar field from file a file.
877
1065
  """
fargopy/version.py CHANGED
@@ -1 +1 @@
1
- version='0.3.15'
1
+ version='0.4.0'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fargopy
3
- Version: 0.3.15
3
+ Version: 0.4.0
4
4
  Summary: FARGO3D Wrapping
5
5
  Home-page: https://pypi.org/project/fargopy
6
6
  Author: Jorge Zuluaga, Alejandro Murillo-González, Matias Montesinos
@@ -17,6 +17,7 @@ Requires-Dist: matplotlib
17
17
  Requires-Dist: tqdm
18
18
  Requires-Dist: numpy
19
19
  Requires-Dist: ipython
20
+ Requires-Dist: joblib
20
21
  Requires-Dist: celluloid
21
22
  Requires-Dist: psutil
22
23
  Requires-Dist: gdown
@@ -459,6 +460,8 @@ You may find in the [examples directory](https://github.com/seap-udea/fargopy/tr
459
460
 
460
461
  ## What's new
461
462
 
463
+ Version 0.4.*:
464
+ - Interpolation and flux computations.
462
465
 
463
466
  Version 0.3.*:
464
467
 
@@ -0,0 +1,17 @@
1
+ fargopy/__init__.py,sha256=LXTuWtqxWCDPWGG9mO20NpK1WtQPWmDhET08OXJ82lE,12526
2
+ fargopy/fields.py,sha256=yHenVK2AdEFDggF6-mZ9O33Q18mJQ-ccP1RaBAjI6Tw,36896
3
+ fargopy/flux.py,sha256=7nSFkX2rKQo4NI-c_GnhXpRhgRv6COvxsUyaNIODqRY,32480
4
+ fargopy/fsimulation.py,sha256=Lo2METd7Qa05A8tvp5GaJss8cQFBCJS0w7gFFve8ySI,18657
5
+ fargopy/plot.py,sha256=T2xhVQnBU9NVebxgMgegcuBc0YZSei12VC6OzD5JihI,1583
6
+ fargopy/simulation.py,sha256=NQIjJ2wu4E7CXHSro3zFEhefRXjQqAw8AaRH5evGJys,50304
7
+ fargopy/sys.py,sha256=O53WNHU3EL3GIrpxuK4mi2er929f6Ztdf5Fej62DDs8,5055
8
+ fargopy/util.py,sha256=Bbll0TwJjFp5hv2luoBu9ogNiepp4oErPFcuty7YqdY,672
9
+ fargopy/version.py,sha256=oa-4RrMgexZC4mIb7ovFgKJij15qqFFtuczJifkJeU0,16
10
+ fargopy/tests/test___init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ fargopy-0.4.0.data/scripts/ifargopy,sha256=t5E07jKzOLtNnlNyElQZbzjCW6wnR0bc8uCaZpw9yS8,382
12
+ fargopy-0.4.0.dist-info/licenses/LICENSE,sha256=aIckKnNVrkXQMqEKlzGn_REfTwc82TF35BHMCRwPXCI,1097
13
+ fargopy-0.4.0.dist-info/METADATA,sha256=nkII7w-W0HNHKE3I4DuEygV6X6Nb3Z1vsqZPyXld_HM,17837
14
+ fargopy-0.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ fargopy-0.4.0.dist-info/entry_points.txt,sha256=555NPKYbLCN0fgJbdW4b4azZ5sqjhqVqTUxujBBYEJY,49
16
+ fargopy-0.4.0.dist-info/top_level.txt,sha256=_r66v1_-9T7dB5sQa12AdxaAdsv9-OTwtR-vft4OPBU,8
17
+ fargopy-0.4.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (78.1.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,16 +0,0 @@
1
- fargopy/__init__.py,sha256=Ua0ORnNZRgXeU1A-SlT5p2YBBs8x-O30Vwu2xh8b3mg,12490
2
- fargopy/fields.py,sha256=--TrrAaFO9WmsrecRfdmEV1FRfp6JQRlIqyqGn11p2g,10128
3
- fargopy/fsimulation.py,sha256=jfaLxgNePUx1seUv4uP5BHhxzU02wAmKbpE25wYnR1Y,23912
4
- fargopy/plot.py,sha256=T2xhVQnBU9NVebxgMgegcuBc0YZSei12VC6OzD5JihI,1583
5
- fargopy/simulation.py,sha256=MiVkFsm9irt90xFgAcS_2oz467L-Ox5z2eCtIichuZs,41976
6
- fargopy/sys.py,sha256=O53WNHU3EL3GIrpxuK4mi2er929f6Ztdf5Fej62DDs8,5055
7
- fargopy/util.py,sha256=Bbll0TwJjFp5hv2luoBu9ogNiepp4oErPFcuty7YqdY,672
8
- fargopy/version.py,sha256=tGOTbIKeitQH2urrdMPXqzyOiU7L-EhzSKhBjPcjOU4,17
9
- fargopy/tests/test___init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- fargopy-0.3.15.data/scripts/ifargopy,sha256=t5E07jKzOLtNnlNyElQZbzjCW6wnR0bc8uCaZpw9yS8,382
11
- fargopy-0.3.15.dist-info/licenses/LICENSE,sha256=aIckKnNVrkXQMqEKlzGn_REfTwc82TF35BHMCRwPXCI,1097
12
- fargopy-0.3.15.dist-info/METADATA,sha256=DZO8Aj5Obp8rarK4k7wWJ9EtSLoWOef70qLwJUrderk,17762
13
- fargopy-0.3.15.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
14
- fargopy-0.3.15.dist-info/entry_points.txt,sha256=555NPKYbLCN0fgJbdW4b4azZ5sqjhqVqTUxujBBYEJY,49
15
- fargopy-0.3.15.dist-info/top_level.txt,sha256=_r66v1_-9T7dB5sQa12AdxaAdsv9-OTwtR-vft4OPBU,8
16
- fargopy-0.3.15.dist-info/RECORD,,