コード例 #1
0
def check_solver(solver, inputs=list_files(max_size=20)):
    """
    Prove optimality with comparing solution with control version.
    Only for small examples, sorry. For big ones you can call is_valid()
    :param task:
    :param function(task) solver:
    :return:
    """
    for fn in inputs:
        task = read_input(fn)
        solution = solver(task)

        if not is_valid(task, solution):
            print 'ERROR: solution for {fn} is invalid: {solution}'.format(fn=fn, solution=solution)
            continue

        control_solution = bruteforce_solver(task)
        control_cost = calc_cost(task, control_solution)
        cost = calc_cost(task, solution)
        if cost != control_cost:
            msg = ('ERROR: solution for {fn} has cost={cost}, but optimal is {control_cost}:\n' +
                   '    control:{control_solution}\n' +
                   '    tested: {solution}')
            print msg.format(fn=fn, cost=cost, control_cost=control_cost,
                             control_solution=control_solution, solution=solution)
            continue

        print 'OK: solution for {fn} is optimal, cost={cost}'.format(fn=fn, cost=cost)
コード例 #2
0
def check_solver(solver, inputs=list_files(max_size=20)):
    """
    Prove optimality with comparing solution with control version.
    Only for small examples, sorry. For big ones you can call is_valid()
    :param task:
    :param function(task) solver:
    :return:
    """
    for fn in inputs:
        task = read_input(fn)
        solution = solver(task)

        if not is_valid(task, solution):
            print 'ERROR: solution for {fn} is invalid: {solution}'.format(
                fn=fn, solution=solution)
            continue

        control_solution = bruteforce_solver(task)
        control_cost = calc_cost(task, control_solution)
        cost = calc_cost(task, solution)
        if cost != control_cost:
            msg = (
                'ERROR: solution for {fn} has cost={cost}, but optimal is {control_cost}:\n'
                + '    control:{control_solution}\n' +
                '    tested: {solution}')
            print msg.format(fn=fn,
                             cost=cost,
                             control_cost=control_cost,
                             control_solution=control_solution,
                             solution=solution)
            continue

        print 'OK: solution for {fn} is optimal, cost={cost}'.format(fn=fn,
                                                                     cost=cost)
コード例 #3
0
    def __init__(self, config, climateTS=None):
        '''

        Sets up the initial spatial grid, time grid, accumulation rate, age, density, mass, stress, and temperature of the model run
        :param configName: name of json config file containing model configurations
        
        '''

        ### load in json config file and parses the user inputs to a dictionary

        # with open(configName, "r") as f:
        #     jsonString  = f.read()
        #     self.c      = json.loads(jsonString)
        self.c = config
        print('Spin run started')
        print("physics are", self.c['physRho'])
        if 'merging' not in self.c:
            self.c['merging'] = False

        ### create directory to store results. Deletes if it exists already.
        # Vincent says we do not want to remove existing directory (preferential flow?) - 4/24/19
        if os.path.exists(self.c['resultsFolder']):
            dir_exts = [
                os.path.splitext(fname)[1]
                for fname in os.listdir(self.c['resultsFolder'])
            ]
            dir_unique = list(set(dir_exts))

            CFM_exts = ['.json', '.hdf5']
            if CFM_exts and all(((elem == ".json") or (elem == '.hdf5'))
                                for elem in dir_unique):

                rmtree(self.c['resultsFolder'])
                os.makedirs(self.c['resultsFolder'])
            else:
                print(
                    'WARNING: THE DIRECTORY YOU ARE USING CONTAINS NON-CFM FILES'
                )
                print(
                    'CFM will delete all files in the results directory with .hdf5 extension'
                )
                files_in_directory = os.listdir(self.c['resultsFolder'])
                filtered_files = [
                    file for file in files_in_directory
                    if file.endswith(".hdf5")
                ]
                for file in filtered_files:
                    path_to_file = os.path.join(self.c['resultsFolder'], file)
                    os.remove(path_to_file)

        else:
            os.makedirs(self.c['resultsFolder'])

        ############################
        ##### load input files #####
        ############################
        ### temperature ###
        if climateTS != None:
            input_temp = climateTS['TSKIN']
            input_bdot = climateTS['BDOT']
            input_year_temp = input_year_bdot = climateTS['time']

        else:
            input_temp, input_year_temp = read_input(
                os.path.join(self.c['InputFileFolder'],
                             self.c['InputFileNameTemp']))
            input_bdot, input_year_bdot = read_input(
                os.path.join(self.c['InputFileFolder'],
                             self.c['InputFileNamebdot']))

        if input_temp[0] < 0.0:
            input_temp = input_temp + K_TO_C
        try:
            if self.c['spinup_climate_type'] == 'initial':
                self.temp0 = input_temp[0]
            elif self.c['spinup_climate_type'] == 'mean':
                self.temp0 = np.mean(input_temp)

        except Exception:
            print(
                "You should add key 'spinup_climate_type' to the config .json file"
            )
            print("spinup is based on mean climate of input")
            self.temp0 = np.mean(input_temp)

        ### accumulation rate ###
        try:
            if self.c['spinup_climate_type'] == 'initial':
                self.bdot0 = input_bdot[0]
            elif self.c['spinup_climate_type'] == 'mean':
                self.bdot0 = np.mean(input_bdot)
        except:
            self.bdot0 = np.mean(input_bdot)

        if 'manual_climate' in self.c:
            pass
        else:
            print(
                "Add 'manual_climate' to the json to enable specifying long-term bdot and T"
            )
            self.c['manual_climate'] = False

        if self.c[
                'manual_climate']:  # If we want to use a manually specified climate for spin up (e.g. known long-term values).
            self.temp0 = self.c[
                'deepT']  #specify deep T as mean temperature for spin up calculations (compaction,grain growth)
            self.bdot0 = self.c[
                'bdot_long']  # *1e-3/0.917 #specify long term accumulation as mean accumulation for spin up calculations (compaction,grain growth) + conversion from mmWE/yr to mIE/yr
            print('make sure "bdot_long" has units of mIE/yr!')

        ### could include others, e.g. surface density
        ############################

        ############################
        ### set up model grid ######
        ############################
        self.gridLen = int(
            (self.c['H'] - self.c['HbaseSpin']) /
            (self.bdot0 / self.c['stpsPerYear']))  # number of grid points

        gridHeight = np.linspace(self.c['H'], self.c['HbaseSpin'],
                                 self.gridLen)
        self.z = self.c['H'] - gridHeight
        self.dz = np.diff(self.z)
        self.dz = np.append(self.dz, self.dz[-1])
        self.dx = np.ones(self.gridLen)
        print('Grid length is', self.gridLen)
        ############################

        ############################
        ### if the regridding module is being used, do the
        ### initial regridding
        ############################
        # try:
        #     self.doublegrid = self.c['doublegrid']
        #     if self.c['doublegrid']:
        #         self.nodestocombine, self.z, self.dz, self.gridLen, self.dx, self.gridtrack = init_regrid(self)
        # except:
        #     self.doublegrid = False
        #     print('you should add "doublegrid" to the json')

        ############################
        ### get an initial depth/density profile based on H&L analytic solution
        ############################
        # if not self.c['initprofile']: #VV
        THL = self.temp0
        AHL = self.bdot0

        try:  #VV use Reeh corrected T
            if self.c['ReehCorrectedT'] and self.c['MELT']:
                input_snowmelt, input_year_snowmelt = read_input(
                    os.path.join(self.c['InputFileFolder'],
                                 self.c['InputFileNamemelt']))  #VV
                meanmelt = np.mean(
                    input_snowmelt
                )  # mean melt per year [mIE/yr] (units are specified in Reeh 2008)
                meanacc = self.bdot0  # mean annual accumulation [mIE/yr]
                self.SIR = min(
                    meanmelt, 0.6 * meanacc
                )  # Reeh 1991 and Reeh 2008 PMAX value is set at 0.6 melt becomes superimposed ice until it reaches 0.6 of annual acc, then runoff
                THL = self.temp0 + 26.6 * self.SIR
                THL = min(THL, 273.15)
            elif (self.c['ReehCorrectedT'] and not self.c['MELT']):
                print(
                    '"ReehCorrectedT" is True but melt is not turned on. That is weird. Exiting.'
                )
                sys.exit()

        except:
            print(
                'add "ReehCorrectedT" to .json to enable melt-corrected temperature'
            )
            self.c['ReehCorrectedT'] = False
            pass

        self.age, self.rho = hl_analytic(self.c['rhos0'], self.z, THL,
                                         AHL)  # self.age is in age in seconds

        # try:
        self.doublegrid = self.c['doublegrid']
        if self.c['doublegrid']:
            ### VV change 09/12/2020: surface node thicker to avoid deepening of transition depth ###
            dznew = 917 / self.rho * self.dz  #adjust ice equivalent thickness of nodes to a thickness approximated by HL analytic
            znew = np.append(0, np.cumsum(dznew)[0:-1])  #adjust z accordingly
            icut = np.where(znew > self.c['H'] -
                            self.c['HbaseSpin'])[0][0]  #new lower index
            self.z = znew[0:icut]  #restrict firn column to domain limits
            self.dz = dznew[0:icut]  #restrict firn column to domain limits
            self.gridLen = len(self.z)  #new gridlen
            self.dx = np.ones(self.gridLen)  #adjust dx
            # Recompute HL analytic on the updated profile #
            self.age, self.rho = hl_analytic(
                self.c['rhos0'], self.z, THL,
                AHL)  # self.age is in age in seconds
            # Doublegrid routine #
            self.z, self.dz, self.gridLen, self.dx, self.gridtrack = init_regrid22(
                self)  #VV grid22
            # Recompute HL analytic on the regridded profile #
            self.age, self.rho = hl_analytic(
                self.c['rhos0'], self.z, THL,
                AHL)  # self.age is in age in seconds
            print('After doublegrid, grid length is ', self.gridLen)
            # print('z ', self.z[-5:])

        # except:
        #     self.doublegrid = False
        #     print('you should add "doublegrid" to the json')

        # if self.c['initprofile']: # VV filler values to avoid model blow up if THL and AHL are out of HL calibration range
        # self.age = S_PER_YEAR*100*np.ones_like(self.dz) #VV this does not matter as it is rectified when we initialise profie below
        # self.rho = 500*np.ones_like(self.dz)#VV this does not matter as it is rectified when we initialise profile
        ############################

        ############################
        ### set up time stepping
        if self.c[
                'AutoSpinUpTime']:  # automatic, based on time that it will take for a parcel to get to 850 kg m^-3
            try:
                zz = np.min(self.z[self.rho > 850.0])
                self.years = int(zz / self.bdot0)
            except ValueError:
                print("auto spin up error; using spin up time from json")
                self.years = self.c[
                    'yearSpin']  # number of years to spin up for
        else:  # based on time taken to spin up in the config file.
            self.years = self.c['yearSpin']  # number of years to spin up for

        dt1 = S_PER_YEAR / self.c['stpsPerYear']
        self.stp = int(self.years * S_PER_YEAR / dt1)
        self.t = 1.0 / self.c['stpsPerYear']  # years per time step
        self.dt = dt1 * np.ones(self.stp)
        ############################

        ############################
        ### Initial and boundary conditions
        ############################
        ### Surface temperature for each time step
        self.Ts = self.temp0 * np.ones(self.stp)

        if self.c[
                'SeasonalTcycle']:  #impose seasonal temperature cycle of amplitude 'TAmp'
            if self.c['SeasonalThemi'] == 'north':
                self.Ts = self.Ts - self.c['TAmp'] * (
                    np.cos(2 * np.pi * np.linspace(0, self.years, self.stp))
                )  # This is for Greenland

            elif self.c['SeasonalThemi'] == 'south':
                if self.c['coreless']:
                    self.Ts = self.Ts + self.c['TAmp'] * (
                        np.cos(
                            2 * np.pi * np.linspace(0, self.years, self.stp)) +
                        0.3 * np.cos(
                            4 * np.pi * np.linspace(0, self.years, self.stp))
                    )  # Coreless winter, from Orsi
                else:
                    self.Ts = self.Ts + self.c['TAmp'] * (
                        np.cos(2 * np.pi * np.linspace(0, self.years, self.stp)
                               ))  # This is basic for Antarctica
            else:
                print(
                    'You have turned on the SeasonalTcycle, but you do not have'
                )
                print(
                    'the hemisphere selected. Exiting. (set to south or north')
                sys.exit()

        ### initial temperature profile
        # init_Tz         = self.temp0 * np.ones(self.gridLen)
        self.T_mean = self.temp0 * np.ones(self.stp)
        self.Tz = self.temp0 * np.ones(self.gridLen)
        self.T50 = np.mean(self.Tz[self.z < 50])
        self.T10m = np.mean(self.T_mean)
        if self.c['ReehCorrectedT']:
            self.Tz = self.Tz + 26.6 * self.SIR  # temperature correction accounting for latent heat, Reeh 1991 (5) Reeh 2008 (16)
            self.Tz = np.minimum(self.Tz, 273.15)
            self.T_mean = np.mean(self.Tz[self.z < 50])
            self.T10m = self.T_mean

        try:
            ctest = self.c['conductivity']
        except:
            self.c['conductivity'] = 'Anderson'

        ### Accumulation rate for each time step
        self.bdotSec0 = self.bdot0 / S_PER_YEAR / self.c[
            'stpsPerYear']  # accumulation (m I.E. per second)
        self.bdotSec = self.bdotSec0 * np.ones(
            self.stp)  # vector of accumulation at each time step
        self.bdot_mean = np.ones_like(self.dz) * self.bdot0
        self.bdot_av = self.bdot0 * np.ones(
            self.stp)  #The long-term mean accumulation rate

        ### Surface isotope values for each time step
        if self.c['isoDiff']:
            self.spin = True
            self.Isotopes = {}  #dictionary of class instances
            self.iso_out = {}  # outputs for each isotope
            self.Isoz = {}  # depth profile of each isotope, at each time step
            self.Iso_sig2_z = {}  # diffusion length profile
            self.iso_sig2_out = {}

            for isotope in self.c['iso']:
                self.Isotopes[isotope] = isotopeDiffusion(
                    self.spin, self.c, isotope, self.stp, self.z)

        ### Surface Density
        self.rhos0 = self.c['rhos0'] * np.ones(
            self.stp
        )  # could configure this so that user specifies vector of some noise

        ### initial mass, stress, and mean accumulation rate
        self.mass = self.rho * self.dz
        self.sigma = self.mass * self.dx * GRAVITY
        self.sigma = self.sigma.cumsum(axis=0)
        self.mass_sum = self.mass.cumsum(axis=0)

        ### longitudinal strain rate
        if self.c['strain']:
            self.du_dx = np.zeros(self.gridLen)
            self.du_dx[1:] = self.c['du_dx'] / (S_PER_YEAR)

        ### initial grain growth (if specified in config file)
        if self.c['physGrain']:
            # if self.c['calcGrainSize']:
            #     r02 = surfacegrain(self,0) #VV
            #     self.r2 = r02 * np.ones(self.gridLen)
            # else:
            self.r2 = np.linspace(self.c['r2s0'], (6 * self.c['r2s0']),
                                  self.gridLen)
        else:
            self.r2 = None

        ### "temperature history" if using Morris physics
        if self.c['physRho'] == 'Morris2014':
            if 'QMorris' not in self.c:
                print('Add "QMorris" to the .json. CFM is setting to 110e3')
                self.c['QMorris'] = 110.0e3
            # initial temperature history function (units seconds)
            self.Hx = np.exp(-1 * self.c['QMorris'] /
                             (R * self.Tz)) * (self.age + self.dt[0])
            self.THist = True
        else:
            self.THist = False

        self.LWC = np.zeros_like(self.z)
        self.MELT = False
        self.c['LWCheat'] = 'enthalpy'
        ### values for Goujon physics
        if self.c['physRho'] == 'Goujon2003':
            self.Gamma_Gou = 0
            self.Gamma_old_Gou = 0
            self.Gamma_old2_Gou = 0
            self.ind1_old = 0
        #######################

        #######################
        try:
            if self.c['no_densification']:
                print('CAUTION: densification if OFF!')
            else:
                pass
        except:
            # print('no_densification not in .json; setting to false')
            self.c['no_densification'] = False
