Changeset 3007 for trunk/GSASIIscriptable.py
- Timestamp:
- Aug 15, 2017 3:33:29 PM (5 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/GSASIIscriptable.py
r3000 r3007 15 15 16 16 Supports a command line interface as well. 17 18 19 Look at :class:`G2Project` to start. 17 20 """ 18 21 from __future__ import division, print_function # needed? … … 22 25 import imp 23 26 import copy 24 import platform25 27 import os 26 28 import random as ran 27 import json28 29 29 30 import numpy.ma as ma … … 31 32 import numpy as np 32 33 import scipy as sp 33 import matplotlib as mpl34 34 35 35 import GSASIIpath 36 36 GSASIIpath.SetBinaryPath(False) # would rather have this in __name__ == '__main__' stanza 37 import GSASIIIO as G2IO38 import GSASIIfiles as G2fil39 37 import GSASIIobj as G2obj 40 38 import GSASIIpwd as G2pwd 41 import GSASIIstr IO as G2strIO39 import GSASIIstrMain as G2strMain 42 40 import GSASIIspc as G2spc 43 import GSASIIstrMain as G2strMain44 import GSASIImath as G2mth45 41 import GSASIIElem as G2elem 46 42 47 try: 48 import matplotlib.pyplot as plt 49 except ImportError: 50 plt = None 43 # Delay imports to not slow down small scripts 44 G2fil = None 45 PwdrDataReaders = [] 46 PhaseReaders = [] 47 48 49 def LoadG2fil(): 50 """Delay importing this module, it is slow""" 51 global G2fil 52 global PwdrDataReaders 53 global PhaseReaders 54 if G2fil is None: 55 import GSASIIfiles 56 G2fil = GSASIIfiles 57 PwdrDataReaders = G2fil.LoadImportRoutines("pwd", "Powder_Data") 58 PhaseReaders = G2fil.LoadImportRoutines("phase", "Phase") 59 51 60 52 61 def LoadDictFromProjFile(ProjFile): … … 351 360 generalData['F000X'] = F000X 352 361 generalData['F000N'] = F000N 362 import GSASIImath as G2mth 353 363 generalData['Mass'] = G2mth.getMass(generalData) 354 364 … … 368 378 filename = os.path.abspath(filename) 369 379 gsasii_version = str(GSASIIpath.GetVersionNumber()) 380 LoadG2fil() 381 import matplotlib as mpl 370 382 python_library_versions = G2fil.get_python_versions([mpl, np, sp]) 371 383 … … 463 475 Returns a 2-tuple of (Iparm1, Iparm2) parameters 464 476 """ 477 LoadG2fil() 465 478 ext = os.path.splitext(instfile)[1] 466 479 … … 634 647 635 648 class G2Project(G2ObjectWrapper): 649 """Represents an entire GSAS-II project.""" 636 650 def __init__(self, gpxfile=None, author=None, filename=None): 637 651 """Loads a GSAS-II project from a specified filename. … … 698 712 699 713 :returns: A :class:`G2PwdrData` object representing 700 the histogram""" 714 the histogram 715 """ 716 LoadG2fil() 701 717 datafile = os.path.abspath(os.path.expanduser(datafile)) 702 718 iparams = os.path.abspath(os.path.expanduser(iparams)) … … 704 720 histname, new_names, pwdrdata = load_pwd_from_reader( 705 721 pwdrreaders[0], iparams, 706 list(self.histogram_names()))722 [h.name for h in self.histograms()]) 707 723 if histname in self.data: 708 724 print("Warning - redefining histogram", histname) … … 724 740 725 741 :returns: A :class:`G2Phase` object representing the 726 new phase.""" 742 new phase. 743 """ 744 LoadG2fil() 727 745 phasefile = os.path.abspath(os.path.expanduser(phasefile)) 728 746 … … 732 750 733 751 phasename = phasename or phasereader.Phase['General']['Name'] 734 phaseNameList = list(self.phase_names())752 phaseNameList = [p.name for p in self.phases()] 735 753 phasename = G2obj.MakeUniqueLabel(phasename, phaseNameList) 736 754 phasereader.Phase['General']['Name'] = phasename … … 803 821 _deep_copy_into(from_=data, into=self.data) 804 822 805 def refine(self, newfile=None, printFile=None ):823 def refine(self, newfile=None, printFile=None, makeBack=False): 806 824 # index_ids will automatically save the project 807 825 self.index_ids() 808 826 # TODO G2strMain does not properly use printFile 809 G2strMain.Refine(self.filename )827 G2strMain.Refine(self.filename, makeBack=makeBack) 810 828 # Reload yourself 811 829 self.reload() … … 832 850 """Returns the histogram named histname, or None if it does not exist. 833 851 852 :param histname: The name of the histogram (str), or ranId or index. 834 853 :returns: A :class:`G2PwdrData` object, or None if 835 854 the histogram does not exist 855 836 856 .. seealso:: 837 :func:`~GSASIIscriptable.G2Project.histogram_names`838 857 :func:`~GSASIIscriptable.G2Project.histograms` 839 858 :func:`~GSASIIscriptable.G2Project.phase` 840 859 :func:`~GSASIIscriptable.G2Project.phases` 841 :func:`~GSASIIscriptable.G2Project.phase_names`842 860 """ 843 861 if histname in self.data: 844 862 return G2PwdrData(self.data[histname], self) 845 return None 863 histRanId = None 864 for key, val in G2obj.HistIdLookup.items(): 865 name, ranId = val 866 # histname can be either ranId (key) or index (val) 867 if ranId == histname or key == str(histname): 868 return self.histogram(name) 846 869 847 870 def histograms(self): 848 871 """Return a list of all histograms, as 849 872 :class:`G2PwdrData` objects 873 850 874 .. seealso:: 851 :func:`~GSASIIscriptable.G2Project.histogram_names`852 875 :func:`~GSASIIscriptable.G2Project.histograms` 853 876 :func:`~GSASIIscriptable.G2Project.phase` 854 877 :func:`~GSASIIscriptable.G2Project.phases` 855 :func:`~GSASIIscriptable.G2Project.phase_names`856 878 """ 857 return [self.histogram(name) for name in self.histogram_names()] 879 output = [] 880 for obj in self.names: 881 if len(obj) > 1 and obj[0] != u'Phases': 882 output.append(self.histogram(obj[0])) 883 return output 858 884 859 885 def phase_names(self): … … 861 887 862 888 :returns: A list of strings 889 863 890 .. seealso:: 864 891 :func:`~GSASIIscriptable.G2Project.histogram` 865 892 :func:`~GSASIIscriptable.G2Project.histograms` 866 :func:`~GSASIIscriptable.G2Project.histogram_names`867 893 :func:`~GSASIIscriptable.G2Project.phase` 868 894 :func:`~GSASIIscriptable.G2Project.phases` … … 880 906 :returns: A :class:`G2Phase` object 881 907 :raises: KeyError 908 882 909 .. seealso:: 883 :func:`~GSASIIscriptable.G2Project.histogram_names`884 910 :func:`~GSASIIscriptable.G2Project.histograms` 885 911 :func:`~GSASIIscriptable.G2Project.phase` 886 912 :func:`~GSASIIscriptable.G2Project.phases` 887 :func:`~GSASIIscriptable.G2Project.phase_names`888 913 """ 889 914 phases = self.data['Phases'] 890 915 if phasename in phases: 891 916 return G2Phase(phases[phasename], phasename, self) 917 phaseRanId = None 918 for key, val in G2obj.PhaseIdLookup.items(): 919 name, ranId = val 920 # phasename can be either ranId (key) or index (val) 921 if ranId == phasename or key == str(phasename): 922 return self.phase(name) 892 923 893 924 def phases(self): … … 896 927 897 928 :returns: A :class:`G2Phase` 929 898 930 .. seealso:: 899 931 :func:`~GSASIIscriptable.G2Project.histogram` 900 932 :func:`~GSASIIscriptable.G2Project.histograms` 901 :func:`~GSASIIscriptable.G2Project.histogram_names`902 933 :func:`~GSASIIscriptable.G2Project.phase` 903 :func:`~GSASIIscriptable.G2Project.phase_names`904 934 """ 905 return [self.phase(name) for name in self.phase_names()] 935 for obj in self.names: 936 if obj[0] == 'Phases': 937 return [self.phase(p) for p in obj[1:]] 938 return [] 906 939 907 940 def do_refinements(self, refinements, histogram='all', phase='all', … … 944 977 """Apply specified refinements to a given histogram(s) or phase(s). 945 978 979 Refinement parameters are categorize in three groups: 980 981 1. Histogram parameters 982 2. Phase parameters 983 3. Histogram-and-Phase (HAP) parameters 984 946 985 :param dict refinement: The refinements to be conducted 947 986 :param histogram: Either a name of a histogram (str), a list of 948 987 histogram names, or 'all' (default) 949 988 :param phase: Either a name of a phase (str), a list of phase names, or 950 'all' (default)""" 989 'all' (default) 990 991 .. seealso:: 992 :func:`~G2PwdrData.set_refinements` 993 :func:`~G2PwdrData.clear_refinements` 994 :func:`~G2Phase.set_refinements` 995 :func:`~G2Phase.clear_refinements` 996 :func:`~G2Phase.set_HAP_refinements` 997 :func:`~G2Phase.clear_HAP_refinements`""" 998 951 999 if histogram == 'all': 952 hists = [self.histogram(name) 953 for name in self.histogram_names()] 954 elif isinstance(histogram, str): 1000 hists = self.histograms() 1001 elif isinstance(histogram, str) or isinstance(histogram, int): 955 1002 hists = [self.histogram(histogram)] 956 1003 else: … … 958 1005 959 1006 if phase == 'all': 960 phases = [self.phase(name) for name in self.phase_names()]961 elif isinstance(phase, str) :1007 phases = self.phases() 1008 elif isinstance(phase, str) or isinstance(phase, int): 962 1009 phases = [self.phase(phase)] 963 1010 else: … … 975 1022 pwdr_set = {} 976 1023 phase_set = {} 1024 hap_set = {} 977 1025 for key, val in refinement.get('set', {}).items(): 978 1026 # Apply refinement options … … 981 1029 elif G2Phase.is_valid_refinement_key(key): 982 1030 phase_set[key] = val 1031 elif G2Phase.is_valid_HAP_refinement_key(key): 1032 hap_set[key] = val 983 1033 else: 984 print("Unknown refinement key:", key)1034 raise ValueError("Unknown refinement key", key) 985 1035 986 1036 for hist in hists: … … 988 1038 for phase in phases: 989 1039 phase.set_refinements(phase_set) 1040 for phase in phases: 1041 phase.set_HAP_refinements(hap_set, hists) 990 1042 991 1043 pwdr_clear = {} 992 1044 phase_clear = {} 1045 hap_clear = {} 993 1046 for key, val in refinement.get('clear', {}).items(): 994 1047 # Clear refinement options … … 997 1050 elif G2Phase.is_valid_refinement_key(key): 998 1051 phase_clear[key] = val 1052 elif G2Phase.is_valid_HAP_refinement_key(key): 1053 hap_set[key] = val 999 1054 else: 1000 print("Unknown refinement key:", key)1055 raise ValueError("Unknown refinement key", key) 1001 1056 1002 1057 for hist in hists: … … 1004 1059 for phase in phases: 1005 1060 phase.clear_refinements(phase_clear) 1061 for phase in phases: 1062 phase.clear_HAP_refinements(hap_clear, hists) 1006 1063 1007 1064 def index_ids(self): 1065 import GSASIIstrIO as G2strIO 1008 1066 self.save() 1009 1067 return G2strIO.GetUsedHistogramsAndPhases(self.filename) … … 1042 1100 Automatically converts string phase, hist, or atom names into the ID required 1043 1101 by G2VarObj.""" 1102 1044 1103 if reloadIdx: 1045 1104 self.index_ids() … … 1143 1202 1144 1203 class G2PwdrData(G2ObjectWrapper): 1145 """Wraps a Pow eder Data Histogram."""1204 """Wraps a Powder Data Histogram.""" 1146 1205 def __init__(self, data, proj): 1147 1206 self.data = data … … 1168 1227 for key in ['R', 'Rb', 'wR', 'wRb', 'wRmin']} 1169 1228 1229 @property 1230 def id(self): 1231 return G2obj.HistRanIdLookup[self.ranId] 1232 1170 1233 def fit_fixed_points(self): 1171 1234 """Attempts to apply a background fit to the fixed points currently specified.""" 1172 1173 1235 def SetInstParms(Inst): 1174 1236 dataType = Inst['Type'][0] … … 1243 1305 1244 1306 def plot(self, Yobs=True, Ycalc=True, Background=True, Residual=True): 1245 if plt: 1307 try: 1308 import matplotlib.pyplot as plt 1246 1309 data = self['data'][1] 1247 1310 if Yobs: … … 1253 1316 if Residual: 1254 1317 plt.plot(data[0], data[5], label="Residual") 1318 except ImportError: 1319 pass 1255 1320 1256 1321 def set_refinements(self, refs): … … 1326 1391 1327 1392 def clear_refinements(self, refs): 1328 """Clears the refinement parameter 'key' and its associated value.""" 1393 """Clears the refinement parameter 'key' and its associated value. 1394 1395 :param dict refs: A dictionary of parameters to clear.""" 1329 1396 for key, value in refs.items(): 1330 1397 if key == 'Limits': … … 1380 1447 1381 1448 :param str atomlabel: The name of the atom (e.g. "O2") 1382 1383 1449 :returns: A :class:`G2AtomRecord` object 1384 representing the atom.""" 1450 representing the atom. 1451 """ 1385 1452 # Consult GSASIIobj.py for the meaning of this 1386 1453 cx, ct, cs, cia = self.data['General']['AtomPtrs'] … … 1395 1462 1396 1463 :returns: A list of :class:`G2AtomRecord` objects. See 1397 also :func:`~GSASIIscriptable.G2Phase.atom`""" 1464 also :func:`~GSASIIscriptable.G2Phase.atom` 1465 """ 1398 1466 ptrs = self.data['General']['AtomPtrs'] 1399 1467 output = [] … … 1413 1481 return self.data['ranId'] 1414 1482 1483 @property 1484 def id(self): 1485 return G2obj.PhaseRanIdLookup[self.ranId] 1486 1415 1487 def cell_dict(self): 1416 1488 """Returns a dictionary of the cell parameters, with keys: … … 1424 1496 1425 1497 def set_refinements(self, refs): 1498 """Sets the refinement parameter 'key' to the specification 'value' 1499 1500 :param dict refs: A dictionary of the parameters to be set. 1501 1502 :returns: None""" 1426 1503 for key, value in refs.items(): 1427 1504 if key == "Cell": … … 1447 1524 1448 1525 def clear_refinements(self, refs): 1526 """Clears a given set of parameters. 1527 1528 :param dict refs: The parameters to clear""" 1449 1529 for key, value in refs.items(): 1450 1530 if key == "Cell": … … 1465 1545 else: 1466 1546 raise ValueError("Unknown key:", key) 1547 1548 def set_HAP_refinements(self, refs, histograms='all'): 1549 """Sets the given HAP refinement parameters between this phase and 1550 the given histograms 1551 1552 :param dict refs: A dictionary of the parameters to be set. 1553 :param histograms: Either 'all' (default) or a list of the histograms 1554 whose HAP parameters will be set with this phase. Histogram and phase 1555 must already be associated 1556 1557 :returns: None 1558 """ 1559 if histograms == 'all': 1560 histograms = self['Histograms'].values() 1561 else: 1562 histograms = [self['Histograms'][h.name] for h in histograms] 1563 1564 for key, val in refs.items(): 1565 for h in histograms: 1566 if key == 'Babinet': 1567 try: 1568 sets = list(val) 1569 except ValueError: 1570 sets = ['BabA', 'BabU'] 1571 for param in sets: 1572 if param not in ['BabA', 'BabU']: 1573 raise ValueError("Not sure what to do with" + param) 1574 for hist in histograms: 1575 hist['Babinet'][param][1] = True 1576 elif key == 'Extinction': 1577 for h in histograms: 1578 h['Extinction'][1] = True 1579 elif key == 'HStrain': 1580 for h in histograms: 1581 hist['HStrain'][1] = [True for p in hist['Hstrain'][0]] 1582 elif key == 'Mustrain': 1583 for h in histograms: 1584 mustrain = h['Mustrain'] 1585 newType = None 1586 if isinstance(val, str): 1587 if val in ['isotropic', 'uniaxial', 'generalized']: 1588 newType = val 1589 else: 1590 raise ValueError("Not a Mustrain type: " + val) 1591 elif isinstance(val, dict): 1592 newType = val.get('type', None) 1593 direction = val.get('direction', None) 1594 1595 if newType: 1596 mustrain[0] = newType 1597 if newType == 'isotropic': 1598 mustrain[2][0] = True 1599 mustrain[5] = [False for p in mustrain[4]] 1600 elif newType == 'uniaxial': 1601 pass 1602 else: # newtype == 'generalized' 1603 mustrain[2] = [False for p in mustrain[1]] 1604 if direction: 1605 direction = [int(n) for n in direction] 1606 if len(direction) != 3: 1607 raise ValueError("Expected hkl, found", direction) 1608 mustrain[3] = direction 1609 elif key == 'Pref.Ori.': 1610 for h in histograms: 1611 h['Pref.Ori.'][2] = True 1612 elif key == 'Show': 1613 for h in histograms: 1614 h['Show'] = True 1615 elif key == 'Size': 1616 raise NotImplementedError() 1617 elif key == 'Use': 1618 for h in histograms: 1619 h['Use'] = True 1620 elif key == 'Scale': 1621 for h in histograms: 1622 h['Scale'][1] = False 1623 1624 def clear_HAP_refinements(self, refs, histograms='all'): 1625 """Clears the given HAP refinement parameters between this phase and 1626 the given histograms 1627 1628 :param dict refs: A dictionary of the parameters to be cleared. 1629 :param histograms: Either 'all' (default) or a list of the histograms 1630 whose HAP parameters will be cleared with this phase. Histogram and 1631 phase must already be associated 1632 1633 :returns: None 1634 """ 1635 if histograms == 'all': 1636 histograms = self['Histograms'].values() 1637 else: 1638 histograms = [self['Histograms'][h.name] for h in histograms] 1639 1640 for key, val in refs.items(): 1641 for h in histograms: 1642 if key == 'Babinet': 1643 try: 1644 sets = list(val) 1645 except ValueError: 1646 sets = ['BabA', 'BabU'] 1647 for param in sets: 1648 if param not in ['BabA', 'BabU']: 1649 raise ValueError("Not sure what to do with" + param) 1650 for hist in histograms: 1651 hist['Babinet'][param][1] = False 1652 elif key == 'Extinction': 1653 for h in histograms: 1654 h['Extinction'][1] = False 1655 elif key == 'HStrain': 1656 for h in histograms: 1657 hist['HStrain'][1] = [False for p in hist['Hstrain'][0]] 1658 elif key == 'Mustrain': 1659 for h in histograms: 1660 mustrain = h['Mustrain'] 1661 mustrain[2] = [False for p in mustrain[1]] 1662 mustrain[5] = [False for p in mustrain[4]] 1663 elif key == 'Pref.Ori.': 1664 for h in histograms: 1665 h['Pref.Ori.'][2] = False 1666 elif key == 'Show': 1667 for h in histograms: 1668 h['Show'] = False 1669 elif key == 'Size': 1670 raise NotImplementedError() 1671 elif key == 'Use': 1672 for h in histograms: 1673 h['Use'] = False 1674 elif key == 'Scale': 1675 for h in histograms: 1676 h['Scale'][1] = False 1467 1677 1468 1678 … … 1544 1754 hists = proj.histograms() 1545 1755 for h in hists: 1546 print(fname, h.name)1756 print(fname, "hist", h.id, h.name) 1547 1757 if phases: 1548 phase s= proj.phases()1549 for p in phase s:1550 print(fname, p.name)1758 phase_list = proj.phases() 1759 for p in phase_list: 1760 print(fname, "phase", p.id, p.name) 1551 1761 1552 1762 … … 1618 1828 # print("Done") 1619 1829 1620 PwdrDataReaders = G2fil.LoadImportRoutines("pwd", "Powder_Data")1621 PhaseReaders = G2fil.LoadImportRoutines("phase", "Phase")1622 1830 if __name__ == '__main__': 1623 1831 main() … … 1672 1880 # print(key, ":", sep='') 1673 1881 # pretty.pprint(val) 1674
Note: See TracChangeset
for help on using the changeset viewer.