示例#1
0
    def _convertNamelists(self, namelists):
        for name in namelists.keys():
            nl = Namelist(name)
            for p in namelists[name]:
                nl.add(p[0], p[1])

            self.namelists[name] = nl
示例#2
0
    def setNamelist(self, namelist):
        """
        Sets namelist as dictionaty:

            namelist: (dict) -- Dictionary of namelist

        Format:
        {"name":      <namelist name>,
         "params":    {param1:    value1,
                       param2:    value2,
                       ...}}

        Example:
        {"name":      "control",
         "params":    {calculation:   'scf',
                       restart_mode:  'from_scratch',
                       tprnfor:       .true.}}
        """
        if not namelist:    # Ignore empty card
            return

        self._checkDictFormat(namelist, NAMELIST_KEYS, NAMELIST_REQ)

        nl       = Namelist(namelist["name"])
        if namelist.has_key("params"):
            for p in namelist["params"].keys():
                value   = namelist["params"][p]
                nl.set(p, value)

        self._fnamelists.append(nl)
示例#3
0
    def setNamelist(self, namelist):
        """
        Sets namelist as dictionaty:

            namelist: (dict) -- Dictionary of namelist

        Format:
        {"name":      <namelist name>,
         "params":    {param1:    value1,
                       param2:    value2,
                       ...}}

        Example:
        {"name":      "control",
         "params":    {calculation:   'scf',
                       restart_mode:  'from_scratch',
                       tprnfor:       .true.}}
        """
        if not namelist:  # Ignore empty card
            return

        self._checkDictFormat(namelist, NAMELIST_KEYS, NAMELIST_REQ)

        nl = Namelist(namelist["name"])
        if namelist.has_key("params"):
            for p in namelist["params"].keys():
                value = namelist["params"][p]
                nl.set(p, value)

        self._fnamelists.append(nl)
示例#4
0
 def _convertNamelists(self, namelists):
     """Converts dictionary to Namelist"""
     for name in namelists.keys():
         nl      = Namelist(name)
         for p in namelists[name]:
             nl.add(p[0], p[1])
             
         self.namelists[name] = nl
示例#5
0
    def test_qeinput_namelist(self):
        input   = QEInput()
        nl      = Namelist("control")
        nl.set("title", "'Ni'")
        input.addNamelist(nl)
        nl2     = input.namelist("phonon")
        self.assertEqual(input.toString(), fixtures.assertNewNamelist)

        input.removeNamelist("control")
        self.assertEqual(input.toString(), fixtures.assertNewNamelist2)
示例#6
0
    def test_qeinput_namelist(self):
        input = QEInput()
        nl = Namelist("control")
        nl.set("title", "'Ni'")
        input.addNamelist(nl)
        nl2 = input.namelist("phonon")
        self.assertEqual(input.toString(), fixtures.assertNewNamelist)

        input.removeNamelist("control")
        self.assertEqual(input.toString(), fixtures.assertNewNamelist2)
示例#7
0
 def test_namelist_set_get(self):
     nl  = Namelist("control")
     self.assertEqual(nl.get("title"), None)
     
     nl.set("title", "hello")
     self.assertEqual(nl.get("title"), "hello")
     self.assertEqual(nl.get("title", quotes=True), "hello") # should not add quotes
     
     nl.set("Title", "'hello'")
     self.assertEqual(nl.get("titlE", quotes=False), "hello")
     self.assertEqual(nl.get("title"), "'hello'")
示例#8
0
def _to_str_nml(params):
    """ Write with namelist format
    """
    # convert to Namelist class
    groups = odict()
    for k, g in groupby(params, lambda x: x.group):
        if k == "":
            print list(g)
            raise ValueError("Group not defined. Cannot write to namelist. See Parameters' set_group() method.")
        groups[k] = odict([(p.name, p.value) for p in g])
    nml = Namelist(groups)
    string = nml.dump()
    return string
