import GiRaFFEfood_NRPy_Common_Functions as gfcf  # Some useful functions for GiRaFFE initial data.
import reference_metric as rfm  # NRPy+: Reference metric support
import Min_Max_and_Piecewise_Expressions as noif
par.set_parval_from_str("reference_metric::CoordSystem", "Cartesian")
rfm.reference_metric()
# Step 1a: Set commonly used parameters.
thismodule = __name__

nrpyDilog = sp.Function('nrpyDilog')
from outputC import custom_functions_for_SymPy_ccode
custom_functions_for_SymPy_ccode["nrpyDilog"] = "gsl_sf_dilog"

C_SM = par.Cparameters("REAL", thismodule, ["C_SM"], 1.0)
par.initialize_param(
    par.glb_param(type="bool",
                  module=thismodule,
                  parname="drop_fr",
                  defaultval=True))


def f_of_r(r, M):
    if par.parval_from_str("drop_fr"):
        return sp.sympify(0)
    x = sp.sympify(2) * M / r
    L = sp.sympify(0) + \
        noif.coord_greater_bound(x,sp.sympify(0))*noif.coord_less_bound(x,sp.sympify(1))*nrpyDilog(x)\
       +sp.Rational(1,2)*sp.log(noif.coord_greater_bound(x,sp.sympify(0))*x + noif.coord_leq_bound(x,sp.sympify(1)))\
       *sp.log(noif.coord_less_bound(x,sp.sympify(1))*(sp.sympify(1)-x) + noif.coord_geq_bound(x,sp.sympify(1)))
    f = r*r*(sp.sympify(2)*r-sp.sympify(3)*M)*sp.Rational(1,8)/(M**3)*L\
      +(M*M+sp.sympify(3)*M*r-sp.sympify(6)*r*r)*sp.Rational(1,12)/(M*M)*sp.log(r*sp.Rational(1,2)/M)\
      +sp.Rational(11,72) + M*sp.Rational(1,3)/r + r*sp.Rational(1,2)/M - r*r*sp.Rational(1,2)/(M*M)
    return f
Example #2
0
from NRPy_logo import *
#print_logo()

# Step 2: Initialize core parameter NRPy::MainModule,
#         which defines the desired main module.
#         E.g., scalarwave, BSSN_RHSs, BSSN_InitialData, etc.
# Contains parameter initialization, manipulation, and read-in routines
import NRPy_param_funcs as par

# Used to import needed modules dynamically
import importlib

# Initialize the MainModule parameter.
# This is the ONLY parameter initialized outside of a module!
MainModule = "scalarwave"  # Default. To be overwritten later.
par.initialize_param(par.glb_param("char", "NRPy", "MainModule", MainModule))

# Step 4: Initialize NRPy+ as desired.

# Step 4a: Enter Interactive Mode if NRPy+ is run via
#   `python nrpy.py`
if (len(sys.argv) == 1):
    print("/* Run `python nrpy.py --help` for other command-line options */")
    print("/* Entering interactive mode                                  */\n")