コード例 #4
0
            state = state.parent
            continue

        if state.is_all_covered():
            solution.store_result(state)
            state = state.negate()  # try to deselect the current set or rollback to the parent state
            continue

        if state.get_optimistic_cost() >= solution.best_cost:
            if now() > deadline:  # we get to this place often enough to stop in time,
                                  # and we get to it not on the each iteration, so we will not check the time too frequently
                return solution
            state = state.negate()  # try to deselect the current set or rollback to the parent state
            continue

        state = state.next_child()

    solution.proven_as_optimal = True  # we have not terminated on timeout, so we have explored all the tree
    return solution


if __name__ == '__main__':
    from reader import read_input
    for fn in ['sc_157_0', 'sc_330_0', 'sc_1000_11', 'sc_5000_1', 'sc_10000_5', 'sc_10000_2']:
        print '=== {} ==='.format(fn)
        task = read_input('sc_45_0')
        solution = deep_search(task, timeout=0.5*60)
        print solution, solution.metrics
    #from profile import run
    #run('deep_search(task, timeout=120)', sort=2)  # sort - 2 cumtime, 1 - totime
コード例 #5
0
#PART-1: SETUP
#-------------------------------------------------------------------------
writer.write_header()

#CHECK THAT A FILE WAS PROVIDED BY USER
if(len(argv)!=2):	raise ValueError("NO INPUT FILE")

#SB=SNOWBALL (i.e DICTIONARY THAT ACCUMULATED EVERYTHING)(SB != sackville baggins) 
SB={};		
SB['input_file']=argv[1]

##GET RUN PARAMETER 
util.get_run_parameters(SB)

#READ INPUT FILES
reader.read_input(SB)		#READ INPUT FILE AND ADD INFO TO SB
reader.read_pot_file(SB)	#READ NN FILE AND ADD INFO TO SB 
reader.read_database(SB);	#READ DATABASES AND ADD INFO TO SB 

#WRITE POSCAR IF DESIRED 
if(SB['dump_poscars']):	util.dump_poscars(SB)() #MOVE TO read_data

#COMPUTE NEIGHBORLIST (NBL) AND LSP FOR ALL STRUCTURES
util.compute_all_nbls(SB)	
util.compute_all_lsps(SB)	
util.partition_data(SB)

if(SB['normalize_gi']):	
	raise Exception("ERROR: NORMALIZATION OF Gi IS CURRENTLY DISABLED")
	util.collect_all_lsp(SB) 	#MAKE A SINGLE MATRIX WITH ALL GI
	util.normalize_lsp(SB)
コード例 #6
0
ファイル: firn_density_spin.py プロジェクト: vgkinis/iso_cfm
    def __init__(self, configName):
        '''
        Sets up the initial spatial grid, time grid, accumulation rate, age, density, mass, stress, and temperature of the model run
        :param configName: name of json config file containing model configurations
        '''

        # load in json config file and parses the user inputs to a dictionary
        with open(configName, "r") as f:
            jsonString = f.read()
            self.c = json.loads(jsonString)

        print('Spin run started')
        print("physics are", self.c['physRho'])

        # create directory to store results. Deletes if it exists already.
        if os.path.exists(self.c['resultsFolder']):
            rmtree(self.c['resultsFolder'])
        os.makedirs(self.c['resultsFolder'])

        ##### load input files #####
        ### temperature
        input_temp, input_year_temp = read_input(self.c['InputFileNameTemp'])
        if input_temp[0] < 0.0:
            input_temp = input_temp + K_TO_C
        self.temp0 = input_temp[0]  #Make sure that this is what we want!
        # self.temp0 = mean(input_temp[0:12]) #Make sure that this is what we want!

        ### accumulation rate
        input_bdot, input_year_bdot = read_input(self.c['InputFileNamebdot'])
        self.bdot0 = input_bdot[0]  #Make sure that this is what we want!

        ### could include others, e.g. surface density
        ##########

        ##### set up model grid
        self.gridLen = int(
            (self.c['H'] - self.c['HbaseSpin']) /
            (self.bdot0 / self.c['stpsPerYearSpin']))  # number of grid points
        gridHeight = np.linspace(self.c['H'], self.c['HbaseSpin'],
                                 self.gridLen)
        self.z = self.c['H'] - gridHeight
        self.dz = np.diff(self.z)
        self.dz = np.append(self.dz, self.dz[-1])
        self.dx = np.ones(self.gridLen)

        ##### get an initial depth/density profile based on H&L analytic solution
        THL = input_temp[0]
        AHL = input_bdot[0]
        self.age, self.rho = hl_analytic(self.c['rhos0'], self.z, THL,
                                         AHL)  # self.age is in age in seconds

        ###### get initial isotope diffusion length using HL analytical, returns a dictionary with keys "D", "18", "17"
        self.iso_sigma = iso_diffusion_vas.Sigma(P = self.c['P_atm'], rho_o = self.c['rhos0'], \
            rho_co = self.c['rho_co_iso']).analytical_HL(rho_array = self.rho, T = THL, accum_ice = AHL)

        print(self.iso_sigma['D'][0])
        print('blablabla')

        # plt.figure(1)
        # plt.plot(self.z, self.iso_sigma['D'])
        # plt.plot(self.z, self.iso_sigma['18'])
        # plt.plot(self.z, self.iso_sigma['17'])
        # plt.show()

        ##### set up time stepping
        if self.c[
                'AutoSpinUpTime']:  # automatic, based on time that it will take for a parcel to get to 850 kg m^-3
            try:
                zz = np.min(self.z[self.rho > 850.0])
                self.years = int(zz / self.bdot0)
            except ValueError:
                print("auto spin up error; using spin up time from json")
                self.years = self.c[
                    'yearSpin']  # number of years to spin up for
        else:  # based on time taken to spin up in the config file.

            self.years = self.c['yearSpin']  # number of years to spin up for

        self.dt = S_PER_YEAR / self.c['stpsPerYearSpin']
        self.stp = int(self.years * S_PER_YEAR / self.dt)
        self.t = 1.0 / self.c['stpsPerYearSpin']  # years per time step

        # self.stp        = int(self.years * self.c['stpsPerYearSpin']) # total number of time steps, as integer
        # self.dt         = self.years * S_PER_YEAR / self.stp # size of time steps, seconds
        # # self.dts        = self.years / self.stp # size of time step, years
        # self.t          = 1.0 / self.c['stpsPerYearSpin'] # years per time step

        # print 'dts', self.dts
        # print 't', self.t
        #####

        ### Surface temperature for each time step
        self.Ts = self.temp0 * np.ones(self.stp)
        self.T_mean = np.mean(self.Ts)  # MS 3/7/17: is this what we want?

        if self.c[
                'SeasonalTcycle']:  #impose seasonal temperature cycle of amplitude 'TAmp', including coreless winter (Orsi)
            self.Ts = self.Ts + self.c['TAmp'] * (
                np.cos(2 * np.pi * np.linspace(0, self.years, self.stp)) +
                0.3 * np.cos(4 * np.pi * np.linspace(0, self.years, self.stp)))
        # initial temperature profile
        init_Tz = input_temp[0] * np.ones(self.gridLen)

        ### Accumulation rate for each time step
        self.bdotSec0 = self.bdot0 / S_PER_YEAR / self.c[
            'stpsPerYearSpin']  # accumulation (m I.E. per second)
        self.bdotSec = self.bdotSec0 * np.ones(
            self.stp)  # vector of accumulation at each time step

        ### Surface isotope values for each time step
        if self.c['isoDiff']:
            try:
                input_iso, input_year_iso = read_input(
                    self.c['InputFileNameIso'])
                del_s0 = input_iso[0]
            except:
                print(
                    'No external file for surface isotope values found, but you specified in the config file that isotope diffusion is on. The model will generate its own synthetic isotope data for you.'
                )
                del_s0 = -50.0

            self.del_s = del_s0 * np.ones(self.stp)
            init_del_z = del_s0 * np.ones(self.gridLen)
            self.del_z = init_del_z
        else:
            self.del_s = None
            init_del_z = None

        ### Surface Density
        self.rhos0 = self.c['rhos0'] * np.ones(self.stp)
        # could configure this so that user specifies vector of surface elevation
        # could add noise too

        ### set up initial mass, stress, and mean accumulation rate
        self.mass = self.rho * self.dz
        self.sigma = self.mass * self.dx * GRAVITY
        self.sigma = self.sigma.cumsum(axis=0)
        self.mass_sum = self.mass.cumsum(axis=0)
        self.bdot_mean = (np.concatenate(
            ([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] /
             (self.age[1:] * RHO_I / self.t)))
                          ) * self.c['stpsPerYear'] * S_PER_YEAR

        ### set up longitudinal strain rate
        if self.c['strain']:
            self.du_dx = np.zeros(self.gridLen)
            self.du_dx[1:] = self.c['du_dx'] / (S_PER_YEAR)

        ### set up initial temperature grid as well as a class to handle heat/isotope diffusion
        # self.diffu      = Diffusion(self.z, self.stp, self.gridLen, init_Tz, init_del_z) # is this the best way to do this?
        self.Tz = init_Tz
        self.T_mean = self.Tz[0]
        self.T10m = self.T_mean

        ### set up initial grain growth (if specified in config file)
        if self.c['physGrain']:
            if self.c['calcGrainSize']:
                r02 = -2.42e-9 * (
                    self.Ts) + 9.46e-7  # where does this equation come from?
                self.r2 = r02 * np.ones(self.gridLen)
            else:
                self.r2 = np.linspace(self.c['r2s0'], (6 * self.c['r2s0']),
                                      self.gridLen)
        else:
            self.r2 = None

        ### set up "temperature history" if using Morris physics
        if self.c['physRho'] == 'Morris2014':
            # initial temperature history function (units seconds)
            self.Hx = np.exp(-110.0e3 / (R * init_Tz)) * (self.age + self.dt)
            self.THist = True
        else:
            self.THist = False

        print('Ts', self.Ts[-4:])
        print('bdot_s', self.bdotSec[-4:])
        print('dt', self.dt)
コード例 #7
0
    def __init__(self, spin, config, isotope, stp, z, modeltime=None):
        '''
        Initialize Isotope diffusion class.
        '''
        self.c = config
        self.isotope = isotope

        try:
            fn = os.path.splitext(self.c['InputFileNameIso'])
            isofile = fn[0] + '_{}'.format(self.isotope) + fn[1]
            print(isofile)
            if isotope == 'NoDiffusion':
                isofile = fn[0] + '_dD' + fn[1]
            input_iso, input_year_iso = read_input(
                os.path.join(self.c['InputFileFolder'], isofile))

            if spin:
                if self.c['spinup_climate_type'] == 'initial':
                    del_s0 = input_iso[0]
                elif self.c['spinup_climate_type'] == 'mean':
                    del_s0 = np.mean(input_iso)

                self.del_s = del_s0 * np.ones(stp)
                self.del_z = del_s0 * np.ones_like(z)
                self.iso_sig2_s = 0 * np.zeros(stp)
                self.iso_sig2_z = 0 * np.ones_like(z)

            elif not spin:
                del_z_init = read_init(self.c['resultsFolder'],
                                       self.c['spinFileName'],
                                       'IsoSpin_{}'.format(self.isotope))
                iso_sig2_init = read_init(self.c['resultsFolder'],
                                          self.c['spinFileName'],
                                          'iso_sig2_{}'.format(self.isotope))
                self.del_z = del_z_init[1:]
                self.iso_sig2_z = iso_sig2_init[1:]
                Isf = interpolate.interp1d(
                    input_year_iso,
                    input_iso,
                    self.c['int_type'],
                    fill_value='extrapolate')  # interpolation function
                self.del_s = Isf(
                    modeltime)  # isotopes interpolated to modeltime
                self.iso_sig2_s = np.zeros(stp)

        except:
            print(
                'No external file for surface isotope values found ({}), but you specified in the config file that isotope diffusion is on. The model will generate its own synthetic isotope data for you.'
                .format(self.isotope))
            print(
                'Double check that file name is correct. New module will add d18O or dD to filename for input.'
            )

            if spin:
                del_s0 = -50.0
                print(
                    'Currently this is -50 per mil, regardless of isotope you choose.'
                )
                self.del_s = del_s0 * np.ones(stp)
                self.del_z = del_s0 * np.ones_like(z)
                self.iso_sig2_s = 0 * np.zeros(stp)
                self.iso_sig2_z = 0 * np.ones_like(z)

            elif not spin:
                del_z_init = read_init(self.c['resultsFolder'],
                                       self.c['spinFileName'],
                                       'IsoSpin_{}'.format(self.isotope))
                iso_sig2_init = read_init(self.c['resultsFolder'],
                                          self.c['spinFileName'],
                                          'iso_sig2_{}'.format(self.isotope))
                self.del_z = del_z_init[1:]
                self.iso_sig2_z = iso_sig2_init[1:]
                ar1 = 0.9  # red noise memory coefficient
                std_rednoise = 2  # red noise standard deviation
                self.del_s = std_rednoise * np.random.randn(stp)  # white noise
                for x in range(1, stp):
                    self.del_s[x] = self.del_s[x - 1] * ar1 + np.random.randn(
                    )  # create red noise from white
                self.del_s = self.del_s - 50
                self.iso_sig2_s = np.zeros(stp)

        if 'site_pressure' not in self.c:
            print('site_pressure is not in .json; defaulting to 1013.25')
            self.c['site_pressure'] = 1013.25