示例#9
0
 def some_opts_extr(self):
     try:
         names = np.sort(listdir(self.frm.folder_name))
     except TypeError:
         self.frm.status.set('it seems you should show me the folder, Doc')
         return False
     for name in names:
         if fnmatch(name, '*.in'):
             inputname = self.frm.folder_name + '/' + name
     No_ion = int(
         Namelist(inputname).get('ions').get('par')[0].get('no_ion')[0])
     self.frm.n_nod = int(
         Namelist(inputname).get('option').get('par')[0].get('nd_para')
         [0]) - 1
     return No_ion
示例#10
0
    def test_namelist_remove_exists(self):
        nl = Namelist("control")
        nl.set("title", "hello")
        self.assertTrue(nl.exists("title"))
        self.assertTrue(nl.exists("Title"))

        nl.remove("title")
        self.assertFalse(nl.exists("title"))
示例#11
0
 def __setitem__(self, key, value):
     if key == 'k0':
         # convenience variable for harmonic potential
         self['rk2'] = float(value)
         self['rk3'] = float(value)
     elif key == 'r0':
         # convenience variable for harmonic potential
         self['r2'] = float(value)
         self['r3'] = float(value)
         self['r1'] = self._r1_harmonic
         self['r4'] = self._r4_harmonic
     elif key in ['rk2','rk3']:
         # some restraints use internal units (e.g. angles)
         Namelist.__setitem__(self,key,float(value)) 
     else:
         Namelist.__setitem__(self,key,value)
示例#12
0
    def setParam(self, namelist, param, value=""):
        """
        Set parameter of the namelist. If the parameter or namelist do not exist,
        it creates them.

            namelist: (str) -- Name of the namelist
            param: (str) -- Name of the parameter
            value: (str) -- Valur of the parameter
        """
        for nl in self._fnamelists:
            if nl.name() == namelist:
                nl.set(param, value)
                return

        # namelist doesn't exists
        nl  = Namelist(namelist)
        nl.set(param, value)
        self._fnamelists.append(nl)
示例#13
0
    def setParam(self, namelist, param, value=""):
        """
        Set parameter of the namelist. If the parameter or namelist do not exist,
        it creates them.

            namelist: (str) -- Name of the namelist
            param: (str) -- Name of the parameter
            value: (str) -- Valur of the parameter
        """
        for nl in self._fnamelists:
            if nl.name() == namelist:
                nl.set(param, value)
                return

        # namelist doesn't exists
        nl = Namelist(namelist)
        nl.set(param, value)
        self._fnamelists.append(nl)
示例#14
0
    def test_namelist_remove_exists(self):
        nl  = Namelist("control")
        nl.set("title", "hello")
        self.assertTrue(nl.exists("title"))
        self.assertTrue(nl.exists("Title"))

        nl.remove("title")
        self.assertFalse(nl.exists("title"))
示例#15
0
def _parse_file_nml(cls, string):
    nml = Namelist.parse_file(string)

    # flatten namelist to store it in the Parameters class
    params = cls()
    for g in nml.groups:
        for nm in nml.groups[g]:
            p = Parameter(name=nm, value=nml.groups[g][nm], group=g)
            params.append(p)
    return params
示例#16
0
 def __str__(self):
     if len(self.keys()) > 0: # Don't print empty namelists.
         if self.name is not None:
             return Namelist.__str__(self)
         else:
             # Modify the Namelist print behavior for a NoneType namelist.
             # Namely, don't print the "&name" section and ending slash.
             return '\n'.join([' %s=%s'%(k,v) for k,v in self.iteritems()])
     else:
         return ''