#   Print help message if NRPy+ is run via
#    `python nrpy.py --help`
elif (len(sys.argv) == 2 and sys.argv[1] == "--help"):
    print("\n     \033[1m............................................\033[0m ")
    print("     -={ \033[1mNRPy+ supports multiple usage modes.\033[0m }=-\n")
    print(
Example #3
0
# Author: Zachariah B. Etienne
#         zachetie **at** gmail **dot* com

import NRPy_param_funcs as par  # NRPy+: Parameter interface
import sympy as sp  # Import SymPy, a computer algebra system written entirely in Python
from collections import namedtuple  # Standard Python `collections` module: defines named tuples data structure
import os  # Standard Python module for multiplatform OS-level functions

# Initialize globals related to the grid
glb_gridfcs_list = []
glb_gridfc = namedtuple('gridfunction',
                        'gftype name rank DIM f_infinity wavespeed')

thismodule = __name__
par.initialize_param(
    par.glb_param("char", thismodule, "GridFuncMemAccess", "SENRlike"))
par.initialize_param(par.glb_param("char", thismodule, "MemAllocStyle", "210"))
par.initialize_param(par.glb_param("int", thismodule, "DIM", 3))

Nxx = par.Cparameters("int", thismodule, ["Nxx0", "Nxx1", "Nxx2"],
                      [64, 32, 64])  # Default to 64x32x64 grid
Nxx_plus_2NGHOSTS = par.Cparameters(
    "int", thismodule,
    ["Nxx_plus_2NGHOSTS0", "Nxx_plus_2NGHOSTS1", "Nxx_plus_2NGHOSTS2"],
    [70, 38, 70])  # Default to 64x32x64 grid w/ NGHOSTS=3
xx = par.Cparameters("REAL", thismodule, ["xx0", "xx1", "xx2"],
                     1e300)  # These are C variables, not parameters, and
# will be overwritten; best to initialize to crazy
# number to ensure they are overwritten!
# TODO: dt = par.Cparameters("REAL", thismodule, ["dt"], 0.1)
dxx = par.Cparameters("REAL", thismodule, ["dxx0", "dxx1", "dxx2"], 0.1)
Example #4
0
import NRPy_param_funcs as par
import re
from SIMD import expr_convert_to_SIMD_intrins

from collections import namedtuple
lhrh = namedtuple('lhrh', 'lhs rhs')
outCparams = namedtuple(
    'outCparams',
    'preindent includebraces declareoutputvars outCfileaccess outCverbose CSE_enable CSE_varprefix SIMD_enable SIMD_debug enable_TYPE'
)

# Parameter initialization is called once, within nrpy.py.
par.initialize_param(
    par.glb_param("char", __name__, "PRECISION",
                  "double"))  # __name__ = "outputC", this module's name.

# par.initialize_param(par.glb_param("bool", thismodule, "SIMD_enable", False))


# super fast 'uniq' function:
# f8() function from https://www.peterbe.com/plog/uniqifiers-benchmark
def superfast_uniq(seq):  # Author: Dave Kirby
    # Order preserving
    seen = set()
    return [x for x in seq if x not in seen and not seen.add(x)]


def ccode_postproc(string):
    PRECISION = par.parval_from_str("PRECISION")

    # In the C math library, e.g., pow(x,y) assumes x and y are doubles, and returns a double.
Example #5
0
def unpickle_NRPy_env(NRPyEnvVars):
    import pickle
    # https://www.pythonforthelab.com/blog/storing-binary-data-and-serializing/
    grfcs_list = []
    param_list = []
    Cparm_list = []

    outCfunc_dict = {}
    outCfuncproto_dict = {}
    outCfuncoutdir_dict = {}
    outCfunc_master_list = []

    for WhichParamSet in NRPyEnvVars[0]:
        # gridfunctions
        i = 0
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            grfcs_list.append(
                gri.glb_gridfc(gftype=pickle.loads(WhichParamSet[i + 0]),
                               name=pickle.loads(WhichParamSet[i + 1]),
                               rank=pickle.loads(WhichParamSet[i + 2]),
                               DIM=pickle.loads(WhichParamSet[i + 3]),
                               f_infinity=pickle.loads(WhichParamSet[i + 4]),
                               wavespeed=pickle.loads(WhichParamSet[i + 5])))
            i += 6
        # parameters
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            param_list.append(
                par.glb_param(type=pickle.loads(WhichParamSet[i + 0]),
                              module=pickle.loads(WhichParamSet[i + 1]),
                              parname=pickle.loads(WhichParamSet[i + 2]),
                              defaultval=pickle.loads(WhichParamSet[i + 3])))
            i += 4
        # Cparameters
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            Cparm_list.append(
                par.glb_Cparam(type=pickle.loads(WhichParamSet[i + 0]),
                               module=pickle.loads(WhichParamSet[i + 1]),
                               parname=pickle.loads(WhichParamSet[i + 2]),
                               defaultval=pickle.loads(WhichParamSet[i + 3])))
            i += 4
        # outC_func_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcbody = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfunc_dict[funcname] = funcbody

        # outC.outC_function_prototype_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcproto = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfuncproto_dict[funcname] = funcproto

        # outC.outC_function_outdir_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcoutdir = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfuncoutdir_dict[funcname] = funcoutdir

        # outC.outC_function_master_list
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            includes = pickle.loads(WhichParamSet[i + 0])
            i += 1
            prefunc = pickle.loads(WhichParamSet[i + 0])
            i += 1
            desc = pickle.loads(WhichParamSet[i + 0])
            i += 1
            c_type = pickle.loads(WhichParamSet[i + 0])
            i += 1
            name = pickle.loads(WhichParamSet[i + 0])
            i += 1
            params = pickle.loads(WhichParamSet[i + 0])
            i += 1
            preloop = pickle.loads(WhichParamSet[i + 0])
            i += 1
            body = pickle.loads(WhichParamSet[i + 0])
            i += 1
            loopopts = pickle.loads(WhichParamSet[i + 0])
            i += 1
            postloop = pickle.loads(WhichParamSet[i + 0])
            i += 1
            enableCparameters = pickle.loads(WhichParamSet[i + 0])
            i += 1
            rel_path_to_Cparams = pickle.loads(WhichParamSet[i + 0])
            i += 1
            # 'includes prefunc desc c_type name params preloop body loopopts postloop enableCparameters rel_path_to_Cparams append_coordsuffix'
            outCfunc_master_list += [
                outC.outC_function_element(
                    includes=includes,
                    prefunc=prefunc,
                    desc=desc,
                    c_type=c_type,
                    name=name,
                    params=params,
                    preloop=preloop,
                    body=body,
                    loopopts=loopopts,
                    postloop=postloop,
                    enableCparameters=enableCparameters,
                    rel_path_to_Cparams=rel_path_to_Cparams)
            ]

    grfcs_list_uniq = []
    for gf_ntuple_stored in grfcs_list:
        found_gf = False
        for gf_ntuple_new in grfcs_list_uniq:
            if gf_ntuple_new == gf_ntuple_stored:
                found_gf = True
        if found_gf == False:
            grfcs_list_uniq.append(gf_ntuple_stored)

    param_list_uniq = []
    for pr_ntuple_stored in param_list:
        found_pr = False
        for pr_ntuple_new in param_list_uniq:
            if pr_ntuple_new == pr_ntuple_stored:
                found_pr = True
        if found_pr == False:
            param_list_uniq.append(pr_ntuple_stored)

    # Set glb_paramsvals_list:
    # Step 1: Reset all paramsvals to their defaults
    #  BAD IDEA: OVERWRITTEN DEFAULTS SHOULD BE KEPT.
    # par.glb_paramsvals_list = []
    # for parm in param_list_uniq:
    #     par.glb_paramsvals_list.append(parm.defaultval)

    Cparm_list_uniq = []
    for Cp_ntuple_stored in Cparm_list:
        found_Cp = False
        for Cp_ntuple_new in Cparm_list_uniq:
            if Cp_ntuple_new == Cp_ntuple_stored:
                found_Cp = True
        if found_Cp == False:
            Cparm_list_uniq.append(Cp_ntuple_stored)

    gri.glb_gridfcs_list = []
    par.glb_params_list = []
    par.glb_Cparams_list = []

    gri.glb_gridfcs_list = grfcs_list_uniq
    par.glb_params_list = param_list_uniq
    par.glb_Cparams_list = Cparm_list_uniq
    for key, item in outCfunc_dict.items():
        outC.outC_function_dict[key] = item

    for key, item in outCfuncproto_dict.items():
        outC.outC_function_prototype_dict[key] = item

    for key, item in outCfuncoutdir_dict.items():
        outC.outC_function_outdir_dict[key] = item

    return outCfunc_master_list
Example #6
0
#  Sets up finite difference stencils as desired.
#
# Depends on: grid.py.
#             Everything depends on outputC.py.

import grid as gri
import re
from outputC import *

from operator import itemgetter

# Step 1: Initialize free parameters for this module:
import NRPy_param_funcs as par
modulename = __name__
# Centered finite difference accuracy order
par.initialize_param(par.glb_param("INT", modulename, "FD_CENTDERIVS_ORDER",
                                   4))


def FD_outputC(filename, sympyexpr_list, params="", upwindcontrolvec=""):
    outCparams = parse_outCparams_string(params)

    # Step 0.a:
    # In case sympyexpr_list is a single sympy expression,
    #     convert it to a list with just one element:
    if type(sympyexpr_list) is not list:
        sympyexpr_list = [sympyexpr_list]

    # Step 0.b:
    # finite_difference.py takes control over outCparams.includebraces here,
    #     which is necessary because outputC() is called twice:
    #     first for the reads from main memory and finite difference
Example #7
0
# As documented in the NRPy+ tutorial module
#   Tutorial-WeylScalarsInvariants-Cartesian

# Step 1: import all needed modules from NRPy+:
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import indexedexp as ixp  # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import grid as gri  # NRPy+: Functions having to do with numerical grids
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import sys  # Standard Python module for multiplatform OS-level operations

# Step 2: Initialize WeylScalars parameters
thismodule = __name__
# Current option: Approx_QuasiKinnersley = choice made in Baker, Campanelli, and Lousto. PRD 65, 044001 (2002)
par.initialize_param(
    par.glb_param("char *", thismodule, "TetradChoice",
                  "Approx_QuasiKinnersley"))
# This controls what gets output. Acceptable values are "psi4_only", "all_psis", and "all_psis_and_invariants"
par.initialize_param(
    par.glb_param("char *", thismodule, "output_scalars",
                  "all_psis_and_invariants"))


def WeylScalars_Cartesian():
    # Step 3.a: Set spatial dimension (must be 3 for BSSN)
    DIM = 3
    par.set_parval_from_str("grid::DIM", DIM)

    # Step 3.b: declare the additional gridfunctions (i.e., functions whose values are declared
    #          at every grid point, either inside or outside of our SymPy expressions) needed
    #         for this thorn:
    #           * the physical metric $\gamma_{ij}$,
# Author: Maria C. Babiuc Hamilton template courtesy Zachariah B. Etienne
#         babiuc **at** marshall **dot* edu

from outputC import parse_outCparams_string, outC_function_dict, outC_function_prototype_dict, outC_NRPy_basic_defines_h_dict, outC_function_master_list  # NRPy+: Core C code output module
import NRPy_param_funcs as par  # NRPy+: parameter interface
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import grid as gri  # NRPy+: Functions having to do with numerical grids
import os, sys  # Standard Python module for multiplatform OS-level functions
from hermite_interpolator_helpers import extract_from_list_of_interp_vars__base_gfs_and_interp_ops_lists
from hermite_interpolator_helpers import generate_list_of_interp_vars_from_lhrh_sympyexpr_list
from hermite_interpolator_helpers import read_gfs_from_memory, HIparams, construct_Ccode

# Step 1: Initialize free parameters for this module:
modulename = __name__
# Hermite interpolator dimension order
par.initialize_param(par.glb_param("int", modulename, "HI_DIMENSIONS_ORDER",
                                   3))
par.initialize_param(
    par.glb_param("bool", modulename, "enable_HI_functions", False))


def HI_outputC(filename, sympyexpr_list, params="", upwindcontrolvec=""):
    outCparams = parse_outCparams_string(params)

    # Step 0.a:
    # In case sympyexpr_list is a single sympy expression,
    #     convert it to a list with just one element.
    #     This enables the rest of the routine to assume
    #     sympyexpr_list is indeed a list.
    if not isinstance(sympyexpr_list, list):
        sympyexpr_list = [sympyexpr_list]
Example #9
0
# indexedexp.py: functions related to indexed expressions,
# including e.g., tensors and pseudotensors:

# Step 1: Load needed modules
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import grid as gri  # NRPy+: Functions having to do with numerical grids
import functional as func  # NRPy+: Python toolkit for functional programming
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import sys  # Standard Python module for multiplatform OS-level functions
import re  # Standard Python module for regular expressions

thismodule = __name__
par.initialize_param(par.glb_param("char", thismodule, "symmetry_axes", ""))


def declare_indexedexp(rank, symbol=None, symmetry=None, dimension=None):
    """ Generate an indexed expression of specified rank and dimension

        >>> ixp = declare_indexedexp(rank=2, symbol='M', dimension=3, symmetry='sym01')
        >>> assert func.pipe(ixp, lambda x: func.repeat(func.flatten, x, 1), set, len) == 6

        >>> ixp = declare_indexedexp(rank=3, symbol='M', dimension=3, symmetry='sym01')
        >>> assert len(set(func.repeat(func.flatten, ixp, 2))) == 18
        >>> ixp = declare_indexedexp(rank=3, symbol='M', dimension=3, symmetry='sym02')
        >>> assert len(set(func.repeat(func.flatten, ixp, 2))) == 18
        >>> ixp = declare_indexedexp(rank=3, symbol='M', dimension=3, symmetry='sym12')
        >>> assert len(set(func.repeat(func.flatten, ixp, 2))) == 18

        >>> ixp = declare_indexedexp(rank=3, symbol='M', dimension=3, symmetry='sym012')
        >>> assert len(set(func.repeat(func.flatten, ixp, 2))) == 10
# THIS MODULE: ../Tutorial-VacuumMaxwell_Flat_ID.ipynb

# Step P1: Import needed NRPy+ core modules:
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import indexedexp as ixp  # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm  # NRPy+: Reference metric support
import sys  # Standard Python module for multiplatform OS-level functions
from Maxwell.CommonParams import amp, lam, time  # NRPy+: Common parameters for all VacuumMaxwell modules (defines amp, lam, and time)

# The name of this module ("InitialData") is given by __name__:
thismodule = __name__

# define parameter for which system to use
par.initialize_param(
    par.glb_param("char", thismodule, "System_to_use", "System_I"))


# Initial data for toroidal dipole field
def Toroidal():
    system = par.parval_from_str(thismodule + "::System_to_use")
    DIM = par.parval_from_str("grid::DIM")

    dst_basis = par.parval_from_str("reference_metric::CoordSystem")

    # Set coordinate system to Cartesian
    par.set_parval_from_str("reference_metric::CoordSystem", "Cartesian")
    rfm.reference_metric()

    global AidU, EidU, psi_ID
    num_elements = pickle.loads(WhichParamSet[i])
    i += 1
    for lst in range(num_elements):
        grfcs_list.append(
            gri.glb_gridfc(gftype=pickle.loads(WhichParamSet[i + 0]),
                           name=pickle.loads(WhichParamSet[i + 1]),
                           rank=pickle.loads(WhichParamSet[i + 2]),
                           DIM=pickle.loads(WhichParamSet[i + 3])))
        i += 4
    # parameters
    num_elements = pickle.loads(WhichParamSet[i])
    i += 1
    for lst in range(num_elements):
        param_list.append(
            par.glb_param(type=pickle.loads(WhichParamSet[i + 0]),
                          module=pickle.loads(WhichParamSet[i + 1]),
                          parname=pickle.loads(WhichParamSet[i + 2]),
                          defaultval=pickle.loads(WhichParamSet[i + 3])))
        i += 4
    # Cparameters
    num_elements = pickle.loads(WhichParamSet[i])
    i += 1
    for lst in range(num_elements):
        Cparm_list.append(
            par.glb_Cparam(type=pickle.loads(WhichParamSet[i + 0]),
                           module=pickle.loads(WhichParamSet[i + 1]),
                           parname=pickle.loads(WhichParamSet[i + 2]),
                           defaultval=pickle.loads(WhichParamSet[i + 3])))
        i += 4
grfcs_list_uniq = []
for gf_ntuple_stored in grfcs_list:
    found_gf = False
Example #12
0
# Depends on: outputC.py and grid.py.

# Author: Zachariah B. Etienne
#         zachetie **at** gmail **dot* com

from outputC import *  # NRPy+: Core C code output module
import grid as gri  # NRPy+: Functions having to do with numerical grids
import sys  # Standard Python module for multiplatform OS-level functions

from operator import itemgetter

# Step 1: Initialize free parameters for this module:
import NRPy_param_funcs as par
modulename = __name__
# Centered finite difference accuracy order
par.initialize_param(par.glb_param("int", modulename, "FD_CENTDERIVS_ORDER",
                                   4))
par.initialize_param(
    par.glb_param("int", modulename, "FD_KO_ORDER__CENTDERIVS_PLUS", 2))


def FD_outputC(filename, sympyexpr_list, params="", upwindcontrolvec=""):
    outCparams = parse_outCparams_string(params)

    # Step 0.a:
    # In case sympyexpr_list is a single sympy expression,
    #     convert it to a list with just one element:
    if type(sympyexpr_list) is not list:
        sympyexpr_list = [sympyexpr_list]

    # Step 0.b:
    # finite_difference.py takes control over outCparams.includebraces here,
Example #13
0
# Author: Zachariah B. Etienne
#         zachetie **at** gmail **dot* com

# Step 1: Import all needed modules from NRPy+:
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import indexedexp as ixp  # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm  # NRPy+: Reference metric support
import BSSN.BSSN_quantities as Bq  # NRPy+: Computes useful BSSN quantities
import BSSN.BSSN_RHSs as Brhs  # NRPy+: Constructs BSSN right-hand-side expressions
import sys  # Standard Python modules for multiplatform OS-level functions

# Step 1.a: Declare/initialize parameters for this module
thismodule = __name__
par.initialize_param(
    par.glb_param("char", thismodule, "LapseEvolutionOption", "OnePlusLog"))
par.initialize_param(
    par.glb_param("char", thismodule, "ShiftEvolutionOption",
                  "GammaDriving2ndOrder_Covariant"))


def BSSN_gauge_RHSs():
    # Step 1.d: Set spatial dimension (must be 3 for BSSN, as BSSN is
    #           a 3+1-dimensional decomposition of the general
    #           relativistic field equations)
    DIM = 3

    # Step 1.e: Given the chosen coordinate system, set up
    #           corresponding reference metric and needed
    #           reference metric quantities
    # The following function call sets up the reference metric
Example #14
0
#       orthogonal coordinate scale factor
#       (positive root of diagonal metric components),
#     2) xxCart[]: Cartesian coordinate (x,y,z)
#     3) xxSph[]: Spherical coordinate (r,theta,phi)
#

import time
import sympy as sp

import NRPy_param_funcs as par
import indexedexp as ixp
import grid as gri

# Step 0a: Initialize parameters
thismodule = __name__
par.initialize_param(par.glb_param("char", thismodule, "CoordSystem", "Spherical"))

# Step 0b: Declare global variables
xx = gri.xx
xxCart = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s
Cart_to_xx = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s
Cartx,Carty,Cartz = sp.symbols("Cartx Carty Cartz", real=True)
Cart = [Cartx,Carty,Cartz]
xxSph  = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s
scalefactor_orthog = ixp.zerorank1(DIM=4) # Must be set in terms of xx[]s
have_already_called_reference_metric_function = False

def reference_metric():
    global have_already_called_reference_metric_function # setting to global enables other modules to see updated value.
    have_already_called_reference_metric_function = True
Example #15
0
import NRPy_param_funcs as par
from collections import namedtuple
import sympy as sp

# grid.py: functions & parameters related to numerical grids:
# functions: Automatic loop output, output C code needed for gridfunction memory I/O, gridfunction registration

# Initialize globals related to the grid
glb_gridfcs_list = []
glb_gridfc = namedtuple('gridfunction', 'gftype name')

thismodule = __name__
par.initialize_param(
    par.glb_param("char", thismodule, "GridFuncMemAccess", "SENRlike"))
par.initialize_param(par.glb_param("char", thismodule, "MemAllocStyle", "210"))
par.initialize_param(par.glb_param("INT", thismodule, "DIM", 3))
par.initialize_param(
    par.glb_param("INT", thismodule, "Nx[DIM]", "SetAtCRuntime"))

xx = par.Cparameters("REALARRAY", thismodule, ["xx0", "xx1", "xx2", "xx3"])


def variable_type(var):
    var_is_gf = False
    for gf in range(len(glb_gridfcs_list)):
        if str(var) == glb_gridfcs_list[gf].name:
            var_is_gf = True
    var_is_parameter = False
    for paramname in range(len(par.glb_params_list)):
        if str(var) == par.glb_params_list[paramname].parname:
            var_is_parameter = True
Example #16
0
import loop as lp                # NRPy+: Generate C code loops
import indexedexp as ixp         # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm   # NRPy+: Reference metric support
import cmdline_helper as cmd     # NRPy+: Multi-platform Python command-line interface

thismodule = __name__

# There are several C parameters that we will need in this module:
M_PI  = par.Cparameters("#define",thismodule,["M_PI"], "")
GAMMA_SPEED_LIMIT = par.Cparameters("REAL",thismodule,"GAMMA_SPEED_LIMIT",10.0) # Default value based on
                                                                                # IllinoisGRMHD.
                                                                                # GiRaFFE default = 2000.0

# There are three fixes in this module; we might not always want to do all (or even any!) of them.
# So, we initialize some NRPy+ parameters to control this behavior
par.initialize_param(par.glb_param(type="bool", module=thismodule, parname="enforce_orthogonality_StildeD_BtildeU", defaultval=True))
par.initialize_param(par.glb_param(type="bool", module=thismodule, parname="enforce_speed_limit_StildeD", defaultval=True))
par.initialize_param(par.glb_param(type="bool", module=thismodule, parname="enforce_current_sheet_prescription", defaultval=True))

def GiRaFFE_NRPy_C2P(StildeD,BU,gammaDD,gammaUU,gammadet,betaU,alpha):
    sqrtgammadet = sp.sqrt(gammadet)
    BtildeU = ixp.zerorank1()
    for i in range(3):
        # \tilde{B}^i = B^i \sqrt{\gamma}
        BtildeU[i] = sqrtgammadet*BU[i]

    BtildeD = ixp.zerorank1()
    for i in range(3):
        for j in range(3):
            BtildeD[j] += gammaDD[i][j]*BtildeU[i]
Example #17
0
#    and related quantities, including rescaling matrices ReDD,
#    ReU, and hatted quantities.
#  DO NOT CALL IN STANDALONE PYTHON MODULE
# rfm.reference_metric()

# Step 1.c: Set spatial dimension (must be 3 for BSSN, as BSSN is
#           a 3+1-dimensional decomposition of the general
#           relativistic field equations)
#  DO NOT CALL IN STANDALONE PYTHON MODULE
# DIM = 3
# par.set_parval_from_str("grid::DIM",DIM)

# Step 1.d: Declare/initialize parameters for this module
thismodule = __name__
par.initialize_param(
    par.glb_param("char", thismodule, "EvolvedConformalFactor_cf", "W"))
par.initialize_param(
    par.glb_param("bool", thismodule, "detgbarOverdetghat_equals_one", "True"))
par.initialize_param(
    par.glb_param("bool", thismodule, "LeaveRicciSymbolic", "False"))


def declare_BSSN_gridfunctions_if_not_declared_already():
    # Step 2: Register all needed BSSN gridfunctions.

    # Declare as globals all variables that may be
    # used outside this function
    global hDD, aDD, lambdaU, vetU, betU, trK, cf, alpha

    #   Check to see if this function has already been called.
    #   If so, do not register the gridfunctions again!
Example #18
0
# This module provides functions that declare and define useful BSSN quantities

# Author: Zachariah B. Etienne
#         zachetie **at** gmail **dot* com

# Step 1.a: Import all needed modules from NRPy+:
import NRPy_param_funcs as par
import sympy as sp
import indexedexp as ixp
import grid as gri
import reference_metric as rfm

# Step 1.b: Declare/initialize parameters for this module
thismodule = __name__
par.initialize_param(par.glb_param("char", thismodule, "ConformalFactor", "W"))
par.initialize_param(par.glb_param("bool", thismodule, "detgbarOverdetghat_equals_one", "True"))

def declare_BSSN_gridfunctions_if_not_declared_already():
    # Step 2: Register all needed BSSN gridfunctions.

    # Step 2.a: Declare as globals all variables that may be
    #           used outside this function
    global hDD,aDD,lambdaU,vetU,betU,trK,cf,alpha

    # Step 2.a: First check to see if this function has already been called.
    #   If so, do not register the gridfunctions again!
    for i in range(len(gri.glb_gridfcs_list)):
        if "hDD00" in gri.glb_gridfcs_list[i].name:
            hDD = ixp.declarerank2("hDD", "sym01")
            aDD = ixp.declarerank2("aDD", "sym01")
            lambdaU = ixp.declarerank1("lambdaU")
from outputC import *
import loop

import reference_metric as rfm
par.set_parval_from_str("reference_metric::CoordSystem", "Cartesian")
rfm.reference_metric()

# Step 1a: Set commonly used parameters.
thismodule = "GiRaFFEfood_HO"
# Set the spatial dimension parameter to 3.
par.set_parval_from_str("grid::DIM", 3)
DIM = par.parval_from_str("grid::DIM")

# Create a parameter to control the initial data choice. For now, this will only have Exact Wald as an option.
par.initialize_param(
    par.glb_param("char", thismodule, "IDchoice", "Exact_Wald"))

# Step 1b: Set needed Cparameters
M = par.Cparameters("REAL", thismodule, ["M"],
                    1.0)  # The mass of the black hole
M_PI = par.Cparameters("#define", thismodule, ["M_PI"], "")  # pi, 3.141592...
KerrSchild_radial_shift = par.Cparameters("REAL", thismodule,
                                          "KerrSchild_radial_shift",
                                          0.4)  # Default value for ExactWald


def GiRaFFEfood_HO_Exact_Wald():

    # <a id='step2'></a>
    #
    # ### Step 2: Set the vectors A and E in Spherical coordinates
# Authors: Zachariah B. Etienne
#          (zachetie **at** gmail **dot* com),
#          and Patrick Nelson

# Step 1.a: import all needed modules from NRPy+:
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import indexedexp as ixp  # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm  # NRPy+: Reference metric support
import sys  # Standard Python modules for multiplatform OS-level functions

# Step 1.b: Initialize TetradChoice parameter
thismodule = __name__
# Current option: QuasiKinnersley = choice made in Baker, Campanelli, and Lousto. PRD 65, 044001 (2002)
par.initialize_param(
    par.glb_param("char", thismodule, "TetradChoice", "QuasiKinnersley"))
par.initialize_param(
    par.glb_param("char", thismodule, "UseCorrectUnitNormal",
                  "False"))  # False = consistent with WeylScal4 ETK thorn.


def Psi4_tetrads():
    global l4U, n4U, mre4U, mim4U

    # Step 1.c: Check if tetrad choice is implemented:
    if par.parval_from_str(thismodule + "::TetradChoice") != "QuasiKinnersley":
        print("ERROR: " + thismodule + "::TetradChoice = " +
              par.parval_from_str("TetradChoice") + " currently unsupported!")
        sys.exit(1)

    # Step 1.d: Given the chosen coordinate system, set up
Example #21
0
def unpickle_NRPy_env(NRPyEnvVars):
    import pickle
    # https://www.pythonforthelab.com/blog/storing-binary-data-and-serializing/
    grfcs_list = []
    param_list = []
    Cparm_list = []

    outCfunc_dict = {}
    outCfuncproto_dict = {}
    outCfuncoutdir_dict = {}

    for WhichParamSet in NRPyEnvVars[0]:
        # gridfunctions
        i = 0
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            grfcs_list.append(
                gri.glb_gridfc(gftype=pickle.loads(WhichParamSet[i + 0]),
                               name=pickle.loads(WhichParamSet[i + 1]),
                               rank=pickle.loads(WhichParamSet[i + 2]),
                               DIM=pickle.loads(WhichParamSet[i + 3])))
            i += 4
        # parameters
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            param_list.append(
                par.glb_param(type=pickle.loads(WhichParamSet[i + 0]),
                              module=pickle.loads(WhichParamSet[i + 1]),
                              parname=pickle.loads(WhichParamSet[i + 2]),
                              defaultval=pickle.loads(WhichParamSet[i + 3])))
            i += 4
        # Cparameters
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            Cparm_list.append(
                par.glb_Cparam(type=pickle.loads(WhichParamSet[i + 0]),
                               module=pickle.loads(WhichParamSet[i + 1]),
                               parname=pickle.loads(WhichParamSet[i + 2]),
                               defaultval=pickle.loads(WhichParamSet[i + 3])))
            i += 4
        # outC_func_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcbody = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfunc_dict[funcname] = funcbody

        # outC_function_prototype_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcproto = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfuncproto_dict[funcname] = funcproto

        # outC_function_outdir_dict
        num_elements = pickle.loads(WhichParamSet[i])
        i += 1
        for lst in range(num_elements):
            funcname = pickle.loads(WhichParamSet[i + 0])
            funcoutdir = pickle.loads(WhichParamSet[i + 1])
            i += 2
            outCfuncoutdir_dict[funcname] = funcoutdir

    grfcs_list_uniq = []
    for gf_ntuple_stored in grfcs_list:
        found_gf = False
        for gf_ntuple_new in grfcs_list_uniq:
            if gf_ntuple_new == gf_ntuple_stored:
                found_gf = True
        if found_gf == False:
            grfcs_list_uniq.append(gf_ntuple_stored)

    param_list_uniq = []
    for pr_ntuple_stored in param_list:
        found_pr = False
        for pr_ntuple_new in param_list_uniq:
            if pr_ntuple_new == pr_ntuple_stored:
                found_pr = True
        if found_pr == False:
            param_list_uniq.append(pr_ntuple_stored)

    # Set glb_paramsvals_list:
    # Step 1: Reset all paramsvals to their defaults
    #  BAD IDEA: OVERWRITTEN DEFAULTS SHOULD BE KEPT.
    # par.glb_paramsvals_list = []
    # for parm in param_list_uniq:
    #     par.glb_paramsvals_list.append(parm.defaultval)

    Cparm_list_uniq = []
    for Cp_ntuple_stored in Cparm_list:
        found_Cp = False
        for Cp_ntuple_new in Cparm_list_uniq:
            if Cp_ntuple_new == Cp_ntuple_stored:
                found_Cp = True
        if found_Cp == False:
            Cparm_list_uniq.append(Cp_ntuple_stored)

    gri.glb_gridfcs_list = []
    par.glb_params_list = []
    par.glb_Cparams_list = []

    gri.glb_gridfcs_list = grfcs_list_uniq
    par.glb_params_list = param_list_uniq
    par.glb_Cparams_list = Cparm_list_uniq
    for key, item in outCfunc_dict.items():
        outC_function_dict[key] = item

    for key, item in outCfuncproto_dict.items():
        outC_function_prototype_dict[key] = item

    for key, item in outCfuncoutdir_dict.items():
        outC_function_outdir_dict[key] = item
Example #22
0
#          (zachetie **at** gmail **dot* com),
#          and Patrick Nelson

# Step 1.a: import all needed modules from NRPy+:
import sympy as sp
import NRPy_param_funcs as par
import indexedexp as ixp
import grid as gri
import finite_difference as fin
import reference_metric as rfm

# Step 1.b: Initialize TetradChoice parameter
thismodule = __name__
# Current option: QuasiKinnersley = choice made in Baker, Campanelli, and Lousto. PRD 65, 044001 (2002)
par.initialize_param(
    par.glb_param("char", thismodule, "TetradChoice", "QuasiKinnersley"))
par.initialize_param(
    par.glb_param("char", thismodule, "UseCorrectUnitNormal", "False"))


def v_vectorDU(v1, v2, v3, i, a):
    if i == 0:
        return v1[a]
    elif i == 1:
        return v2[a]
    elif i == 2:
        return v3[a]
    else:
        print("ERROR: unknown vector!")
        exit(1)
# Author: Zachariah B. Etienne
#         zachetie **at** gmail **dot* com

from outputC import parse_outCparams_string, outC_function_dict, outC_function_prototype_dict, outC_NRPy_basic_defines_h_dict, outC_function_master_list  # NRPy+: Core C code output module
import NRPy_param_funcs as par   # NRPy+: parameter interface
import sympy as sp               # SymPy: The Python computer algebra package upon which NRPy+ depends
import grid as gri               # NRPy+: Functions having to do with numerical grids
import os, sys                   # Standard Python module for multiplatform OS-level functions
from finite_difference_helpers import extract_from_list_of_deriv_vars__base_gfs_and_deriv_ops_lists
from finite_difference_helpers import generate_list_of_deriv_vars_from_lhrh_sympyexpr_list
from finite_difference_helpers import read_gfs_from_memory, FDparams, construct_Ccode

# Step 1: Initialize free parameters for this module:
modulename = __name__
# Centered finite difference accuracy order
par.initialize_param(par.glb_param("int",  modulename, "FD_CENTDERIVS_ORDER",          4))
par.initialize_param(par.glb_param("bool", modulename, "enable_FD_functions",      False))
par.initialize_param(par.glb_param("int",  modulename, "FD_KO_ORDER__CENTDERIVS_PLUS", 2))

def FD_outputC(filename, sympyexpr_list, params="", upwindcontrolvec=""):
    outCparams = parse_outCparams_string(params)

    # Step 0.a:
    # In case sympyexpr_list is a single sympy expression,
    #     convert it to a list with just one element.
    #     This enables the rest of the routine to assume
    #     sympyexpr_list is indeed a list.
    if not isinstance(sympyexpr_list, list):
        sympyexpr_list = [sympyexpr_list]

    # Step 0.b:
Example #24
0
import NRPy_param_funcs as par  # NRPy+: Parameter interface
import indexedexp as ixp  # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import grid as gri  # NRPy+: Functions having to do with numerical grids
import sympy as sp  # SymPy: The Python computer algebra package upon which NRPy+ depends

par.initialize_param(
    par.glb_param("char", __name__, "System_to_use", "System_II"))


def MaxwellCartesian_Evol():
    #Step 0: Set the spatial dimension parameter to 3.
    par.set_parval_from_str("grid::DIM", 3)
    DIM = par.parval_from_str("grid::DIM")

    # Step 1: Set the finite differencing order to 4.
    # (not needed here)
    # par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER", 4)

    # Step 2: Register gridfunctions that are needed as input.
    _psi = gri.register_gridfunctions(
        "EVOL", ["psi"])  # lgtm [py/unused-local-variable]

    # Step 3a: Declare the rank-1 indexed expressions E_{i}, A_{i},
    #          and \partial_{i} \psi. Derivative variables like these
    #          must have an underscore in them, so the finite
    #          difference module can parse the variable name properly.
    ED = ixp.register_gridfunctions_for_single_rank1("EVOL", "ED")
    AD = ixp.register_gridfunctions_for_single_rank1("EVOL", "AD")
    psi_dD = ixp.declarerank1("psi_dD")

    ## Step 3b: Declare the conformal metric tensor and its first
Example #25
0
import NRPy_param_funcs as par
import indexedexp as ixp
import grid as gri
import finite_difference as fin
import reference_metric as rfm

rfm.reference_metric()
from outputC import *
import BSSN_RHSs as bssn
import sympy as sp

# Step 1: Initialize WeylScalar parameters
thismodule = __name__
# Use proper names for Tetrad Choices. If no name given (hunt the literature), then use the literature reference as the name.
TetradChoice = par.initialize_param(
    par.glb_param("char", thismodule, "TetradChoice",
                  "Approx_QuasiKinnersley"))

# Why are these needed?
# xorig = par.initialize_param(par.glb_param("REAL", thismodule, "xorig", "0.0"))
# yorig = par.initialize_param(par.glb_param("REAL", thismodule, "yorig", "0.0"))
# zorig = par.initialize_param(par.glb_param("REAL", thismodule, "zorig", "0.0"))
# offset = par.initialize_param(par.glb_param("REAL", thismodule, "offset", "1.0e-15"))


# Step 2: Define the Levi-Civita symbol, used with tetrads <- better description needed.
def define_LeviCivitaSymbol(DIM=-1):
    if DIM == -1:
        DIM = par.parval_from_str("DIM")

    LeviCivitaSymbol = ixp.zerorank3()
Example #26
0
# THIS MODULE: ../Tutorial-VacuumMaxwell_Flat_ID.ipynb

# Step P1: Import needed NRPy+ core modules:
import NRPy_param_funcs as par                # NRPy+: Parameter interface
import sympy as sp                            # SymPy: The Python computer algebra package upon which NRPy+ depends
import indexedexp as ixp                      # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm                # NRPy+: Reference metric support
import sys                                    # Standard Python module for multiplatform OS-level functions
from Maxwell.CommonParams import amp, lam, time # NRPy+: Common parameters for all VacuumMaxwell modules (defines amp, lam, and time)


# The name of this module ("InitialData") is given by __name__:
thismodule = __name__

# define parameter for which system to use
par.initialize_param(par.glb_param("char",thismodule,"System_to_use","System_I"))

# Initial data for toroidal dipole field
def Toroidal():
    system = par.parval_from_str(thismodule+"::System_to_use")
    DIM = par.parval_from_str("grid::DIM")

    dst_basis = par.parval_from_str("reference_metric::CoordSystem")

    # Set coordinate system to Cartesian
    par.set_parval_from_str("reference_metric::CoordSystem","Cartesian")
    rfm.reference_metric()

    global AidU, EidU, psi_ID

    x = rfm.xx_to_Cart[0]