コード例 #8
0
    def __init__(self, configName):
        '''
        Sets up the initial spatial grid, time grid, accumulation rate, age, density, mass, stress, and temperature of the model run
        :param configName: name of json config file containing model configurations
        '''

        ### load in json config file and parses the user inputs to a dictionary
        self.spin=False
        with open(configName, "r") as f:
            jsonString  = f.read()
            self.c      = json.loads(jsonString)

        print('Spin run started')
        print("physics are", self.c['physRho'])
        try:
            print('Merging is:',self.c["merging"])
        except Exception:
            print('"merging" missing from .json fields')
            pass

        ### create directory to store results. Deletes if it exists already.
        # Vincent says we do not want to remove existing (preferential flow?) - 4/24/19
        if os.path.exists(self.c['resultsFolder']):
            rmtree(self.c['resultsFolder'])
        os.makedirs(self.c['resultsFolder'])

        ############################
        ##### load input files #####
        ############################
        ### temperature
        input_temp, input_year_temp = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNameTemp']))
        if input_temp[0] < 0.0:
            input_temp              = input_temp + K_TO_C
        try:
            if self.c['spinup_climate_type']=='initial':
                self.temp0                  = input_temp[0]
            elif self.c['spinup_climate_type']=='mean':
                self.temp0                  = np.mean(input_temp)

        except Exception:
            print("You should add key 'spinup_climate_type' to the config .json file")
            print("spinup is based on mean climate of input")
            self.temp0                  = np.mean(input_temp)
        
        ### accumulation rate
        input_bdot, input_year_bdot = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNamebdot']))
        
        try:
            if self.c['spinup_climate_type']=='initial':
                self.bdot0      = input_bdot[0]
            elif self.c['spinup_climate_type']=='mean':
                self.bdot0      = np.mean(input_bdot)
        except:
            self.bdot0      = np.mean(input_bdot)
        
        try:
            if self.c['manual_climate']: # If we want to use a manually specified climate for spin up (e.g. known long-term values). 
                self.temp0 = self.c['deepT'] #specify deep T as mean temperature for spin up calculations (compaction,grain growth)
                self.bdot0 = self.c['bdot_long']# *1e-3/0.917 #specify long term accumulation as mean accumulation for spin up calculations (compaction,grain growth) + conversion from mmWE/yr to mIE/yr
                print('make sure "bdot_long" has units of mIE/yr!')
        except Exception:
            print("Add 'manual_climate' to the json to enable specifying bdot and T")
        
        # if self.c['initprofile']: #pretty sure that this does not need to depend on init profile?
            ### Vincent's code
            # try:
            #     if self.c['singleleap'] or self.c['singlenormal']: #VV If we use the initprofile but the input forcing data does not cover an entire year
            #         self.temp0 = self.c['deepT'] #VV use deep T as mean temperature for spin up calculations (compaction,grain growth)
            #         self.bdot0 = self.c['bdot_long']*1e-3/0.917 #VV use long term accumulation as mean accumulation for spin up calculations (compaction,grain growth) + conversion from mmWE/yr to mIE/yr
            # except Exception:
            #     print("you are using an initial profile for spinup,")
            #     print("but you do not have 'singleleap' or 'singlenormal' in the .json")

        
        print('bdot0', self.bdot0)
        print('temp0', self.temp0)
        ### could include others, e.g. surface density
        ############################

        ############################
        ### set up model grid ######
        ############################
        self.gridLen    = int((self.c['H'] - self.c['HbaseSpin']) / (self.bdot0 / self.c['stpsPerYearSpin'])) # number of grid points
        gridHeight      = np.linspace(self.c['H'], self.c['HbaseSpin'], self.gridLen)
        self.z          = self.c['H'] - gridHeight
        self.dz         = np.diff(self.z) 
        self.dz         = np.append(self.dz, self.dz[-1])
        self.dx         = np.ones(self.gridLen)
        print('Grid length is', self.gridLen)
        ############################

        ############################
        ### if the regridding module is being used, do the
        ### initial regridding
        ############################
        try:
            self.doublegrid = self.c['doublegrid']
            if self.c['doublegrid']:
                self.nodestocombine, self.z, self.dz, self.gridLen, self.dx, self.gridtrack = init_regrid(self)
        except:
            self.doublegrid = False
            print('you should add "doublegrid" to the json')

        ############################
        ### get an initial depth/density profile based on H&L analytic solution
        ############################
        # if not self.c['initprofile']: #VV
        THL                 = self.temp0
        AHL                 = self.bdot0
        try: #VV use Reeh corrected T
            if self.c['Reeh91'] and self.c['MELT']:
                input_snowmelt, input_year_snowmelt = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNamemelt'])) #VV
                meanmelt = np.mean(input_snowmelt) # mean melt per year [mIE/yr] (units are specified in Reeh 2008)
                meanacc  = self.bdot0 # mean annual accumulation [mIE/yr]
                #SIR_step = np.minimum(input_snowmelt,0.6*meanacc) # Reeh 1991 and Reeh 2008 PMAX value is set at 0.6 melt becomes superimposed ice until it reaches 0.6 of annual acc, then runoff
                #SIR = np.mean(SIR_step) # annual mean superimposed ice formation
                SIR = min(meanmelt,0.6*meanacc)
                THL = self.temp0 + 26.6*SIR
                THL = min(THL,273.15)
        except:
            print('add "Reeh91" to .json to enable melt-corrected temperature')
            pass
        self.age, self.rho     = hl_analytic(self.c['rhos0'], self.z, THL, AHL) # self.age is in age in seconds
        # elif self.c['initprofile'] == True: # VV we have an initial temperature and density profile
            # Just avoid the model to blow up because it has no age and rho variables, real values are given below
            # self.age = S_PER_YEAR*100*np.ones_like(self.dz) #VV this does not matter as it is rectified when we initialise profie below
            # self.rho = 500*np.ones_like(self.dz)#VV this does not matter as it is rectified when we initialise profile
        ############################

        ############################
        ### set up time stepping
        if self.c['AutoSpinUpTime']: # automatic, based on time that it will take for a parcel to get to 850 kg m^-3
            try:
                zz          = np.min(self.z[self.rho > 850.0])
                self.years  = int(zz / self.bdot0)
            except ValueError:
                print("auto spin up error; using spin up time from json")
                self.years = self.c['yearSpin'] # number of years to spin up for
        else: # based on time taken to spin up in the config file.
            self.years = self.c['yearSpin'] # number of years to spin up for
        
        self.dt     = S_PER_YEAR / self.c['stpsPerYearSpin']
        self.stp    = int(self.years*S_PER_YEAR/self.dt)
        self.t      =  1.0 / self.c['stpsPerYearSpin'] # years per time step
        ############################

        ############################
        ### Initial and boundary conditions
        ############################
        ### Surface temperature for each time step
        self.Ts         = self.temp0 * np.ones(self.stp)

        if self.c['SeasonalTcycle']: #impose seasonal temperature cycle of amplitude 'TAmp'           
            if self.c['SeasonalThemi'] == 'north':
                self.Ts         = self.Ts - self.c['TAmp'] * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp))) # This is for Greenland

            elif self.c['SeasonalThemi'] == 'south':
                if self.c['coreless']:
                    self.Ts     = self.Ts + self.c['TAmp'] * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp)) + 0.3 * np.cos(4 * np.pi * np.linspace(0, self.years, self.stp))) # Coreless winter, from Orsi
                else:
                    self.Ts     = self.Ts + self.c['TAmp'] * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp))) # This is basic for Antarctica
            else:
                print('You have turned on the SeasonalTcycle, but you do not have')
                print('the hemisphere selected. Exiting. (set to south or north')
                sys.exit()

        ### initial temperature profile
        # init_Tz       = input_temp[0] * np.ones(self.gridLen)
        init_Tz         = np.mean(self.Ts) * np.ones(self.gridLen)

        ### Accumulation rate for each time step
        self.bdotSec0   = self.bdot0 / S_PER_YEAR / self.c['stpsPerYearSpin'] # accumulation (m I.E. per second)
        self.bdotSec    = self.bdotSec0 * np.ones(self.stp) # vector of accumulation at each time step

        ### Surface isotope values for each time step
        if self.c['isoDiff']:
            try:
                input_iso, input_year_iso = read_input(self.c['InputFileNameIso'])
                del_s0  = input_iso[0]
            except:
                print('No external file for surface isotope values found, but you specified in the config file that isotope diffusion is on. The model will generate its own synthetic isotope data for you.')
                del_s0  = -50.0

            self.del_s  = del_s0 * np.ones(self.stp)
            init_del_z  = del_s0 * np.ones(self.gridLen)
            self.del_z  = init_del_z
        else:
            self.del_s  = None
            init_del_z  = None    
        
        ### Surface Density
        self.rhos0      = self.c['rhos0'] * np.ones(self.stp)
        # could configure this so that user specifies vector of surface elevation
        # could add noise too

        ### initial mass, stress, and mean accumulation rate
        self.mass       = self.rho * self.dz
        self.sigma      = self.mass * self.dx * GRAVITY
        self.sigma      = self.sigma.cumsum(axis = 0)
        self.mass_sum   = self.mass.cumsum(axis = 0)
        #VVself.bdot_mean  = (np.concatenate(([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] / (self.age[1:] * RHO_I / self.t)))) * self.c['stpsPerYear'] * S_PER_YEAR

        ### Mean temperatures and accumulation rates #VV ###
        ### MS: commented out for now 10/4/18
        # if self.c['initprofile']:
        #     self.T_av = self.c['Ts_long'] * np.ones(self.stp) # If we use initial profile, Ts_long is best guess for Tav
        #     self.bdot_av = self.c['bdot_long']*1e-3/0.917 * np.ones(self.stp) # If we use initial profile, bdotlong is best guess for bdot_av + conversion from mmWE/yr to mIE/yr
        #     self.bdot_mean = np.ones_like(self.dz)*self.c['bdot_long']*1e-3/0.917 # Also best guess for bdot_mean
        # else:
        self.T_av = self.temp0 * np.ones(self.stp) #VV This is to be used instead of T10m
        self.bdot_av = self.bdot0* np.ones(self.stp) #VV 
        self.bdot_mean  = (np.concatenate(([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] / (self.age[1:] * RHO_I / self.t)))) * self.c['stpsPerYear'] * S_PER_YEAR #VV

        ### longitudinal strain rate
        if self.c['strain']:
            self.du_dx      = np.zeros(self.gridLen)
            self.du_dx[1:]  = self.c['du_dx']/(S_PER_YEAR)
        
        ### initial temperature grid 
        self.Tz         = init_Tz
        self.T_mean     = np.mean(self.Tz[self.z<50])
        self.T10m       = self.T_mean
        
        ### VV addition
#         print('self.Tz[0:5] no Reeh:',self.Tz[0:5])
#         
#         ##VV Correction of temperature profile with latent heat release from meltwater, following Reeh 1991 parameterisation ##
#         try:
#             if self.c['Reeh91'] and self.c['MELT']:
#                 input_snowmelt, input_year_snowmelt = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNamemelt'])) #VV
#                 meanmelt = np.mean(input_snowmelt) # mean melt per year [mIE/yr] (units are specified in Reeh 2008)
#                 meanacc  = self.bdot0 # mean annual accumulation [mIE/yr]
#                 #SIR_step = np.minimum(input_snowmelt,0.6*meanacc) # Reeh 1991 and Reeh 2008 PMAX value is set at 0.6 melt becomes superimposed ice until it reaches 0.6 of annual acc, then runoff
#                 #SIR = np.mean(SIR_step) # annual mean superimposed ice formation
#                 
#                 SIR = min(meanmelt,0.6*meanacc)
#                     
#                 self.Tz         = init_Tz + 26.6*SIR # Correction of temperatures taking into account latent heat, Reeh 1991 (5) Reeh 2008 (16)
#                 self.Tz         = np.minimum(self.Tz,273.15)
#                 self.T_mean     = np.mean(self.Tz[self.z<50])
#                 self.T10m       = self.T_mean
#                 print('self.Tz[0:5] Reeh:',self.Tz[0:5])
#         except:
#             pass
        ### end VV addition
        
        ### initial grain growth (if specified in config file)
        if self.c['physGrain']:
            if self.c['calcGrainSize']:
                r02 = surfacegrain(self,0) #VV
                self.r2 = r02 * np.ones(self.gridLen)
            else:
                self.r2 = np.linspace(self.c['r2s0'], (6 * self.c['r2s0']), self.gridLen)
        else:
            self.r2 = None

        ### "temperature history" if using Morris physics
        if self.c['physRho']=='Morris2014':
            # initial temperature history function (units seconds)
            self.Hx     = np.exp(-110.0e3/(R*init_Tz))*(self.age+self.dt)
            self.THist  = True
        else:
            self.THist  = False

        self.LWC = np.zeros_like(self.z)
        self.MELT = False