示例#17
0
def testCreateConfig():
    print "Testing creation of config file"
    qe = QEInput()
    nl = Namelist('control')
    nl.add('title', "'Ni'")
    nl.add('restart_mode', "'from_scratch'")
    print "Adding parameters to namelist:\n%s" % nl.toString()
    nl.set('title', "'Fe'")
    qe.addNamelist(nl)
    print "Adding namelist to QEInput:\n%s" % qe.toString()

    c = Card('atomic_species')
    c.addLine('Ni  26.98  Ni.pbe-nd-rrkjus.UPF')
    print "Adding line to card:\n%s" % c.toString()
    qe.addCard(c)
    print "Adding card to QEInput:\n%s" % qe.toString()
示例#18
0
    def _createNamelist(self, name):
        """
        Creates namelist specified by name

            name: (str) -- Name of the namelist
        """
        if not name in self.namelistRef:    # If not standard card, ignore it
            return None

        # Otherwise create a new namelist
        nl  = Namelist(name)
        self.namelists[name] = nl
        return nl
示例#19
0
def testCreateConfig():
    print "Testing creation of config file"
    qe  = QEInput()
    nl  = Namelist('control')
    nl.add('title', "'Ni'")
    nl.add('restart_mode', "'from_scratch'")
    print "Adding parameters to namelist:\n%s" % nl.toString()
    nl.set('title', "'Fe'")
    qe.addNamelist(nl)
    print "Adding namelist to QEInput:\n%s" % qe.toString()

    c = Card('atomic_species')
    c.addLine('Ni  26.98  Ni.pbe-nd-rrkjus.UPF')
    print "Adding line to card:\n%s" % c.toString()
    qe.addCard(c)
    print "Adding card to QEInput:\n%s" % qe.toString()
示例#20
0
 def __str__(self):
     # Convert list values to strings.
     self['iat'] = ','.join([str(i) for i in self['iat']])
     try:
         self['rstwt'] = ','.join([str(i) for i in self['rstwt']])
     except KeyError:
         pass
     txt = Namelist.__str__(self)
     # Convert back to lists.
     self['iat'] = [int(i) for i in self['iat'].split(',')]
     try:
         self['rstwt'] = [float(i) for i in self['rstwt'].split(',')]
     except KeyError:
         pass
     return txt
示例#21
0
文件: main.py 项目: liboisq/WO2PV
def get_pv(forcing, output, n1=0, n2=10000, option="timeseries"):
    """ forcing : nc file assumed to be located in Forcings/ e.g. "SIRTA_all" 
        output : name of output file containing PV production, stored in PV_Outputs directory       
        n1 and n2 : left and right indicess for partial computations along timeseries
        option : specify the type of forcing to optimize vectorial computations
    """
    print("----------Namelist loading----------------")
    nam = Namelist(
    )  # all options should be hardcoded in the Namelist() attributes

    print("----------Atmosphere loading----------------")
    # build an Atmosphere object from an nc file. Such object can be built directly from np.arrays
    atm = Atmosphere(*tools.get_atm_from_ncfile(
        forcing=forcing, albedo=nam.albedo, n1=n1, n2=n2))
    atm.compute_sun()  # to compute the full series of sza, saa, sw_toa

    # define PV panel from information contained in Namelist
    print("----------Module initialization----------------")
    panel = Panel(
        name=nam.panel_name,
        technology=nam.panel_technology,
        beta=nam.panel_beta,
        gamma=nam.panel_gamma,
        method_FF=nam.method_FF,
        SR_method=nam.SR_method,
        namelist=nam
    )  # get physical characteristics of the panel from a description file - here SIRTA panel used for consistency

    # call pv_interface to handle large arrays and successive (and possibly multi-thread) calls to pv_production
    t1 = time.time()
    if option == "timeseries":
        power_simul = pv_interface_timeseries(nam, atm, panel)
    elif option == "atlas":
        power_simul = pv_interface_atlas(nam, atm, panel)

    # save PV outputs
    np.savetxt("PV_Outputs/%s.dat" % output, power_simul)
    t2 = time.time()
    print("Time to run the PV code = %s seconds" % (t2 - t1))

    return atm.dates, power_simul, atm.lat, atm.lon