コード例 #9
0
def load_strain(self, spin=False):
    '''
    Load strain rate inputs for spin-up and main run. Depending on the number of data rows in the strain input file, the
    input is taken as (1-valued) the divergence rate, (2-valued) the principal horizontal strain rates or (3-valued) the
    horizontal strain rate components eps_xx, eps_yy and eps_xy. 
    
    Falk Oraschewski, 17.05.2022
    
    :param self: 
    :param spin: 
    
    :return self.eps_eff_hor_2, self.eps_divergence, self.c: 
    '''

    int_type = self.c['int_type']

    input_eps, input_year_eps, input_eps_full, input_year_eps_full = read_input(
        os.path.join(self.c['InputFileFolder'], self.c['InputFileNameStrain']))
    if np.ndim(input_eps) == 1:
        if spin:
            if self.c['spinup_climate_type'] == 'initial':
                self.eps_divergence = input_eps[0] * np.ones(self.gridLen)
            else:
                self.eps_divergence = np.mean(input_eps) * np.ones(
                    self.gridLen)
        else:
            print(
                'Single valued strain rate input is taken as horizontal divergence rates. Strain softening is deactivated.'
            )
            dusf = interpolate.interp1d(input_year_eps,
                                        input_eps,
                                        int_type,
                                        fill_value='extrapolate')
            self.eps_divergence = dusf(self.modeltime)
        self.c['strain_softening'] = False  # Deactivate strain softening
        self.eps_eff_hor_2 = np.zeros_like(
            self.eps_divergence
        )  # Create empty effective horizontal strain rate.

    elif np.min(np.shape(input_eps)) == 2:
        input_eps_1, input_eps_2 = input_eps[0, :], input_eps[1, :]
        if spin:
            if self.c['spinup_climate_type'] == 'initial':
                eps_1 = input_eps_1[0] * np.ones(self.gridLen)
                eps_2 = input_eps_2[0] * np.ones(self.gridLen)
            else:
                print(
                    '2-valued strain rate input is taken as principal horizontal strain rates.'
                )
                eps_1 = np.mean(input_eps_1) * np.ones(self.gridLen)
                eps_2 = np.mean(input_eps_2) * np.ones(self.gridLen)
        else:
            d1sf = interpolate.interp1d(input_year_eps,
                                        input_eps_1,
                                        int_type,
                                        fill_value='extrapolate')
            d2sf = interpolate.interp1d(input_year_eps,
                                        input_eps_2,
                                        int_type,
                                        fill_value='extrapolate')
            eps_1 = d1sf(self.modeltime)
            eps_2 = d2sf(self.modeltime)
        self.eps_eff_hor_2 = (eps_1**2 + eps_2**2) / 2
        self.eps_divergence = -(eps_1 + eps_2)

    elif np.min(np.shape(input_eps)) == 3:
        input_eps_xx, input_eps_yy, input_eps_xy = input_eps[0, :], input_eps[
            1, :], input_eps[2, :]
        if spin:
            if self.c['spinup_climate_type'] == 'initial':
                eps_xx = input_eps_xx[0] * np.ones(self.gridLen)
                eps_yy = input_eps_yy[0] * np.ones(self.gridLen)
                eps_xy = input_eps_xy[0] * np.ones(self.gridLen)
            else:
                print(
                    '3-valued strain rate input is taken as the horizontal components eps_xx, eps_yy and eps_xy in that order.'
                )
                eps_xx = np.mean(input_eps_xx) * np.ones(self.gridLen)
                eps_yy = np.mean(input_eps_yy) * np.ones(self.gridLen)
                eps_xy = np.mean(input_eps_xy) * np.ones(self.gridLen)
        else:
            dxxsf = interpolate.interp1d(input_year_eps,
                                         input_eps_xx,
                                         int_type,
                                         fill_value='extrapolate')
            dyysf = interpolate.interp1d(input_year_eps,
                                         input_eps_yy,
                                         int_type,
                                         fill_value='extrapolate')
            dxysf = interpolate.interp1d(input_year_eps,
                                         input_eps_xy,
                                         int_type,
                                         fill_value='extrapolate')
            eps_xx = dxxsf(self.modeltime)
            eps_yy = dyysf(self.modeltime)
            eps_xy = dxysf(self.modeltime)
        self.eps_eff_hor_2 = (eps_xx**2 + eps_yy**2 + 2 * eps_xy**2) / 2
        self.eps_divergence = -(eps_xx + eps_yy)
    return self.eps_eff_hor_2, self.eps_divergence, self.c
コード例 #10
0
                    for item_idx in cand_items:
                        sets = self.item2sets[item_idx]
                        sets.remove(cand_idx)
                        if not sets:
                            self.is_feasible = False
                            return  # We cant cover the item

    def on_sets_chosen(self, sets):
        covered_items = set()
        for s in sets:
            covered_items.update(self.set2items.pop(s))

        self.on_items_covered(covered_items)

    # Getting info

    def is_all_covered(self):
        return not self.item2sets

    def get_optimistic_cost(self):
        return self.estimator.get_optimistic(self)


if __name__ == '__main__':
    from reader import read_input
    from time import time as now
    state = State.from_task(read_input('sc_15_0'))
    # st = now()
    # state.remove_redundant_sets()
    # print now() - st
コード例 #11
0
    print(
        'Opening a continuous portal to our AI for continuous streaming of input and output.'
    )
    active = True
elif int(args.stream) == 2:
    print(
        'Opening a continuous portal to our AI for continuous streaming of input and output.'
    )
else:
    print('Please specify either -stream 0, -stream 1 or -stream 2.')
    exit()
fn = str(args.fn)
print('\n Welcome to DeepXS version Alpha 2\n')
""" MAIN """
#read input
input_data = read_input(fn, array=array)
#pair settings
c1c1_occurences = [0, 1, 5, 6, 7, 11, 12, 13]
n2n2_occurences = [0, 2, 5, 8, 9, 11, 12, 14]
n2c1p_occurences = [0, 3, 6, 8, 10, 11, 13, 14]
n2c1m_occurences = [0, 4, 7, 9, 10, 12, 13, 14]