示例#22
0
 def __getitem__(self, key):
     try:
         return Namelist.__getitem__(self,key)
     except KeyError:
         self[key] = value = self.default(key)
         return value
示例#23
0
 def test_namelist_name(self):
     nl = Namelist("Control")
     self.assertEqual(nl.name(), "control")
     nl.setName("SyStem")
     self.assertEqual(nl.name(), "system")
示例#24
0
 def __init__(self, *args, **kwargs):
     Namelist.__init__(self,'rst',' ','=',' ',72,72,*args,**kwargs)
示例#25
0
 def createNamelist(self, name):
     """Creates namelist and adds to QEInput. """
     nl = Namelist(name)
     self.namelists[name] = nl
示例#26
0
    def test_namelist_set_get(self):
        nl = Namelist("control")
        self.assertEqual(nl.get("title"), None)

        nl.set("title", "hello")
        self.assertEqual(nl.get("title"), "hello")
        self.assertEqual(nl.get("title", quotes=True),
                         "hello")  # should not add quotes

        nl.set("Title", "'hello'")
        self.assertEqual(nl.get("titlE", quotes=False), "hello")
        self.assertEqual(nl.get("title"), "'hello'")
示例#27
0
 def test_namelist_tostring(self):
     nl = Namelist("control")
     nl.set("title", "hello")
     self.assertEqual(nl.toString(), fixtures.assertNL)
     self.assertEqual(nl.toString(indent=3), fixtures.assertNL_space_3)
示例#28
0
 def test_namelist_name(self):
     nl  = Namelist("Control")
     self.assertEqual(nl.name(), "control")
     nl.setName("SyStem")
     self.assertEqual(nl.name(), "system")
示例#29
0
 def __init__(self, name, engine, *args, **kwargs):
     Namelist.__init__(self,name,line_prefix=' ',name_value_separator=' = ',
                       value_separator=', ',max_namevalues_per_line=72,
                       max_chars_per_line=72,*args,**kwargs)
     self.engine = engine
示例#30
0
#!/usr/bin/env python3

from namelist import Namelist

control = Namelist(name="CONTROL")
control.set_val("calculation", 'scf')
control.set_val("prefix", "scf.pbe.ecut-80")
control.set_val("outdir", "./scratch/")
control.set_val("pseudo_dir", "/home/altoidnerd/.data/PSEUDOPOTENTIALS/")
control.set_val("verbosity", "high")
control.set_val("title", "p-dichlorobenzene-efg")
control.set_val("restart_mode", "from_scratch")
control.set_val("forc_conv_thr", 1.0e-4)
control.set_val("disk_io", "low")
control.set_val("wfcollect", ".false.")

for key in ["tstress", "tprnfor", "lorbm", "lberry", "ikpoint_dir"]:
    control.set_val(key, ".true.")

system = Namelist("SYSTEM")
key_value_pairs = [("ibrav", 0), ('a', 9.558), ('c', "8.981"), ("ecutwfc", 60),
                   ("ecutrho", 600), ("occupations", 'smearing'),
                   ('smearing', 'fermi-dirac'), ('degauss', .00367),
                   ('nat', 70), ('ntyp', '6')]

for (key, value) in key_value_pairs:
    system.set_val(key, value)

electrons_dict = {
    "conv_thr": 1e-7,
    "diago_thr_init": 1e-4,
示例#31
0
 def test_namelist_tostring(self):
     nl  = Namelist("control")
     nl.set("title", "hello")
     self.assertEqual(nl.toString(), fixtures.assertNL)
     self.assertEqual(nl.toString(indent=3), fixtures.assertNL_space_3)
示例#32
0
		def p_subroutine_statement_namelist(p):
			'subroutine_statement : NAMELIST SLASH ID SLASH namelist_variables'
			p[0] = Namelist(p[3], p[5])