if int(args.stream) == 0:
    #c1c1
    for i in c1c1_occurences:
        if i == setting:
            c1c1_LO_data, c1c1_NLO_data = preprocess_c1c1(input_data,
                                                          LO=1,
                                                          NLO=1,
                                                          array=array)
            c1c1_LO_model, c1c1_NLO_model = build_c1c1_AI(
コード例 #12
0
'''
setup_simulation.py

Reads setup.cfg file from current directory, creates necessary directories
and creates the solvers configuration files
'''
import os
import sys
from reader import read_input

if not os.path.exists("./setup.cfg"):
    print("Could not find 'setup.cfg' in current directory. Aborting")
    sys.exit(1)

for dir_name in ["./input", "./output"]:
    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
    if not os.path.isdir(dir_name):
        raise NotADirectoryError(dir_name)

input_file = open("./setup.cfg")
opts, geometry = read_input(input_file)

with open("./solver.cfg", "w") as out:
    out.write("# File generated automatically - do not change it\n" +
              "# To rebuild the configuration use the setup.cfg file\n" +
              "# and rerun the setup_simulation.py distributed\n" +
              "# with the package\n\n\n")
    for key, value in sorted(opts.items()):
        out.write(key + " = " + value + "\n")
コード例 #13
0
def measure_duration(fn, solver=bruteforce_solver):
    start_time = now()
    solver(read_input(fn))
    return now() - start_time
コード例 #14
0
ファイル: rotAvg.py プロジェクト: KTH-Nek5000/turbPipe
def comp(dbCart, Nx, Ny, nu, rho):

    nR = Ny
    nTh = Nx

    #   Read interpolating mesh info
    ReTau, Rmax, drp1, compressedMesh = reader.read_input(
        'input.txt', 'rotAvg')

    xx, yy, theta = disk(Rmax, compressedMesh, ReTau, drp1, nR, nTh)

    #   re-order x,y
    X = np.transpose(xx)
    Y = np.transpose(yy)

    k = 0
    x1 = np.zeros(nTh * nR)
    y1 = np.zeros(nTh * nR)
    angle = np.array([])
    for i in range(0, nR):
        a = theta[:, i]
        angle = np.concatenate((angle, a), axis=None)

    for j in range(0, nTh):
        for i in range(0, nR):
            x1[k] = X[i, j]
            y1[k] = Y[i, j]
            k = k + 1

#   Transpose the imported data tensors
    U = np.transpose(dbCart['U'])
    V = np.transpose(dbCart['V'])
    W = np.transpose(dbCart['W'])
    uu = np.transpose(dbCart['uu'])
    uv = np.transpose(dbCart['uv'])
    uw = np.transpose(dbCart['uw'])
    vv = np.transpose(dbCart['vv'])
    vw = np.transpose(dbCart['vw'])
    ww = np.transpose(dbCart['ww'])
    dUdx = np.transpose(dbCart['dUdx'])
    dUdy = np.transpose(dbCart['dUdy'])
    dUdz = np.transpose(dbCart['dUdz'])
    dVdx = np.transpose(dbCart['dVdx'])
    dVdy = np.transpose(dbCart['dVdy'])
    dVdz = np.transpose(dbCart['dVdz'])
    dWdx = np.transpose(dbCart['dWdx'])
    dWdy = np.transpose(dbCart['dWdy'])
    dWdz = np.transpose(dbCart['dWdz'])
    Pxx = np.transpose(dbCart['Pxx'])
    Pxy = np.transpose(dbCart['Pxy'])
    Pxz = np.transpose(dbCart['Pxz'])
    Pyy = np.transpose(dbCart['Pyy'])
    Pyz = np.transpose(dbCart['Pyz'])
    Pzz = np.transpose(dbCart['Pzz'])
    Dxx = np.transpose(dbCart['Dxx'])
    Dxy = np.transpose(dbCart['Dxy'])
    Dxz = np.transpose(dbCart['Dxz'])
    Dyy = np.transpose(dbCart['Dyy'])
    Dyz = np.transpose(dbCart['Dyz'])
    Dzz = np.transpose(dbCart['Dzz'])
    Cxx = np.transpose(dbCart['Cxx'])
    Cxy = np.transpose(dbCart['Cxy'])
    Cxz = np.transpose(dbCart['Cxz'])
    Cyy = np.transpose(dbCart['Cyy'])
    Cyz = np.transpose(dbCart['Cyz'])
    Czz = np.transpose(dbCart['Czz'])
    Txx = np.transpose(dbCart['Txx'])
    Txy = np.transpose(dbCart['Txy'])
    Txz = np.transpose(dbCart['Txz'])
    Tyy = np.transpose(dbCart['Tyy'])
    Tyz = np.transpose(dbCart['Tyz'])
    Tzz = np.transpose(dbCart['Tzz'])
    VDxx = np.transpose(dbCart['VDxx'])
    VDxy = np.transpose(dbCart['VDxy'])
    VDxz = np.transpose(dbCart['VDxz'])
    VDyy = np.transpose(dbCart['VDyy'])
    VDyz = np.transpose(dbCart['VDyz'])
    VDzz = np.transpose(dbCart['VDzz'])
    PTxx = np.transpose(dbCart['PTxx'])
    PTxy = np.transpose(dbCart['PTxy'])
    PTxz = np.transpose(dbCart['PTxz'])
    PTyy = np.transpose(dbCart['PTyy'])
    PTyz = np.transpose(dbCart['PTyz'])
    PTzz = np.transpose(dbCart['PTzz'])
    PSxx = np.transpose(dbCart['PSxx'])
    PSxy = np.transpose(dbCart['PSxy'])
    PSxz = np.transpose(dbCart['PSxz'])
    PSyy = np.transpose(dbCart['PSyy'])
    PSyz = np.transpose(dbCart['PSyz'])
    PSzz = np.transpose(dbCart['PSzz'])
    uuu = np.transpose(dbCart['uuu'])
    uvv = np.transpose(dbCart['uvv'])
    uuw = np.transpose(dbCart['uuw'])
    uuv = np.transpose(dbCart['uuv'])
    uvw = np.transpose(dbCart['uvw'])
    uww = np.transpose(dbCart['uww'])
    vvv = np.transpose(dbCart['vvv'])
    vvw = np.transpose(dbCart['vvw'])
    vww = np.transpose(dbCart['vww'])
    www = np.transpose(dbCart['www'])
    skew_tensor = np.zeros((3, 3, 3))

    #   Rotation to cylindrical coord.
    n2 = -1
    n3 = 0

    #   Initialisation rotated quantities. The variables zz_ are zz after rotation
    r1 = np.zeros((nTh, nR))
    Ur = np.zeros((nTh, nR))
    Ut = np.zeros((nTh, nR))
    Uz = np.zeros((nTh, nR))
    urur = np.zeros((nTh, nR))
    urut = np.zeros((nTh, nR))
    uruz = np.zeros((nTh, nR))
    utut = np.zeros((nTh, nR))
    uzuz = np.zeros((nTh, nR))
    utuz = np.zeros((nTh, nR))
    dUrdr = np.zeros((nTh, nR))
    dUrdt = np.zeros((nTh, nR))
    dUrdz = np.zeros((nTh, nR))
    dUtdr = np.zeros((nTh, nR))
    dUtdt = np.zeros((nTh, nR))
    dUtdz = np.zeros((nTh, nR))
    dUzdr = np.zeros((nTh, nR))
    dUzdt = np.zeros((nTh, nR))
    dUzdz = np.zeros((nTh, nR))
    Prr = np.zeros((nTh, nR))
    Ptt = np.zeros((nTh, nR))
    Pzz_ = np.zeros((nTh, nR))
    Prt = np.zeros((nTh, nR))
    Prz = np.zeros((nTh, nR))
    Ptz = np.zeros((nTh, nR))
    Drr = np.zeros((nTh, nR))
    Dtt = np.zeros((nTh, nR))
    Dzz_ = np.zeros((nTh, nR))
    Drt = np.zeros((nTh, nR))
    Drz = np.zeros((nTh, nR))
    Dtz = np.zeros((nTh, nR))
    Crr = np.zeros((nTh, nR))
    Ctt = np.zeros((nTh, nR))
    Czz_ = np.zeros((nTh, nR))
    Crt = np.zeros((nTh, nR))
    Crz = np.zeros((nTh, nR))
    Ctz = np.zeros((nTh, nR))
    Trr = np.zeros((nTh, nR))
    Ttt = np.zeros((nTh, nR))
    Tzz_ = np.zeros((nTh, nR))
    Trt = np.zeros((nTh, nR))
    Trz = np.zeros((nTh, nR))
    Ttz = np.zeros((nTh, nR))
    VDrr = np.zeros((nTh, nR))
    VDtt = np.zeros((nTh, nR))
    VDzz_ = np.zeros((nTh, nR))
    VDrt = np.zeros((nTh, nR))
    VDrz = np.zeros((nTh, nR))
    VDtz = np.zeros((nTh, nR))
    PTrr = np.zeros((nTh, nR))
    PTtt = np.zeros((nTh, nR))
    PTzz_ = np.zeros((nTh, nR))
    PTrt = np.zeros((nTh, nR))
    PTrz = np.zeros((nTh, nR))
    PTtz = np.zeros((nTh, nR))
    PSrr = np.zeros((nTh, nR))
    PStt = np.zeros((nTh, nR))
    PSzz_ = np.zeros((nTh, nR))
    PSrt = np.zeros((nTh, nR))
    PSrz = np.zeros((nTh, nR))
    PStz = np.zeros((nTh, nR))
    ururur = np.zeros((nTh, nR))
    ututut = np.zeros((nTh, nR))
    uzuzuz = np.zeros((nTh, nR))
    ururut = np.zeros((nTh, nR))
    ururuz = np.zeros((nTh, nR))
    urutut = np.zeros((nTh, nR))
    ututuz = np.zeros((nTh, nR))
    uruzuz = np.zeros((nTh, nR))
    utuzuz = np.zeros((nTh, nR))
    urutuz = np.zeros((nTh, nR))

    for i in range(0, nTh):

        n1 = n2 + 1
        if (i == 0):
            n2 = n1 + nR - 1
        else:
            n2 = n1 + nR - 1

        r1[i, :] = np.sqrt(
            np.power(x1[n1:n2 + 1], 2) + np.power(y1[n1:n2 + 1], 2))

        # Rotation matrix
        R = np.matrix([[math.cos(angle[i]),
                        math.sin(angle[i]), 0],
                       [-math.sin(angle[i]),
                        math.cos(angle[i]), 0], [0, 0, 1]])

        for jj in range(0, nR):

            # Mean velocities. Tensors of Rank 1.
            U_tens = np.matrix([[U[jj, i]], [V[jj, i]], [W[jj, i]]])
            prod = R * U_tens
            Ur[i, jj] = prod[0]
            Ut[i, jj] = prod[1]
            Uz[i, jj] = prod[2]

            # Reynolds stress tensor. Tensors of Rank 2.
            S = np.matrix([[uu[jj, i], uv[jj, i], uw[jj, i]],
                           [uv[jj, i], vv[jj, i], vw[jj, i]],
                           [uw[jj, i], vw[jj, i], ww[jj, i]]])
            prod = R * S * np.transpose(R)
            urur[i, jj] = prod[0, 0]
            urut[i, jj] = prod[0, 1]
            uruz[i, jj] = prod[0, 2]
            utut[i, jj] = prod[1, 1]
            uzuz[i, jj] = prod[2, 2]
            utuz[i, jj] = prod[1, 2]

            # Velocity gradient tensor. Tensor of Rank 2.
            S = np.matrix([[dUdx[jj, i], dUdy[jj, i], dUdz[jj, i]],
                           [dVdx[jj, i], dVdy[jj, i], dVdz[jj, i]],
                           [dWdx[jj, i], dWdy[jj, i], dWdz[jj, i]]])
            prod = R * S * np.transpose(R)
            dUrdr[i, jj] = prod[0, 0]
            dUrdt[i, jj] = prod[0, 1]
            dUrdz[i, jj] = prod[0, 2]
            dUtdr[i, jj] = prod[1, 0]
            dUtdt[i, jj] = prod[1, 1]
            dUtdz[i, jj] = prod[1, 2]
            dUzdr[i, jj] = prod[2, 0]
            dUzdt[i, jj] = prod[2, 1]
            dUzdz[i, jj] = prod[2, 2]

            # Production tensor. Tensor of Rank 2.
            S = np.matrix([[Pxx[jj, i], Pxy[jj, i], Pxz[jj, i]],
                           [Pxy[jj, i], Pyy[jj, i], Pyz[jj, i]],
                           [Pxz[jj, i], Pyz[jj, i], Pzz[jj, i]]])
            prod = R * S * np.transpose(R)
            Prr[i, jj] = prod[0, 0]
            Ptt[i, jj] = prod[1, 1]
            Pzz_[i, jj] = prod[2, 2]
            Prt[i, jj] = prod[0, 1]
            Prz[i, jj] = prod[0, 2]
            Ptz[i, jj] = prod[1, 2]

            # Dissipation tensor. Tensor of Rank 2.
            S = np.matrix([[Dxx[jj, i], Dxy[jj, i], Dxz[jj, i]],
                           [Dxy[jj, i], Dyy[jj, i], Dyz[jj, i]],
                           [Dxz[jj, i], Dyz[jj, i], Dzz[jj, i]]])
            prod = R * S * np.transpose(R)
            Drr[i, jj] = prod[0, 0]
            Dtt[i, jj] = prod[1, 1]
            Dzz_[i, jj] = prod[2, 2]
            Drt[i, jj] = prod[0, 1]
            Drz[i, jj] = prod[0, 2]
            Dtz[i, jj] = prod[1, 2]

            # Mean convection tensor. Tensor of Rank 2.
            S = np.matrix([[Cxx[jj, i], Cxy[jj, i], Cxz[jj, i]],
                           [Cxy[jj, i], Cyy[jj, i], Cyz[jj, i]],
                           [Cxz[jj, i], Cyz[jj, i], Czz[jj, i]]])
            prod = R * S * np.transpose(R)
            Crr[i, jj] = prod[0, 0]
            Ctt[i, jj] = prod[1, 1]
            Czz_[i, jj] = prod[2, 2]
            Crt[i, jj] = prod[0, 1]
            Crz[i, jj] = prod[0, 2]
            Ctz[i, jj] = prod[1, 2]

            # Turbulent transport tensor. Tensor of Rank 2.
            S = np.matrix([[Txx[jj, i], Txy[jj, i], Txz[jj, i]],
                           [Txy[jj, i], Tyy[jj, i], Tyz[jj, i]],
                           [Txz[jj, i], Tyz[jj, i], Tzz[jj, i]]])
            prod = R * S * np.transpose(R)
            Trr[i, jj] = prod[0, 0]
            Ttt[i, jj] = prod[1, 1]
            Tzz_[i, jj] = prod[2, 2]
            Trt[i, jj] = prod[0, 1]
            Trz[i, jj] = prod[0, 2]
            Ttz[i, jj] = prod[1, 2]

            # Viscous diffusion tensor. Tensor of Rank 2.
            S = np.matrix([[VDxx[jj, i], VDxy[jj, i], VDxz[jj, i]],
                           [VDxy[jj, i], VDyy[jj, i], VDyz[jj, i]],
                           [VDxz[jj, i], VDyz[jj, i], VDzz[jj, i]]])
            prod = R * S * np.transpose(R)
            VDrr[i, jj] = prod[0, 0]
            VDtt[i, jj] = prod[1, 1]
            VDzz_[i, jj] = prod[2, 2]
            VDrt[i, jj] = prod[0, 1]
            VDrz[i, jj] = prod[0, 2]
            VDtz[i, jj] = prod[1, 2]

            # Pressure transport tensor. Tensor of Rank 2.
            S = np.matrix([[PTxx[jj, i], PTxy[jj, i], PTxz[jj, i]],
                           [PTxy[jj, i], PTyy[jj, i], PTyz[jj, i]],
                           [PTxz[jj, i], PTyz[jj, i], PTzz[jj, i]]])
            prod = R * S * np.transpose(R)
            PTrr[i, jj] = prod[0, 0]
            PTtt[i, jj] = prod[1, 1]
            PTzz_[i, jj] = prod[2, 2]
            PTrt[i, jj] = prod[0, 1]
            PTrz[i, jj] = prod[0, 2]
            PTtz[i, jj] = prod[1, 2]

            # Pressure strain tensor. Tensor of Rank 2.
            S = np.matrix([[PSxx[jj, i], PSxy[jj, i], PSxz[jj, i]],
                           [PSxy[jj, i], PSyy[jj, i], PSyz[jj, i]],
                           [PSxz[jj, i], PSyz[jj, i], PSzz[jj, i]]])
            prod = R * S * np.transpose(R)
            PSrr[i, jj] = prod[0, 0]
            PStt[i, jj] = prod[1, 1]
            PSzz_[i, jj] = prod[2, 2]
            PSrt[i, jj] = prod[0, 1]
            PSrz[i, jj] = prod[0, 2]
            PStz[i, jj] = prod[1, 2]

            # Skewness tensor. Tensor of Rank 3.
            skew_tensor[:, :,
                        0] = np.matrix([[uuu[jj, i], uvv[jj, i], uuw[jj, i]],
                                        [uuv[jj, i], uvv[jj, i], uvw[jj, i]],
                                        [uuw[jj, i], uvw[jj, i], uww[jj, i]]])
            skew_tensor[:, :,
                        1] = np.matrix([[uuv[jj, i], uvv[jj, i], uvw[jj, i]],
                                        [uvv[jj, i], vvv[jj, i], vvw[jj, i]],
                                        [uvw[jj, i], vvw[jj, i], vww[jj, i]]])
            skew_tensor[:, :,
                        2] = np.matrix([[uuw[jj, i], uvw[jj, i], uww[jj, i]],
                                        [uvw[jj, i], vvw[jj, i], vww[jj, i]],
                                        [uww[jj, i], vww[jj, i], www[jj, i]]])

            aabc = np.zeros((3, 3, 3))
            adef = skew_tensor[:, :, :]
            for aa in range(0, 3):
                for bb in range(0, 3):
                    for cc in range(0, 3):
                        for dd in range(0, 3):
                            for ee in range(0, 3):
                                for ff in range(0, 3):
                                    aabc[aa, bb, cc] = aabc[
                                        aa, bb,
                                        cc] + R[aa, dd] * R[bb, ee] * R[
                                            cc, ff] * adef[dd, ee, ff]

            ururur[i, jj] = aabc[0, 0, 0]
            ututut[i, jj] = aabc[1, 1, 1]
            uzuzuz[i, jj] = aabc[2, 2, 2]
            ururut[i, jj] = aabc[0, 1, 0]
            ururuz[i, jj] = aabc[0, 2, 0]
            urutut[i, jj] = aabc[1, 1, 0]
            ututuz[i, jj] = aabc[1, 2, 1]
            uruzuz[i, jj] = aabc[2, 2, 0]
            utuzuz[i, jj] = aabc[2, 2, 1]
            urutuz[i, jj] = aabc[1, 2, 0]

#   Average over the azimuthal direction
#   Initialisation averaged quantities.
    Ur_m = np.zeros(nR)
    Ut_m = np.zeros(nR)
    Uz_m = np.zeros(nR)
    urur_m = np.zeros(nR)
    urut_m = np.zeros(nR)
    uruz_m = np.zeros(nR)
    utut_m = np.zeros(nR)
    uzuz_m = np.zeros(nR)
    utuz_m = np.zeros(nR)
    dUrdr_m = np.zeros(nR)
    dUrdt_m = np.zeros(nR)
    dUrdz_m = np.zeros(nR)
    dUtdr_m = np.zeros(nR)
    dUtdt_m = np.zeros(nR)
    dUtdz_m = np.zeros(nR)
    dUzdr_m = np.zeros(nR)
    dUzdt_m = np.zeros(nR)
    dUzdz_m = np.zeros(nR)
    Prr_m = np.zeros(nR)
    Ptt_m = np.zeros(nR)
    Pzz_m = np.zeros(nR)
    Prt_m = np.zeros(nR)
    Prz_m = np.zeros(nR)
    Ptz_m = np.zeros(nR)
    Drr_m = np.zeros(nR)
    Dtt_m = np.zeros(nR)
    Dzz_m = np.zeros(nR)
    Drt_m = np.zeros(nR)
    Drz_m = np.zeros(nR)
    Dtz_m = np.zeros(nR)
    Crr_m = np.zeros(nR)
    Ctt_m = np.zeros(nR)
    Czz_m = np.zeros(nR)
    Crt_m = np.zeros(nR)
    Crz_m = np.zeros(nR)
    Ctz_m = np.zeros(nR)
    Trr_m = np.zeros(nR)
    Ttt_m = np.zeros(nR)
    Tzz_m = np.zeros(nR)
    Trt_m = np.zeros(nR)
    Trz_m = np.zeros(nR)
    Ttz_m = np.zeros(nR)
    VDrr_m = np.zeros(nR)
    VDtt_m = np.zeros(nR)
    VDzz_m = np.zeros(nR)
    VDrt_m = np.zeros(nR)
    VDrz_m = np.zeros(nR)
    VDtz_m = np.zeros(nR)
    PTrr_m = np.zeros(nR)
    PTtt_m = np.zeros(nR)
    PTzz_m = np.zeros(nR)
    PTrt_m = np.zeros(nR)
    PTrz_m = np.zeros(nR)
    PTtz_m = np.zeros(nR)
    PSrr_m = np.zeros(nR)
    PStt_m = np.zeros(nR)
    PSzz_m = np.zeros(nR)
    PSrt_m = np.zeros(nR)
    PSrz_m = np.zeros(nR)
    PStz_m = np.zeros(nR)
    ururur_m = np.zeros(nR)
    ututut_m = np.zeros(nR)
    uzuzuz_m = np.zeros(nR)
    ururut_m = np.zeros(nR)
    ururuz_m = np.zeros(nR)
    urutut_m = np.zeros(nR)
    ututuz_m = np.zeros(nR)
    uruzuz_m = np.zeros(nR)
    utuzuz_m = np.zeros(nR)
    urutuz_m = np.zeros(nR)

    for j in range(0, nR):

        # Mean velocities. Tensors of Rank 1.
        Ur_m[j] = np.mean(Ur[:, j])
        Ut_m[j] = np.mean(Ut[:, j])
        Uz_m[j] = np.mean(Uz[:, j])

        # Reynolds stress tensor. Tensors of Rank 2.
        urur_m[j] = np.mean(urur[:, j])
        urut_m[j] = np.mean(urut[:, j])
        uruz_m[j] = np.mean(uruz[:, j])
        utut_m[j] = np.mean(utut[:, j])
        uzuz_m[j] = np.mean(uzuz[:, j])
        utuz_m[j] = np.mean(utuz[:, j])

        # Velocity gradient tensor. Tensor of Rank 2.
        dUrdr_m[j] = np.mean(dUrdr[:, j])
        dUrdt_m[j] = np.mean(dUrdt[:, j])
        dUrdz_m[j] = np.mean(dUrdz[:, j])
        dUtdr_m[j] = np.mean(dUtdr[:, j])
        dUtdt_m[j] = np.mean(dUtdt[:, j])
        dUtdz_m[j] = np.mean(dUtdz[:, j])
        dUzdr_m[j] = np.mean(dUzdr[:, j])
        dUzdt_m[j] = np.mean(dUzdt[:, j])
        dUzdz_m[j] = np.mean(dUzdz[:, j])

        # Production tensor. Tensor of Rank 2.
        Prr_m[j] = np.mean(Prr[:, j])
        Ptt_m[j] = np.mean(Ptt[:, j])
        Pzz_m[j] = np.mean(Pzz_[:, j])
        Prt_m[j] = np.mean(Prt[:, j])
        Prz_m[j] = np.mean(Prz[:, j])
        Ptz_m[j] = np.mean(Ptz[:, j])

        # Dissipation tensor. Tensor of Rank 2.
        Drr_m[j] = np.mean(Drr[:, j])
        Dtt_m[j] = np.mean(Dtt[:, j])
        Dzz_m[j] = np.mean(Dzz_[:, j])
        Drt_m[j] = np.mean(Drt[:, j])
        Drz_m[j] = np.mean(Drz[:, j])
        Dtz_m[j] = np.mean(Dtz[:, j])

        # Mean convection tensor. Tensor of Rank 2.
        Crr_m[j] = np.mean(Crr[:, j])
        Ctt_m[j] = np.mean(Ctt[:, j])
        Czz_m[j] = np.mean(Czz_[:, j])
        Crt_m[j] = np.mean(Crt[:, j])
        Crz_m[j] = np.mean(Crz[:, j])
        Ctz_m[j] = np.mean(Ctz[:, j])

        # Turbulent transport tensor. Tensor of Rank 2.
        Trr_m[j] = np.mean(Trr[:, j])
        Ttt_m[j] = np.mean(Ttt[:, j])
        Tzz_m[j] = np.mean(Tzz_[:, j])
        Trt_m[j] = np.mean(Trt[:, j])
        Trz_m[j] = np.mean(Trz[:, j])
        Ttz_m[j] = np.mean(Ttz[:, j])

        # Viscous diffusion tensor. Tensor of Rank 2.
        VDrr_m[j] = np.mean(VDrr[:, j])
        VDtt_m[j] = np.mean(VDtt[:, j])
        VDzz_m[j] = np.mean(VDzz_[:, j])
        VDrt_m[j] = np.mean(VDrt[:, j])
        VDrz_m[j] = np.mean(VDrz[:, j])
        VDtz_m[j] = np.mean(VDtz[:, j])

        # Pressure transport tensor. Tensor of Rank 2.
        PTrr_m[j] = np.mean(PTrr[:, j])
        PTtt_m[j] = np.mean(PTtt[:, j])
        PTzz_m[j] = np.mean(PTzz_[:, j])
        PTrt_m[j] = np.mean(PTrt[:, j])
        PTrz_m[j] = np.mean(PTrz[:, j])
        PTtz_m[j] = np.mean(PTtz[:, j])

        # Pressure strain tensor. Tensor of Rank 2.
        PSrr_m[j] = np.mean(PSrr[:, j])
        PStt_m[j] = np.mean(PStt[:, j])
        PSzz_m[j] = np.mean(PSzz_[:, j])
        PSrt_m[j] = np.mean(PSrt[:, j])
        PSrz_m[j] = np.mean(PSrz[:, j])
        PStz_m[j] = np.mean(PStz[:, j])

        # Skewness tensor. Tensor of Rank 3.
        ururur_m[j] = np.mean(ururur[:, j])
        ututut_m[j] = np.mean(ututut[:, j])
        uzuzuz_m[j] = np.mean(uzuzuz[:, j])
        ururut_m[j] = np.mean(ururut[:, j])
        ururuz_m[j] = np.mean(ururuz[:, j])
        urutut_m[j] = np.mean(urutut[:, j])
        ututuz_m[j] = np.mean(ututuz[:, j])
        uruzuz_m[j] = np.mean(uruzuz[:, j])
        utuzuz_m[j] = np.mean(utuzuz[:, j])

    # Compute TKE budget terms
    P_k = 0.5 * (Prr_m + Ptt_m + Pzz_m)  # production
    T_k = 0.5 * (Trr_m + Ttt_m + Tzz_m)  # turbulent transport
    PS_k = 0.5 * (PSrr_m + PStt_m + PSzz_m)  # pressure-strain
    PT_k = 0.5 * (PTrr_m + PTtt_m + PTzz_m)  # pressure-transport
    Pi_k = (PT_k - PS_k)
    VD_k = 0.5 * (VDrr_m + VDtt_m + VDzz_m)  # viscous diffusion
    D_k = 0.5 * (Drr_m + Dtt_m + Dzz_m)  # dissipation
    C_k = 0.5 * (Crr_m + Ctt_m + Czz_m)  # mean convection

    # Write postprocessed results in a file
    # make an array of radii
    r_ = np.zeros(nR)
    for i in range(0, nR):
        r_[i] = np.sqrt(np.power(X[i, 0], 2) + np.power(Y[i, 0], 2))

    rMax = np.max(r_)
    r_ = rMax - r_  #Changing the discrete radius from wall toward center

    # Compute uTau
    uTau = np.sqrt(-dUzdr_m[-1] * nu)
    # method 2
    tauW = (Uz_m[-2] - Uz_m[-1]) / (r_[-2] - r_[-1])
    uTau2 = np.sqrt(nu * tauW)

    ReTau = uTau * rMax / nu
    ReTau2 = uTau2 * rMax / nu
    print('\n')
    print(
        'To double check results u_tau and Re_tau are computed with two different methods. '
    )
    print(
        'Method 1: as square root of the product between the averaged field dUzdr at the wall and nu. Retau is obtained from the uTau*rMax/nu.'
    )
    print(
        'Method 2: as square root of nu*tauW, where tauW is computed as finite difference of the averaged field Uz at the wall. Retau is obtained from the uTau*rMax/nu. \n'
    )
    print('uTau (method1)= ', uTau)
    print('uTau (method2)= ', uTau2)
    print('Re_tau (method1)= ', ReTau)
    print('Re_tau (method2)= ', ReTau2)

    #   Saving Dict. of rotated and averaged quantities(not scaled)
    dbRotAvg = {'Ur':Ur_m, 'Ut':Ut_m, 'Uz':Uz_m, \
                'urur':urur_m, 'urut':urut_m, 'uruz':uruz_m, 'utut':utut_m, 'uzuz':uzuz_m, 'utuz':utuz_m, \
                'dUrdr':dUrdr_m, 'dUrdt':dUrdt_m, 'dUrdz':dUrdz_m, 'dUtdr':dUtdr_m, 'dUtdt':dUtdt_m, 'dUtdz':dUtdz_m, 'dUzdr':dUzdr_m, 'dUzdt':dUzdt_m, 'dUzdz_m':dUzdz, \
                'Prr':Prr_m, 'Ptt':Ptt_m, 'Pzz':Pzz_m, 'Prt':Prt_m, 'Prz':Prz_m, 'Ptz':Ptz_m, \
                'Drr':Drr_m, 'Dtt':Dtt_m, 'Dzz':Dzz_m, 'Drt':Drt_m, 'Drz':Drz_m, 'Dtz':Dtz_m, \
                'Crr':Crr_m, 'Ctt':Ctt_m, 'Czz':Czz_m, 'Crt':Crt_m, 'Crz':Crz_m, 'Ctz':Ctz_m, \
                'Trr':Trr_m, 'Ttt':Ttt_m, 'Tzz':Tzz_m, 'Trt':Trt_m, 'Trz':Trz_m, 'Ttz':Ttz_m, \
                'VDrr':VDrr_m, 'VDtt':VDtt_m, 'VDzz':VDzz_m, 'VDrt':VDrt_m, 'VDrz':VDrz_m, 'VDtz':VDtz_m, \
                'PTrr':PTrr_m, 'PTtt':PTtt_m, 'PTzz':PTzz_m, 'PTrt':PTrt_m, 'PTrz':PTrz_m, 'PTtz':PTtz_m, \
                'PSrr':PSrr_m, 'PStt':PStt_m, 'PSzz':PSzz_m, 'PSrt':PSrt_m, 'PSrz':PSrz_m, 'PStz':PStz_m, \
                'ururur':ururur_m, 'ututut':ututut_m, 'uzuzuz':uzuzuz_m, 'ururut':ururut_m, 'ururuz':ururuz_m, 'urutut':urutut_m, 'ututuz':ututuz_m, 'uruzuz':uruzuz_m, 'utuzuz':utuzuz_m, \
                'P_k':P_k, 'T_k':T_k, 'PS_k':PS_k, 'PT_k':PT_k, 'Pi_k':Pi_k, 'VD_k':VD_k, 'D_k':D_k, 'C_k':C_k, \
                'r':r_, 'nu':nu, 'u_tau': uTau, 'Re_tau':ReTau \
                }

    #   Saving txt file of rotated and averaged quantities

    #velocity profiles + derivatives
    fileName = 'OUTPUT/turbPipe_meanVelDer.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# Mean velocity and their derivatives \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r\t Ur\t Ut\t Uz\t dUrdr\t dUrdt\t dUrdz\t dUtdr\t dUtdt\t dUtdz\t dUzdr\t dUzdt\t dUzdz \n"
    )
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t   \n" % \
                (r_[i], Ur_m[i], Ut_m[i], Uz_m[i], dUrdr_m[i], dUrdt_m[i], dUrdz_m[i], dUtdr_m[i], dUtdt_m[i], dUtdz_m[i], dUzdr_m[i], dUzdt_m[i], dUzdz_m[i]))
    F.close()

    #Reynolds stress components
    fileName = 'OUTPUT/turbPipe_ReStressTens.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# Reynolds stress components \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# r\t urp\t urut\t uruz\t utp\t uzp\t utuz \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t \n" % \
                (r_[i], np.sqrt(urur_m[i]-Ur_m[i]*Ur_m[i]), urut_m[i]-Ur_m[i]*Ut_m[i], uruz_m[i]-Ur_m[i]*Uz_m[i], np.sqrt(utut_m[i]-Ut_m[i]*Ut_m[i]), \
                np.sqrt(abs(uzuz_m[i]-Uz_m[i]*Uz_m[i])), utuz_m[i]-Ut_m[i]*Uz_m[i]) )
    F.close()

    #TKE budget terms
    fileName = 'OUTPUT/turbPipe_kBudgets.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# TKE budget terms: nondim by multiplying by nu/uTau^4 \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r+\t P_k+ \t T_k+ \t PS_k+ \t PT_k+ \t VD_k+ \t D_k+ \t C_k+ \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    fac = nu / np.power(uTau, 4)
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t%g\t \n" % \
                (r_[i]*ReTau, P_k[i]*fac, T_k[i]*fac, PS_k[i]*fac, PT_k[i]*fac, VD_k[i]*fac, D_k[i]*fac, C_k[i]*fac) )
    F.close()

    #budget terms of <urur>
    fileName = 'OUTPUT/turbPipe_rrBudgets.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# budget terms of <urur>: nondim by multiplying by nu/uTau^4 \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r+\t P_rr+ \t T_rr+ \t PS_rr+ \t PT_rr+ \t VD_rr+ \t D_rr+ \t C_rr+ \n"
    )
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t%g \n" % \
                (r_[i]*ReTau, Prr_m[i]*fac, Trr_m[i]*fac, PSrr_m[i]*fac, PTrr_m[i]*fac, VDrr_m[i]*fac, Drr_m[i]*fac, Crr_m[i]*fac) )
    F.close()

    #budget terms of <utut>
    fileName = 'OUTPUT/turbPipe_ttBudgets.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# budget terms of <utut>: nondim by multiplying by nu/uTau^4 \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r+\t P_tt+ \t T_tt+ \t PS_tt+ \t PT_tt+ \t VD_tt+ \t D_tt+ \t C_tt+ \n"
    )
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t%g \n" % \
                (r_[i]*ReTau, Ptt_m[i]*fac, Ttt_m[i]*fac, PStt_m[i]*fac, PTtt_m[i]*fac, VDtt_m[i]*fac, Dtt_m[i]*fac, Ctt_m[i]*fac) )
    F.close()

    #budget terms of <uzuz>
    fileName = 'OUTPUT/turbPipe_zzBudgets.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# budget terms of <uzuz>: nondim by multiplying by nu/uTau^4 \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r+\t P_zz+ \t T_zz+ \t PS_zz+ \t PT_zz+ \t VD_zz+ \t D_zz+ \t C_zz+ \n"
    )
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t%g \n" % \
                (r_[i]*ReTau, Pzz_m[i]*fac, Tzz_m[i]*fac, PSzz_m[i]*fac, PTzz_m[i]*fac, VDzz_m[i]*fac, Dzz_m[i]*fac, Czz_m[i]*fac) )
    F.close()

    #budget terms of <uruz>
    fileName = 'OUTPUT/turbPipe_rzBudgets.txt'
    F = open(fileName, 'w')
    F.write("# Postprocessed results of turbulent pipe flow \n")
    F.write("# budget terms of <uruz>: nondim by multiplying by nu/uTau^4 \n")
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write("# uTau = %g \n" % uTau)
    F.write("# nu = %g \n" % nu)
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    F.write(
        "# r+\t P_rz+ \t T_rz+ \t PS_rz+ \t PT_rz+ \t VD_rz+ \t D_rz+ \t C_rz+ \n"
    )
    F.write(
        "# ------------------------------------------------------------------\n"
    )
    for i in range(0, nR):
        F.write("%g\t%g\t%g\t%g\t %g\t%g\t%g\t%g \n" % \
                (r_[i]*ReTau, Prz_m[i]*fac, Trz_m[i]*fac, PSrz_m[i]*fac, PTrz_m[i]*fac, VDrz_m[i]*fac, Drz_m[i]*fac, Crz_m[i]*fac) )
    F.close()

    return dbRotAvg
コード例 #15
0
            theta[j, i] = th[j]

    return xx, yy, theta


if __name__ == "__main__":
    # initialise variables
    fname = 'int_pos'
    wdsize = 8
    # little endian
    emode = '<'
    # big endian
    #emode = '<'

    #   Read interpolating mesh info
    Nx, Ny, ReTau, Rmax, drp1, compressedMesh = reader.read_input(
        'input.txt', 'pipeInterpMesh')

    nR = Ny
    nTh = Nx

    #
    # generate polar mesh over a circular disk
    xx, yy, theta = disk(Rmax, compressedMesh, ReTau, drp1, nR, nTh)

    # allocate space
    ldim = 2  #2D grid
    npoints = xx.size
    data = pset(ldim, npoints)
    print('Allocated {0} points'.format(npoints))

    # initialise point positions
コード例 #16
0
    def __init__(self, configName):
        '''
        Sets up the initial spatial grid, time grid, accumulation rate, age, density, mass, stress, and temperature of the model run
        :param configName: name of json config file containing model configurations
        '''

        ### load in json config file and parses the user inputs to a dictionary
        self.spin=False
        with open(configName, "r") as f:
            jsonString  = f.read()
            self.c      = json.loads(jsonString)

        print('Spin run started')
        print("physics are", self.c['physRho'])
        try:
            print('Merging is:',self.c["merging"])
        except Exception:
            pass

        ### create directory to store results. Deletes if it exists already.
        if os.path.exists(self.c['resultsFolder']):
            rmtree(self.c['resultsFolder'])
        os.makedirs(self.c['resultsFolder'])

        ############################
        ##### load input files #####
        ############################
        ### temperature
        input_temp, input_year_temp = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNameTemp']))
        if input_temp[0] < 0.0:
            input_temp              = input_temp + K_TO_C
        try:
            if self.c['spinup_climate_type']=='initial':
                self.temp0                  = input_temp[0]
            elif self.c['spinup_climate_type']=='mean':
                self.temp0                  = np.mean(input_temp)
        except:
            print("You should add key 'spinup_climate_type' to the config .json file")
            print("spinup is based on mean climate of input")
            self.temp0                  = np.mean(input_temp)
        
        # self.temp0 = 270.0
        # self.temp0 = mean(input_temp[0:12]) #Make sure that this is what we want!

        ### accumulation rate
        input_bdot, input_year_bdot = read_input(os.path.join(self.c['InputFileFolder'],self.c['InputFileNamebdot']))
        
        try:
            if self.c['spinup_climate_type']=='initial':
                self.bdot0      = input_bdot[0]
            elif self.c['spinup_climate_type']=='mean':
                self.bdot0      = np.mean(input_bdot)
        except:
            self.bdot0      = np.mean(input_bdot)

        if self.c['initprofile']:
            try:
                if self.c['singleleap'] or self.c['singlenormal']: #VV If we use the initprofile but the input forcing data does not cover an entire year
                    self.temp0 = self.c['deepT'] #VV use deep T as mean temperature for spin up calculations (compaction,grain growth)
                    self.bdot0 = self.c['bdot_long']*1e-3/0.917 #VV use long term accumulation as mean accumulation for spin up calculations (compaction,grain growth) + conversion from mmWE/yr to mIE/yr
            except Exception:
                print("you are using an initial profile for spinup,")
                print("but you do not have 'singleleap' or 'singlenormal' in the .json")

        
        print('bdot0', self.bdot0)
        ### could include others, e.g. surface density
        ############################

        ############################
        ### set up model grid ######
        ############################
        self.gridLen    = int((self.c['H'] - self.c['HbaseSpin']) / (self.bdot0 / self.c['stpsPerYearSpin'])) # number of grid points
        gridHeight      = np.linspace(self.c['H'], self.c['HbaseSpin'], self.gridLen)
        self.z          = self.c['H'] - gridHeight
        self.dz         = np.diff(self.z) 
        self.dz         = np.append(self.dz, self.dz[-1])
        self.dx         = np.ones(self.gridLen)
        print('Grid length is', self.gridLen)
        ############################

        ############################
        ### if the regridding module is being used, do the
        ### initial regridding
        ############################
        try:
            self.doublegrid = self.c['doublegrid']
            if self.c['doublegrid']:
                self.nodestocombine, self.z, self.dz, self.gridLen, self.dx, self.gridtrack = init_regrid(self)
        except:
            self.doublegrid = False
            print('you should add "doublegrid" to the json')

        ############################
        ### get an initial depth/density profile based on H&L analytic solution
        ############################
        # if self.c['initprofile'] == False: #VV
        THL                 = self.temp0
        AHL                 = self.bdot0
        self.age, self.rho     = hl_analytic(self.c['rhos0'], self.z, THL, AHL) # self.age is in age in seconds
        # elif self.c['initprofile'] == True: # VV we have an initial temperature and density profile
            # Just avoid the model to blow up because it has no age and rho variables, real values are given below
            # self.age = S_PER_YEAR*100*np.ones_like(self.dz) #VV this does not matter as it is rectified when we initialise profie below
            # self.rho = 500*np.ones_like(self.dz)#VV this does not matter as it is rectified when we initialise profile
        ############################

        ############################
        ### set up time stepping
        if self.c['AutoSpinUpTime']: # automatic, based on time that it will take for a parcel to get to 850 kg m^-3
            try:
                zz          = np.min(self.z[self.rho > 850.0])
                self.years  = int(zz / self.bdot0)
            except ValueError:
                print("auto spin up error; using spin up time from json")
                self.years = self.c['yearSpin'] # number of years to spin up for
        else: # based on time taken to spin up in the config file.
            self.years = self.c['yearSpin'] # number of years to spin up for
        
        self.dt     = S_PER_YEAR / self.c['stpsPerYearSpin']
        self.stp    = int(self.years*S_PER_YEAR/self.dt)
        self.t      =  1.0 / self.c['stpsPerYearSpin'] # years per time step
        ############################

        ############################
        ### Initial and boundary conditions
        ############################
        ### Surface temperature for each time step
        self.Ts         = self.temp0 * np.ones(self.stp)
        if self.c['SeasonalTcycle']: #impose seasonal temperature cycle of amplitude 'TAmp'
            # self.Ts     = self.Ts + self.c['TAmp'] * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp )) + 0.3 * np.cos(4 * np.pi * np.linspace(0, self.years, self.stp ))) #Orsi, coreless winter
            self.Ts         = self.Ts - self.c['TAmp'] * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp))) # This is basic for Greenland (for Antarctica the it should be a plus instead of minus)

        ### initial temperature profile
        # init_Tz       = input_temp[0] * np.ones(self.gridLen)
        init_Tz         = np.mean(self.Ts) * np.ones(self.gridLen)

        ### Accumulation rate for each time step
        self.bdotSec0   = self.bdot0 / S_PER_YEAR / self.c['stpsPerYearSpin'] # accumulation (m I.E. per second)
        self.bdotSec    = self.bdotSec0 * np.ones(self.stp) # vector of accumulation at each time step

        ### Surface isotope values for each time step
        if self.c['isoDiff']:
            try:
                input_iso, input_year_iso = read_input(self.c['InputFileNameIso'])
                del_s0  = input_iso[0]
            except:
                print('No external file for surface isotope values found, but you specified in the config file that isotope diffusion is on. The model will generate its own synthetic isotope data for you.')
                del_s0  = -50.0

            self.del_s  = del_s0 * np.ones(self.stp)
            init_del_z  = del_s0 * np.ones(self.gridLen)
            self.del_z  = init_del_z
        else:
            self.del_s  = None
            init_del_z  = None    
        
        ### Surface Density
        self.rhos0      = self.c['rhos0'] * np.ones(self.stp)
        # could configure this so that user specifies vector of surface elevation
        # could add noise too

        ### initial mass, stress, and mean accumulation rate
        self.mass       = self.rho * self.dz
        self.sigma      = self.mass * self.dx * GRAVITY
        self.sigma      = self.sigma.cumsum(axis = 0)
        self.mass_sum   = self.mass.cumsum(axis = 0)
        #VVself.bdot_mean  = (np.concatenate(([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] / (self.age[1:] * RHO_I / self.t)))) * self.c['stpsPerYear'] * S_PER_YEAR

        ### Mean temperatures and accumulation rates #VV ###
        ### MS: commented out for now 10/4/18
        # if self.c['initprofile']:
        #     self.T_av = self.c['Ts_long'] * np.ones(self.stp) # If we use initial profile, Ts_long is best guess for Tav
        #     self.bdot_av = self.c['bdot_long']*1e-3/0.917 * np.ones(self.stp) # If we use initial profile, bdotlong is best guess for bdot_av + conversion from mmWE/yr to mIE/yr
        #     self.bdot_mean = np.ones_like(self.dz)*self.c['bdot_long']*1e-3/0.917 # Also best guess for bdot_mean
        # else:
        self.T_av = self.temp0 * np.ones(self.stp) #VV This is to be used instead of T10m
        self.bdot_av = self.bdot0* np.ones(self.stp) #VV 
        self.bdot_mean  = (np.concatenate(([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] / (self.age[1:] * RHO_I / self.t)))) * self.c['stpsPerYear'] * S_PER_YEAR #VV

        ### longitudinal strain rate
        if self.c['strain']:
            self.du_dx      = np.zeros(self.gridLen)
            self.du_dx[1:]  = self.c['du_dx']/(S_PER_YEAR)
        
        ### initial temperature grid 
        self.Tz         = init_Tz
        self.T_mean     = np.mean(self.Tz[self.z<50])
        self.T10m       = self.T_mean

        ### initial grain growth (if specified in config file)
        if self.c['physGrain']:
            if self.c['calcGrainSize']:
                r02 = surfacegrain(self,0) #VV
                self.r2 = r02 * np.ones(self.gridLen)
            else:
                self.r2 = np.linspace(self.c['r2s0'], (6 * self.c['r2s0']), self.gridLen)
        else:
            self.r2 = None

        ### "temperature history" if using Morris physics
        if self.c['physRho']=='Morris2014':
            # initial temperature history function (units seconds)
            self.Hx     = np.exp(-110.0e3/(R*init_Tz))*(self.age+self.dt)
            self.THist  = True
        else:
            self.THist  = False

        self.LWC = np.zeros_like(self.z)
        self.MELT = False
コード例 #17
0
    def __init__(self, configName):
        '''
        Sets up the initial spatial grid, time grid, accumulation rate, age, density, mass, stress, temperature, and diffusivity of the model run
        :param configName: name of json config file containing model configurations
        '''

        # load in json config file and parses the user inputs to a dictionary
        with open(configName, "r") as f:
            jsonString = f.read()
            self.c = json.loads(jsonString)
        print("Main run starting")
        print("physics are", self.c['physRho'])

        ### read in initial depth, age, density, temperature from spin-up results
        initDepth = read_init(self.c['resultsFolder'], self.c['spinFileName'],
                              'depthSpin')
        initAge = read_init(self.c['resultsFolder'], self.c['spinFileName'],
                            'ageSpin')
        initDensity = read_init(self.c['resultsFolder'],
                                self.c['spinFileName'], 'densitySpin')
        init_drho_dt = read_init(self.c['resultsFolder'],
                                 self.c['spinFileName'], 'drho_dtSpin')
        initTemp = read_init(self.c['resultsFolder'], self.c['spinFileName'],
                             'tempSpin')

        ### read initial diffusion lengths
        init_iso_sigmaD = read_init(self.c['resultsFolder'],
                                    self.c['spinFileName'], 'iso_sigmaD')
        init_iso_sigma18 = read_init(self.c['resultsFolder'],
                                     self.c['spinFileName'], 'iso_sigma18')
        init_iso_sigma17 = read_init(self.c['resultsFolder'],
                                     self.c['spinFileName'], 'iso_sigma17')
        init_iso_dsigma2_dt_D = read_init(self.c['resultsFolder'],
                                          self.c['spinFileName'],
                                          'iso_dsigma2_dt_D')
        init_iso_dsigma2_dt_18 = read_init(self.c['resultsFolder'],
                                           self.c['spinFileName'],
                                           'iso_dsigma2_dt_18')
        init_iso_dsigma2_dt_17 = read_init(self.c['resultsFolder'],
                                           self.c['spinFileName'],
                                           'iso_dsigma2_dt_17')

        ### set up the initial age and density of the firn column
        self.age = initAge[1:]
        self.rho = initDensity[1:]
        self.drho_dt = init_drho_dt[1:]

        ###set up initial diffusion length dictionary as attribute
        self.iso_sigma = {
            'D': init_iso_sigmaD[1:],
            '18': init_iso_sigma18[1:],
            '17': init_iso_sigma17[1:]
        }
        self.iso_dsigma2_dt = {
            'D': init_iso_dsigma2_dt_D[1:],
            '18': init_iso_dsigma2_dt_18[1:],
            '17': init_iso_dsigma2_dt_17[1:]
        }

        ### set up model grid
        self.z = initDepth[1:]
        self.dz = np.diff(self.z)
        self.dz = np.append(self.dz, self.dz[-1])
        self.gridLen = np.size(self.z)
        self.dx = np.ones(self.gridLen)

        ### get temperature and accumulation rate from input csv file
        input_temp, input_year_temp = read_input(self.c['InputFileNameTemp'])
        if input_temp[0] < 0.0:
            input_temp = input_temp + K_TO_C
        input_bdot, input_year_bdot = read_input(self.c['InputFileNamebdot'])
        input_bdot[input_bdot <= 0.0] = 0.01
        # if self.c['variable_srho']:
        #     input_srho, input_year_srho = read_input(self.c['InputFileNamesrho'])

        try:
            input_snowmelt, input_year_snowmelt = read_input(
                self.c['InputFileNamemelt'])
            MELT = True
            print("Melt is initialized")
        except:
            MELT = False
            print("No melt")
            input_snowmelt = None
            input_year_snowmelt = None

        # year to start and end, from the input file. If inputs have different start/finish, take only the overlapping times
        yr_start = max(input_year_temp[0], input_year_bdot[0])  # start year
        yr_end = min(input_year_temp[-1], input_year_bdot[-1])  # end year

        self.years = (yr_end - yr_start) * 1.0
        self.dt = S_PER_YEAR / self.c['stpsPerYear']
        print('dt', self.dt / S_PER_YEAR)
        self.stp = int(self.years * S_PER_YEAR / self.dt +
                       1)  # total number of time steps, as integer
        # self.modeltime  = np.linspace(yr_start, yr_end, self.stp + 1)   # vector of time of each model step
        self.modeltime = np.linspace(yr_start, yr_end, self.stp)

        # self.dt         = self.years * S_PER_YEAR / self.stp            # size of time steps, seconds
        self.t = 1.0 / self.c['stpsPerYear']  # years per time step

        ### Temperature
        # self.Ts         = np.interp(self.modeltime, input_year_temp, input_temp) # surface temperature interpolated to model time
        Tsf = interpolate.interp1d(input_year_temp,
                                   input_temp,
                                   'linear',
                                   fill_value='extrapolate')
        self.Ts = Tsf(self.modeltime)
        # print len(self.Ts)
        # print self.Ts[0:13]
        if self.c[
                'SeasonalTcycle']:  #impose seasonal temperature cycle of amplitude 'TAmp'
            self.Ts = self.Ts + self.c['TAmp'] * (
                np.cos(2 * np.pi * np.linspace(0, self.years, self.stp)) +
                0.3 * np.cos(4 * np.pi * np.linspace(0, self.years, self.stp)))
            # print self.Ts[0:13]

        ### Accumulation
        # self.bdot       = np.interp(self.modeltime, input_year_bdot, input_bdot) # interpolate accumulation rate to model time ???Should this be nearest?
        bsf = interpolate.interp1d(input_year_bdot,
                                   input_bdot,
                                   'linear',
                                   fill_value='extrapolate')
        self.bdot = bsf(self.modeltime)

        # self.bdotSec    = self.bdot / S_PER_YEAR / (self.stp / self.years) # accumulation rate in per second
        self.bdotSec = self.bdot / S_PER_YEAR / self.c[
            'stpsPerYear']  # accumulation for each time step(per second)
        self.iceout = np.mean(
            self.bdot
        )  # this is the rate of ice flow advecting out of the column

        ### Melt
        if MELT:
            # self.snowmelt   = np.interp(self.modeltime, input_year_snowmelt, input_snowmelt)
            ssf = interpolate.interp1d(input_year_snowmelt,
                                       input_snowmelt,
                                       'nearest',
                                       fill_value='extrapolate')
            self.snowmelt = ssf(self.modeltime)
            self.snowmeltSec = self.snowmelt / S_PER_YEAR / self.c[
                'stpsPerYear']  # melt for each time step (per second)
            # print [self.modeltime, self.snowmelt]
            # raw_input()

        ##### Isotopes ###########
        if self.c['isoDiff']:
            init_del_z = read_init(self.c['resultsFolder'],
                                   self.c['spinFileName'], 'IsoSpin')
            try:
                input_iso, input_year_iso = read_input(
                    self.c['InputFileNameIso'])
                del_s_f = interpolate.interp1d(input_year_iso,
                                               input_iso,
                                               'nearest',
                                               fill_value='extrapolate')
                self.del_s = del_s_f(self.modeltime)
                # del_s0 = input_iso[0]
            except:
                print(
                    'No external file for surface isotope values found, but you specified in the config file that isotope diffusion is on. The model will generate its own synthetic isotope data for you.'
                )
                # del_s0 = -50.0
                ar1 = 0.9  # red noise memory coefficient
                std_rednoise = 2  # red noise standard deviation
                self.del_s = std_rednoise * np.random.randn(
                    self.stp)  # white noise
                for x in range(1, self.stp):
                    self.del_s[x] = self.del_s[x - 1] * ar1 + np.random.randn(
                    )  # create red noise from white
                self.del_s = self.del_s - 50
                #impose seasonal isotope cycle
                # self.del_s = self.del_s + 5 * (np.cos(2 * np.pi * np.linspace(0, self.years, self.stp )) + 0.3 * np.cos(4 * np.pi * np.linspace(0, self.years, self.stp )))
        ###########################

        try:
            if self.c['variable_srho']:
                self.rhos0 = np.interp(self.modeltime, input_year_srho,
                                       input_srho)
            else:
                self.rhos0 = self.c['rhos0'] * np.ones(
                    self.stp)  # density at surface
        except:
            print("you should alter the json to include variable_srho")
            self.rhos0 = self.c['rhos0'] * np.ones(
                self.stp)  # density at surface

        # if MELT:
        #     self.snowmelt = np.interp(self.modeltime, input_year_snowmelt, input_snowmelt)
        #     self.snowmeltSec = self.snowmelt / S_PER_YEAR / (self.stp / self.years)

        # if MELT:
        #     self.snowmelt = np.interp(self.modeltime, input_year_snowmelt, input_snowmelt)
        #     self.snowmeltSec = self.snowmelt / S_PER_YEAR / (self.stp / self.years)

        self.rhos0 = self.c['rhos0'] * np.ones(self.stp)  # density at surface
        self.D_surf = self.c['D_surf'] * np.ones(
            self.stp)  # layer traking routine (time vector).

        self.Dcon = self.c['D_surf'] * np.ones(
            self.gridLen)  # layer tracking routine (initial depth vector)

        # set up vector of times data will be written
        # Tind = np.nonzero(selfself.modeltime>=1958.0)[0][0]

        self.TWrite = self.modeltime[0::self.c['TWriteInt']]
        # self.TWrite_out = self.TWrite
        TWlen = len(self.TWrite)  #- 1
        self.WTracker = 1

        # set up initial mass, stress, and mean accumulation rate
        self.mass = self.rho * self.dz
        self.sigma = self.mass * self.dx * GRAVITY
        self.sigma = self.sigma.cumsum(axis=0)
        self.mass_sum = self.mass.cumsum(axis=0)

        ### mean accumulation over the lifetime of the parcel
        # self.bdot_mean  = np.concatenate(([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] / (self.age[1:] * RHO_I / self.t)))
        self.bdot_mean = (np.concatenate(
            ([self.mass_sum[0] / (RHO_I * S_PER_YEAR)], self.mass_sum[1:] /
             (self.age[1:] * RHO_I / self.t)))
                          ) * self.c['stpsPerYear'] * S_PER_YEAR

        ### set up longitudinal strain rate
        if self.c['strain']:
            self.du_dx = np.zeros(self.gridLen)
            self.du_dx[1:] = self.c['du_dx'] / (S_PER_YEAR)

        # set up class to handle heat/isotope diffusion using user provided data for initial temperature vector
        # self.diffu      = Diffusion(self.z, self.stp, self.gridLen, initTemp[1:], init_del_z[1:]) # [1:] because first element is a time stamp
        # self.T_mean     = self.diffu.T10m # initially the mean temp is the same as the surface temperature
        self.Tz = initTemp[1:]
        self.T_mean = self.Tz[0]
        self.T10m = self.T_mean

        ### Output list defined here
        if self.c['isoDiff']:
            self.output_list = ['density', 'drho_dt', 'depth','temperature', \
            'age', 'climate', 'iso_sigmaD', 'iso_sigma18', 'iso_sigma17', \
            'iso_dsigma2_dt_D', 'iso_dsigma2_dt_18', 'iso_dsigma2_dt_17', 'isotopes']
        else:
            self.output_list = ['density', 'drho_dt', 'depth','temperature', \
            'age', 'climate', 'iso_sigmaD', 'iso_sigma18', 'iso_sigma17', \
            'iso_dsigma2_dt_D', 'iso_dsigma2_dt_18', 'iso_dsigma2_dt_17']
        print(self.output_list)
        if 'density' in self.output_list:
            self.rho_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                    dtype='float32')
            self.rho_out[0, :] = np.append(self.modeltime[0], self.rho)
        if 'drho_dt' in self.output_list:
            self.drho_dt_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                        dtype='float32')
            self.drho_dt_out[0, :] = np.append(self.modeltime[0], self.drho_dt)
        if 'temperature' in self.output_list:
            self.Tz_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                   dtype='float32')
            self.Tz_out[0, :] = np.append(self.modeltime[0], self.Tz)
        if 'age' in self.output_list:
            self.age_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                    dtype='float32')
            self.age_out[0, :] = np.append(self.modeltime[0],
                                           self.age / S_PER_YEAR)
        if 'depth' in self.output_list:
            self.z_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                  dtype='float32')
            self.z_out[0, :] = np.append(self.modeltime[0], self.z)
        if 'dcon' in self.output_list:
            self.D_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                  dtype='float32')
            self.D_out[0, :] = np.append(self.modeltime[0], self.Dcon)
        if 'bdot_mean' in self.output_list:
            self.bdot_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                     dtype='float32')
            self.bdot_out[0, :] = np.append(self.modeltime[0], self.bdot_mean)
        if 'climate' in self.output_list:
            self.Clim_out = np.zeros((TWlen + 1, 3), dtype='float32')
            self.Clim_out[0, :] = np.append(
                self.modeltime[0],
                [self.bdot[0], self.Ts[0]])  # not sure if bdot or bdotSec
        if 'compaction_rate' in self.output_list:
            self.crate_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                      dtype='float32')
            self.crate_out[0, :] = np.append(self.modeltime[0],
                                             np.zeros(len(self.z)))
        if 'iso_sigmaD' in self.output_list:
            self.iso_sigmaD_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                           dtype='float32')
            self.iso_sigmaD_out[0, :] = np.append(self.modeltime[0],
                                                  self.iso_sigma['D'])
        if 'iso_sigma18' in self.output_list:
            self.iso_sigma18_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                            dtype='float32')
            self.iso_sigma18_out[0, :] = np.append(self.modeltime[0],
                                                   self.iso_sigma['18'])
        if 'iso_sigma17' in self.output_list:
            self.iso_sigma17_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                            dtype='float32')
            self.iso_sigma17_out[0, :] = np.append(self.modeltime[0],
                                                   self.iso_sigma['17'])
        if 'iso_dsigma2_dt_D' in self.output_list:
            self.iso_dsigma2_dt_D_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                                 dtype='float32')
            self.iso_dsigma2_dt_D_out[0, :] = np.append(
                self.modeltime[0], self.iso_dsigma2_dt['D'])
        if 'iso_dsigma2_dt_18' in self.output_list:
            self.iso_dsigma2_dt_18_out = np.zeros(
                (TWlen + 1, len(self.dz) + 1), dtype='float32')
            self.iso_dsigma2_dt_18_out[0, :] = np.append(
                self.modeltime[0], self.iso_dsigma2_dt['18'])
        if 'iso_dsigma2_dt_17' in self.output_list:
            self.iso_dsigma2_dt_17_out = np.zeros(
                (TWlen + 1, len(self.dz) + 1), dtype='float32')
            self.iso_dsigma2_dt_17_out[0, :] = np.append(
                self.modeltime[0], self.iso_dsigma2_dt['17'])

        try:
            print('rho_out size (MB):', self.rho_out.nbytes / 1.0e6)
        except:
            pass
        # set up initial grain growth (if specified in config file)
        if self.c['physGrain']:
            initr2 = read_init(self.c['resultsFolder'], self.c['spinFileName'],
                               'r2Spin')
            self.r2 = initr2[1:]
            r20 = self.r2
            if 'grainsize' in self.output_list:
                self.r2_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                       dtype='float32')
                self.r2_out[0, :] = np.append(self.modeltime[0], self.r2)
            else:
                self.r2_out = None
        else:
            self.r2 = None

        if self.c['physRho'] == 'Morris2014':
            self.THist = True
            initHx = read_init(self.c['resultsFolder'], self.c['spinFileName'],
                               'HxSpin')
            self.Hx = initHx[1:]
            if 'temp_Hx' in self.output_list:
                self.Hx_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                       dtype='float32')
                self.Hx_out[0, :] = np.append(self.modeltime[0], self.Hx)
            else:
                self.Hx_out = None
        else:
            self.THist = False

        if self.c['isoDiff']:
            self.del_z = init_del_z[1:]
            if 'isotopes' in self.output_list:
                self.iso_out = np.zeros((TWlen + 1, len(self.dz) + 1),
                                        dtype='float32')
                self.iso_out[0, :] = np.append(self.modeltime[0], self.del_z)
            else:
                self.iso_out = None

        self.dHAll = []

        bcoAgeMart, bcoDepMart, bcoAge815, bcoDep815 = self.update_BCO()
        LIZAgeMart, LIZDepMart = self.update_LIZ()
        intPhi = self.update_DIP()

        self.dHAll.append(0)
        dHOut = 0
        dHOutC = 0

        if 'DIP' in self.output_list:
            self.DIP_out = np.zeros((TWlen + 1, 4), dtype='float32')
            self.DIP_out[0, :] = np.append(self.modeltime[0],
                                           [intPhi, dHOut, dHOutC])
        if 'LIZ' in self.output_list:
            self.LIZ_out = np.zeros((TWlen + 1, 3), dtype='float32')
            self.LIZ_out[0, :] = np.append(self.modeltime[0],
                                           [LIZAgeMart, LIZDepMart])
        if 'BCO' in self.output_list:
            self.BCO_out = np.zeros((TWlen + 1, 5), dtype='float32')
            self.BCO_out[0, :] = np.append(
                self.modeltime[0],
                [bcoAgeMart, bcoDepMart, bcoAge815, bcoDep815])