source: trunk/readexp.tcl @ 1177

Last change on this file since 1177 was 1177, checked in by toby, 14 years ago

fix missing scale factor record

  • Property svn:keywords set to Author Date Revision Id
File size: 121.4 KB
Line 
1# $Id: readexp.tcl 1177 2011-10-25 14:46:19Z toby $
2# Routines to deal with the .EXP "data structure"
3set expmap(Revision) {$Revision: 1177 $ $Date: 2011-10-25 14:46:19 +0000 (Tue, 25 Oct 2011) $}
4
5#  The GSAS data is read from an EXP file.
6#   ... reading an EXP file into an array
7# returns -1 on error
8# returns 0 if the file is old-style UNIX format (no CR/LF)
9# returns 1 if the file is 80 char/line + cr/lf
10# returns 2 if the file is sequential but not fixed-record length
11proc expload {expfile "ns {}"} {
12    # expfile is the path to the data file.
13    # ns is the namespace to place the output array (default is global)
14    if {$ns != ""} {
15        namespace eval $ns {}
16    }
17    if [catch {set fil [open "$expfile" r]}] {
18        tk_dialog .expFileErrorMsg "File Open Error" \
19                "Unable to open file $expfile" error 0 "Exit" 
20        return -1
21    }
22    fconfigure $fil -translation lf
23    set len [gets $fil line]
24    if {[string length $line] != $len} {
25        tk_dialog .expConvErrorMsg "old tcl" \
26                "You are using an old version of Tcl/Tk and your .EXP file has binary characters; run convstod or upgrade" \
27                error 0 "Exit"
28        return -1
29    }
30    catch {
31        unset ${ns}::exparray
32    }
33    if {$len > 160} {
34        set fmt 0
35        # a UNIX-type file
36        set i1 0
37        set i2 79
38        while {$i2 < $len} {
39            set nline [string range $line $i1 $i2]
40            incr i1 80
41            incr i2 80
42            set key [string range $nline 0 11]
43            set ${ns}::exparray($key) [string range $nline 12 end]
44        }
45    } else {
46        set fmt 1
47        while {$len > 0} {
48            set key [string range $line 0 11]
49            set ${ns}::exparray($key) [string range $line 12 79]
50            if {$len != 81 || [string range $line end end] != "\r"} {set fmt 2}
51            set len [gets $fil line]
52        }
53    }
54    close $fil
55    return $fmt
56}
57
58proc createexp {expfile title} {
59    global exparray expmap
60    catch {unset exparray}
61    foreach key   {"     VERSION" "      DESCR" "ZZZZZZZZZZZZ" " EXPR NPHAS"} \
62            value {"   6"         ""            "  Last EXP file record" ""} {
63        # truncate long keys & pad short ones
64        set key [string range "$key        " 0 11]
65        set exparray($key) $value
66    }
67    expinfo title set $title
68    exphistory add " created readexp.tcl [lindex $expmap(Revision) 1] [clock format [clock seconds] -format %Y-%m-%dT%T]"
69    expwrite $expfile
70}
71
72# get information out from an EXP file
73#   creates the following entries in global array expmap
74#     expmap(phaselist)     gives a list of defined phases
75#     expmap(phasetype)     gives the phase type for each defined phase
76#                           =1 nuclear; 2 mag+nuc; 3 mag; 4 macro
77#     expmap(atomlist_$p)   gives a list of defined atoms in phase $p
78#     expmap(htype_$n)      gives the GSAS histogram type for histogram (all)
79#     expmap(powderlist)    gives a list of powder histograms in use
80#     expmap(phaselist_$n)  gives a list of phases used in histogram $n
81#     expmap(nhst)          the number of GSAS histograms
82#
83proc mapexp {} {
84    global expgui expmap exparray
85    # clear out the old array
86    set expmap_Revision $expmap(Revision)
87    unset expmap
88    set expmap(Revision) $expmap_Revision
89    # apply any updates to the .EXP file
90    updateexpfile
91    # get the defined phases
92    set line [readexp " EXPR NPHAS"]
93#    if {$line == ""} {
94#       set msg "No EXPR NPHAS entry. This is an invalid .EXP file"
95#       tk_dialog .badexp "Error in EXP" $msg error 0 Exit
96#       destroy .
97#    }
98    set expmap(phaselist) {}
99    set expmap(phasetype) {}
100    # loop over phases
101    foreach iph {1 2 3 4 5 6 7 8 9} {
102        set i5s [expr {($iph - 1)*5}]
103        set i5e [expr {$i5s + 4}]
104        set flag [string trim [string range $line $i5s $i5e]]
105        if {$flag == ""} {set flag 0}
106        if $flag {
107            lappend expmap(phaselist) $iph
108            lappend expmap(phasetype) $flag
109        }
110    }
111    # get the list of defined atoms for each phase
112    foreach iph $expmap(phaselist) {
113        set expmap(atomlist_$iph) {}
114        if {[lindex $expmap(phasetype) [expr {$iph - 1}]] != 4} {
115            foreach key [array names exparray "CRS$iph  AT*A"] {
116                regexp { AT *([0-9]+)A} $key a num
117                lappend expmap(atomlist_$iph) $num
118            }
119        } else {
120            foreach key [array names exparray "CRS$iph  AT*"] {
121                scan [string range $key 8 11] %x atm
122                lappend expmap(atomlist_$iph) $atm
123            }
124        }
125        # note that sometimes an .EXP file contains more atoms than are actually defined
126        # drop the extra ones
127        set expmap(atomlist_$iph) [lsort -integer $expmap(atomlist_$iph)]
128        set natom [phaseinfo $iph natoms]
129        if {$natom != [llength $expmap(atomlist_$iph)]} {
130            set expmap(atomlist_$iph) [lrange $expmap(atomlist_$iph) 0 [expr {$natom-1}]]
131        }
132    }
133    # now get the histogram types
134    set expmap(nhst) [string trim [readexp { EXPR  NHST }]]
135    set n 0
136    set expmap(powderlist) {}
137    for {set i 0} {$i < $expmap(nhst)} {incr i} {
138        set ihist [expr {$i + 1}]
139        if {[expr {$i % 12}] == 0} {
140            incr n
141            set line [readexp " EXPR  HTYP$n"]
142            if {$line == ""} {
143                set msg "No HTYP$n entry for Histogram $ihist. This is an invalid .EXP file"
144                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
145            }
146            set j 0
147        } else {
148            incr j
149        }
150        set expmap(htype_$ihist) [string range $line [expr 2+5*$j] [expr 5*($j+1)]]
151        # is this a dummy histogram?
152        if {$ihist <=9} {
153            set key "HST  $ihist DUMMY"
154        } else {
155            set key "HST $ihist DUMMY"
156        }
157        # at least for now, ignore non-powder histograms
158        if {[string range $expmap(htype_$ihist) 0 0] == "P" && \
159                [string range $expmap(htype_$ihist) 3 3] != "*"} {
160            if {[existsexp $key]} {
161                set expmap(htype_$ihist) \
162                        [string range $expmap(htype_$ihist) 0 2]D
163            }
164            lappend expmap(powderlist) $ihist
165        }
166    }
167
168    # now process powder histograms
169    foreach ihist $expmap(powderlist) {
170        # make a 2 digit key -- hh
171        if {$ihist < 10} {
172            set hh " $ihist"
173        } else {
174            set hh $ihist
175        }
176        set line [readexp "HST $hh NPHAS"]
177        if {$line == ""} {
178            set msg "No NPHAS entry for Histogram $ihist. This is an invalid .EXP file"
179            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
180        }
181        set expmap(phaselist_$ihist) {}
182        # loop over phases
183        foreach iph {1 2 3 4 5 6 7 8 9} {
184            set i5s [expr {($iph - 1)*5}]
185            set i5e [expr {$i5s + 4}]
186            set flag [string trim [string range $line $i5s $i5e]]
187            if {$flag == ""} {set flag 0}
188            if $flag {lappend expmap(phaselist_$ihist) $iph}
189        }
190    }
191    # load the constrained parameters
192    atom_constraint_load
193    # construct tables of mapped atoms in rigid bodies
194    foreach phase $::expmap(phaselist) {
195        set expmap(rbatoms_$phase) {}
196        foreach bodnum [RigidBodyList] {
197            set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodnum] 1] 0] 3]]
198            foreach mapnum [RigidBodyMappingList $phase $bodnum] {
199                set atomnum [lindex [ReadRigidBodyMapping $phase $bodnum $mapnum] 0]
200                set st [lsearch $::expmap(atomlist_$phase) $atomnum]
201                set en [expr {$st+$natoms-1}]
202                set atoms [lrange $::expmap(atomlist_$phase) $st $en]
203                set expmap(rbatoms_$phase) [concat $expmap(rbatoms_$phase) $atoms]
204            }
205        }
206    }
207    set expgui(mapstat) 1
208}
209
210# this routine is called to update changes in the .EXP file
211proc updateexpfile {} {
212    global exparray
213    # change "CRSx  ODFxxx" records to "CRSx  OD xxx" records
214    # needed by the June 8, 2005 GSAS release
215    set ODFlist [array names exparray "CRS?  ODF*"]
216    if {[llength $ODFlist] > 0} {
217        catch {incr ::expgui(changed)}
218        foreach key $ODFlist {
219            regsub "ODF" $key "OD " newkey
220            set exparray($newkey) $exparray($key)
221            unset exparray($key)
222        }
223    }
224}
225
226
227# return the value for a ISAM key
228proc readexp {key} {
229    global exparray
230    # truncate long keys & pad short ones
231    set key [string range "$key        " 0 11]
232    if [catch {set val $exparray($key)}] {
233        global expgui
234        if $expgui(debug) {puts "Error accessing record $key"}
235        return ""
236    }
237    return $val
238}
239
240# return the number of records matching ISAM key (may contain wildcards)
241proc existsexp {key} {
242    global exparray
243    # key can contain wild cards so don't pad
244    return [llength [array names exparray  $key]]
245}
246
247
248# replace a section of the exparray with $value
249#   replace $char characters starting at character $start (numbered from 1)
250proc setexp {key value start chars} {
251    global exparray
252    # truncate long keys & pad short ones
253    set key [string range "$key        " 0 11]
254    if [catch {set exparray($key)}] {
255        global expgui
256        if $expgui(debug) {puts "Error accessing record $key"}
257        return ""
258    }
259
260    # pad value to $chars
261    set l0 [expr {$chars - 1}]
262    set value [string range "$value                                           " 0 $l0]
263
264    if {$start == 1} {
265        set ret {}
266        set l1 $chars
267    } else {
268        set l0 [expr {$start - 2}]
269        set l1 [expr {$start + $chars - 1}]
270        set ret [string range $exparray($key) 0 $l0]
271    }
272    append ret $value [string range $exparray($key) $l1 end]
273    set exparray($key) $ret
274}
275
276proc makeexprec {key} {
277    global exparray
278    # truncate long keys & pad short ones
279    set key [string range "$key        " 0 11]
280    if [catch {set exparray($key)}] {
281        # set to 68 blanks
282        set exparray($key) [format %68s " "]
283    }
284}
285
286# delete an exp record
287# returns 1 if OK; 0 if not found
288proc delexp {key} {
289    global exparray
290    # truncate long keys & pad short ones
291    set key [string range "$key        " 0 11]
292    if [catch {unset exparray($key)}] {
293        return 0
294    }
295    return 1
296}
297
298# test an argument if it is a valid number; reform the number to fit
299proc validreal {val length decimal} {
300    upvar $val value
301    # is this a number?
302    if [catch {expr {$value}}] {return 0}
303    if [catch {
304        # how many digits are needed to the left of the decimal?
305        set sign 0
306        if {$value > 0} {
307            set digits [expr {1 + int(log10($value))}]
308        } elseif {$value < 0} {
309            set digits [expr {1 + int(log10(-$value))}]
310            set sign 1
311        } else {
312            set digits 1
313        }
314        if {$digits <= 0} {set digits 1}
315        if {$digits + $sign >= $length} {
316            # the number is much too big -- use exponential notation
317            set decimal [expr {$length - 6 - $sign}]
318            # drop more decimal places, as needed
319            set tmp [format "%${length}.${decimal}E" $value]
320            while {[string length $tmp] > $length && $decimal >= 0} {
321                incr decimal -1
322                set tmp [format "%${length}.${decimal}E" $value]
323            }
324        } elseif {$digits + $sign >= $length - $decimal} {
325            # we will have to trim the number of decimal digits
326            set decimal [expr {$length - $digits - $sign - 1}]
327            set tmp [format "%#.${decimal}f" $value]
328        } elseif {abs($value) < pow(10,2-$decimal) && $length > 6 && $value != 0} {
329            # for small values, switch to exponential notation (2-$decimal -> three sig figs.)
330            set decimal [expr {$length - 6 - $sign}]
331            # drop more decimal places, as needed
332            set tmp [format "%${length}.${decimal}E" $value]
333            while {[string length $tmp] > $length && $decimal >= 0} {
334                incr decimal -1
335                set tmp [format "%${length}.${decimal}E" $value]
336            }
337        } else {
338            # use format as specified
339            set tmp [format "%${length}.${decimal}f" $value]
340        }
341        set value $tmp
342    } errmsg] {return 0}
343    return 1
344}
345
346# test an argument if it is a valid integer; reform the number into
347# an integer, if appropriate -- be sure to pass the name of the variable not the value
348proc validint {val length} {
349    upvar $val value
350    # FORTRAN type assumption: blank is 0
351    if {$value == ""} {set value 0}
352    if [catch {
353        set tmp [expr {round($value)}]
354        if {$tmp != $value} {return 0}
355        set value [format "%${length}d" $tmp]
356    }] {return 0}
357    return 1
358}
359
360# process history information
361#    action == last
362#       returns number and value of last record
363#    action == add
364#
365proc exphistory {action "value 0"} {
366    global exparray
367    if {$action == "last"} {
368        set key [lindex [lsort -decreasing [array names exparray *HSTRY*]] 0]
369        if {$key == ""} {return ""}
370        return [list [string trim [string range $key 9 end]] $exparray($key)]
371    } elseif {$action == "add"} {
372        set key [lindex [lsort -decreasing [array names exparray *HSTRY*]] 0]
373        if {$key == ""} {
374            set index 1
375        } else {
376            set index [string trim [string range $key 9 end]]
377            if {$index != "***"} {
378                if {$index < 999} {incr index}
379                set key [format "    HSTRY%3d" $index]
380                set exparray($key) $value
381            }
382        }
383        set key [format "    HSTRY%3d" $index]
384        set exparray($key) $value
385    }
386}
387# get overall info
388#   parm:
389#     print     -- GENLES print option (*)
390#     cycles    -- number of GENLES cycles (*)
391#     title     -- the overall title (*)
392#     convg     -- convergence criterion: -200 to 200 (*)
393#     marq      -- Marquardt damping factor: 1.0 to 9.99 (*)
394#     mbw       -- LS matrix bandwidth; =0 for full matrix (*)
395proc expinfo {parm "action get" "value {}"} {
396    switch ${parm}-$action {
397        title-get {
398            return [string trim [readexp "      DESCR"]]
399        }
400        title-set {
401            setexp "      DESCR" "  $value" 2 68
402        }
403        cycles-get {
404            return [string trim [cdatget MXCY]]
405        }
406        cycles-set {
407            if ![validint value 1] {return 0}
408            cdatset MXCY [format %4d $value]
409        }
410        cyclesrun-get {
411            set cycle -1
412            regexp {.*cycles run *([0-9]*) } [readexp "  GNLS  RUN"] x cycle
413            return $cycle
414        }
415        print-get {
416            set print [string trim [cdatget PRNT]]
417            if {$print != ""} {return $print}
418            return 0
419        }
420        print-set {
421            if ![validint value 1] {return 0}
422            cdatset PRNT [format %4d $value]
423        }
424        convg-get {
425            set cvg [string trim [cdatget CVRG]]
426            if {$cvg == ""} {return -200}
427            if [catch {expr {$cvg}}] {return -200}
428            return $cvg
429        }
430        convg-set {
431            if ![validint value 1] {return 0}
432            set value [expr {-200>$value?-200:$value}]
433            set value [expr {200<$value?200:$value}]
434            cdatset CVRG [format %4d $value]
435        }
436        marq-get {
437            set mar [string trim [cdatget MARQ]]
438            if {$mar == ""} {return 1.0}
439            if [catch {expr $mar}] {return 1.}
440            return $mar
441        }
442        marq-set {
443            if [catch {
444                set value [expr {1.0>$value?1.0:$value}]
445                set value [expr {9.99<$value?9.99:$value}]
446            }] {return 0}
447            if ![validreal value 4 2] {return 0}
448            cdatset MARQ $value
449        }
450        mbw-get {
451            set mbw [string trim [cdatget MBW]]
452            if {$mbw == ""} {return 0}
453            if [catch {expr $mbw}] {return 0}
454            return $mbw
455        }
456        mbw-set {
457            if ![validint value 1] {return 0}
458            if {$value < 0} {return 0}
459            cdatset MBW [format %5d $value]
460        }
461        default {
462            set msg "Unsupported expinfo access: parm=$parm action=$action"
463            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
464        }
465    }
466    return 1
467}
468
469proc cdatget {key} {
470    foreach i {1 2 3 4 5 6 7 8 9} {
471        if {[existsexp "  GNLS CDAT$i"] == 0} break
472        set line [readexp "  GNLS CDAT$i"]
473        if {$line == {}} break
474        foreach i1 {2 10 18 26 34 42 50 58 66} \
475                i2 {9 17 25 33 41 49 57 65 73} {
476            set item [string range $line $i1 $i2]
477            if {[string trim $item] == {}} continue
478            if [regexp "${key}(.*)" $item a b] {return $b}
479        }
480    }
481    return {}
482}
483
484proc cdatset {key value} {
485    # round 1 see if we can find the string
486    foreach i {1 2 3 4 5 6 7 8 9} {
487        set line [readexp "  GNLS CDAT$i"]
488        if {$line == {}} break
489        foreach i1 {2 10 18 26 34 42 50 58 66} \
490                i2 {9 17 25 33 41 49 57 65 73} {
491            set item [string range $line $i1 $i2]
492            if {[string trim $item] == {}} continue
493            if [regexp "${key}(.*)" $item a b] {
494                # found it now replace it
495                incr i1
496                setexp "  GNLS CDAT$i" "${key}${value}" $i1 8
497                return
498            }
499        }
500    }
501    # not found, take the 1st blank space, creating a card if needed
502    foreach i {1 2 3 4 5 6 7 8 9} {
503        set line [readexp "  GNLS CDAT$i"]
504        if {$line == {}} {makeexprec "  GNLS CDAT$i"}
505        foreach i1 {2 10 18 26 34 42 50 58 66} \
506                i2 {9 17 25 33 41 49 57 65 73} {
507            set item [string range $line $i1 $i2]
508            if {[string trim $item] == {}} {
509                # found a blank space: now replace it
510                incr i1
511                setexp "  GNLS CDAT$i" "${key}${value}" $i1 8
512                return
513            }
514        }
515    }
516    return {}
517}
518
519proc disagldat_get {phase} {
520    set key "  DSGL CDAT$phase"
521    if {[existsexp $key] == 0} {return "{none} {none}"}
522    set line [readexp $key]
523    set i1 2
524    # read atom-atom distance parameter
525    set dist {}
526    set item [string range $line $i1 [expr {$i1+3}]]
527    if {$item == "DMAX"} {
528        set val [string range $line [expr {$i1+4}] [expr {$i1+11}]]
529        set dist [string trim $val]
530        incr i1 13
531    } else {
532        set dist "radii"
533        incr i1 5
534    }
535    # read atom-atom-atom angle parameter
536    set ang {}
537    set item [string range $line $i1 [expr {$i1+3}]]
538    if {$item == "DAGL"} {
539        set val [string range $line [expr {$i1+4}] [expr {$i1+11}]]
540        set ang [string trim $val]
541        incr i1 13
542    } else {
543        set ang "radii"
544        incr i1 5
545    }
546    # note there are two more parameters, NOFO/FORA & ONCR/DFLT, but they are not being processed yet
547    return "$dist $ang"
548}
549
550# get phase information: phaseinfo phase parm action value
551#   phase: 1 to 9 (as defined)
552#   parm:
553#     name -- phase name
554#     natoms -- number of atoms (*)
555#     a b c alpha beta gamma -- cell parameters (*)
556#     cellref -- refinement flag for the unit cell(*)
557#     celldamp  -- damping for the unit cell refinement (*)
558#     spacegroup -- space group symbol (*)
559#     ODForder -- spherical harmonic order (*)
560#     ODFsym   -- sample symmetry (0-3) (*)
561#     ODFdampA -- damping for angles (*)
562#     ODFdampC -- damping for coefficients (*)
563#     ODFomega -- omega oriention angle (*)
564#     ODFchi -- chi oriention angle (*)
565#     ODFphi -- phi oriention angle (*)
566#     ODFomegaRef -- refinement flag for omega (*)
567#     ODFchiRef -- refinement flag for chi (*)
568#     ODFphiRef -- refinement flag for phi (*)
569#     ODFterms -- a list of the {l m n} values for each ODF term (*)
570#     ODFcoefXXX -- the ODF coefficient for for ODF term XXX (*)
571#     ODFRefcoef -- refinement flag for ODF terms (*)
572#     DistCalc   -- returns "radii", "none" or a number (*)
573#                   none: no distance or angle computation for the phase
574#                   radii: computation will be done by sums of radii
575#                          (see AtmTypInfo and DefAtmTypInfo)
576#                   other: a distance specifing the maximum distance
577#     AngCalc    -- returns "radii", "none" or a number (*)
578#                   none: no distance or angle computation for the phase
579#                   radii: computation will be done by sums of radii
580#                          (see AtmTypInfo and DefAtmTypInfo)
581#                   other: a distance specifing the maximum distance
582#  action: get (default) or set
583#  value: used only with set
584#  * =>  read+write supported
585proc phaseinfo {phase parm "action get" "value {}"} {
586    switch -glob ${parm}-$action {
587
588        name-get {
589            return [string trim [readexp "CRS$phase    PNAM"]]
590        }
591
592        name-set {
593            setexp "CRS$phase    PNAM" " $value" 2 68
594        }
595
596        spacegroup-get {
597            return [string trim [readexp "CRS$phase  SG SYM"]]
598        }
599
600        spacegroup-set {
601            setexp "CRS$phase  SG SYM" " $value" 2 68
602        }
603
604        natoms-get {
605            return [string trim [readexp "CRS$phase   NATOM"]]     
606        }
607
608        natoms-set {
609            if ![validint value 5] {return 0}
610            setexp "CRS$phase   NATOM" $value 1 5
611        }
612
613        a-get {
614           return [string trim [string range [readexp "CRS$phase  ABC"] 0 9]]
615        }
616        b-get {
617           return [string trim [string range [readexp "CRS$phase  ABC"] 10 19]]
618        }
619        c-get {
620           return [string trim [string range [readexp "CRS$phase  ABC"] 20 29]]
621        }
622        alpha-get {
623           return [string trim [string range [readexp "CRS$phase  ANGLES"] 0 9]]
624        }
625        beta-get {
626           return [string trim [string range [readexp "CRS$phase  ANGLES"] 10 19]]
627        }
628        gamma-get {
629           return [string trim [string range [readexp "CRS$phase  ANGLES"] 20 29]]
630        }
631
632        a-set {
633            if ![validreal value 10 6] {return 0}
634            setexp "CRS$phase  ABC" $value 1 10             
635        }
636        b-set {
637            if ![validreal value 10 6] {return 0}
638            setexp "CRS$phase  ABC" $value 11 10           
639        }
640        c-set {
641            if ![validreal value 10 6] {return 0}
642            setexp "CRS$phase  ABC" $value 21 10           
643        }
644        alpha-set {
645            if ![validreal value 10 4] {return 0}
646            setexp "CRS$phase  ANGLES" $value 1 10         
647        }
648        beta-set {
649            if ![validreal value 10 4] {return 0}
650            setexp "CRS$phase  ANGLES" $value 11 10         
651        }
652        gamma-set {
653            if ![validreal value 10 4] {return 0}
654            setexp "CRS$phase  ANGLES" $value 21 10         
655        }
656        cellref-get {
657            if {[string toupper [string range [readexp "CRS$phase  ABC"] 34 34]] == "Y"} {
658                return 1
659            }
660            return 0
661        }
662        cellref-set {
663            if $value {
664                setexp "CRS$phase  ABC" "Y" 35 1
665            } else {
666                setexp "CRS$phase  ABC" "N" 35 1
667            }       
668        }
669        celldamp-get {
670            set val [string range [readexp "CRS$phase  ABC"] 39 39]
671            if {$val == " "} {return 0}
672            return $val
673        }
674        celldamp-set {
675            setexp "CRS$phase  ABC" $value 40 1
676        }
677
678        ODForder-get {
679            set val [string trim [string range [readexp "CRS$phase  OD "] 0 4]]
680            if {$val == " "} {return 0}
681            return $val
682        }
683        ODForder-set {
684            if ![validint value 5] {return 0}
685            setexp "CRS$phase  OD " $value 1 5
686        }
687        ODFsym-get {
688            set val [string trim [string range [readexp "CRS$phase  OD "] 10 14]]
689            if {$val == " "} {return 0}
690            return $val
691        }
692        ODFsym-set {
693            if ![validint value 5] {return 0}
694            setexp "CRS$phase  OD " $value 11 5
695        }
696        ODFdampA-get {
697            set val [string range [readexp "CRS$phase  OD "] 24 24]
698            if {$val == " "} {return 0}
699            return $val
700        }
701        ODFdampA-set {
702            setexp "CRS$phase  OD " $value 25 1
703        }
704        ODFdampC-get {
705            set val [string range [readexp "CRS$phase  OD "] 29 29]
706            if {$val == " "} {return 0}
707            return $val
708        }
709        ODFdampC-set {
710            setexp "CRS$phase  OD " $value 30 1
711        }
712        ODFomegaRef-get {
713            if {[string toupper [string range [readexp "CRS$phase  OD "] 16 16]] == "Y"} {
714                return 1
715            }
716            return 0
717        }
718        ODFomegaRef-set {
719            if $value {
720                setexp "CRS$phase  OD " "Y" 17 1
721            } else {
722                setexp "CRS$phase  OD " "N" 17 1
723            }       
724        }
725        ODFchiRef-get {
726            if {[string toupper [string range [readexp "CRS$phase  OD "] 17 17]] == "Y"} {
727                return 1
728            }
729            return 0
730        }
731        ODFchiRef-set {
732            if $value {
733                setexp "CRS$phase  OD " "Y" 18 1
734            } else {
735                setexp "CRS$phase  OD " "N" 18 1
736            }       
737        }
738        ODFphiRef-get {
739            if {[string toupper [string range [readexp "CRS$phase  OD "] 18 18]] == "Y"} {
740                return 1
741            }
742            return 0
743        }
744        ODFphiRef-set {
745            if $value {
746                setexp "CRS$phase  OD " "Y" 19 1
747            } else {
748                setexp "CRS$phase  OD " "N" 19 1
749            }       
750        }
751        ODFcoef*-get {
752            regsub ODFcoef $parm {} term
753            set k [expr {($term+5)/6}]
754            if {$k <= 9} {
755                set k "  $k"
756            } elseif {$k <= 99} {
757                set k " $k"
758            }
759            set j [expr {(($term-1) % 6)+1}]
760            set lineB [readexp "CRS$phase  OD${k}B"]
761            set j0 [expr { ($j-1) *10}]
762            set j1 [expr {$j0 + 9}]
763            set val [string trim [string range $lineB $j0 $j1]]
764            if {$val == ""} {return 0.0}
765            return $val
766        }
767        ODFcoef*-set {
768            regsub ODFcoef $parm {} term
769            if ![validreal value 10 3] {return 0}
770            set k [expr {($term+5)/6}]
771            if {$k <= 9} {
772                set k "  $k"
773            } elseif {$k <= 99} {
774                set k " $k"
775            }
776            set j [expr {(($term-1) % 6)+1}]
777            set col [expr { ($j-1)*10 + 1}]
778            setexp "CRS$phase  OD${k}B" $value $col 10
779        }
780        ODFRefcoef-get {
781            if {[string toupper [string range [readexp "CRS$phase  OD "] 19 19]] == "Y"} {
782                return 1
783            }
784            return 0
785        }
786        ODFRefcoef-set {
787            if $value {
788                setexp "CRS$phase  OD " "Y" 20 1
789            } else {
790                setexp "CRS$phase  OD " "N" 20 1
791            }       
792        }
793        ODFomega-get {
794           return [string trim [string range [readexp "CRS$phase  OD "] 30 39]]
795        }
796        ODFchi-get {
797           return [string trim [string range [readexp "CRS$phase  OD "] 40 49]]
798        }
799        ODFphi-get {
800           return [string trim [string range [readexp "CRS$phase  OD "] 50 59]]
801        }
802        ODFomega-set {
803            if ![validreal value 10 4] {return 0}
804            setexp "CRS$phase  OD " $value 31 10
805        }
806        ODFchi-set {
807            if ![validreal value 10 4] {return 0}
808            setexp "CRS$phase  OD " $value 41 10
809        }
810        ODFphi-set {
811            if ![validreal value 10 4] {return 0}
812            setexp "CRS$phase  OD " $value 51 10
813        }
814
815        ODFterms-get {
816            set vallist {}
817            set val [string trim [string range [readexp "CRS$phase  OD "] 5 9]]
818            for {set i 1} {$i <= $val} {incr i 6} {
819                set k [expr {1+($i-1)/6}]
820                if {$k <= 9} {
821                    set k "  $k"
822                } elseif {$k <= 99} {
823                    set k " $k"
824                }
825                set lineA [readexp "CRS$phase  OD${k}A"]
826                set k 0
827                for {set j $i} {$j <= $val && $j < $i+6} {incr j} {
828                    set j0 [expr {($k)*10}]
829                    set j1 [expr {$j0 + 9}]
830                    lappend vallist [string trim [string range $lineA $j0 $j1]]
831                    incr k
832                }
833            }
834            return $vallist
835        }
836        ODFterms-set {
837            set key "CRS$phase  OD    "
838            if {![existsexp $key]} {
839                makeexprec $key
840                set oldlen 0
841            } else {
842                set oldlen [string trim [string range [readexp $key] 5 9]]
843            }
844            set len [llength $value]
845            if ![validint len 5] {return 0}
846            setexp $key $len 6 5
847            set j 0
848            set k 0
849            foreach item $value {
850                incr j
851                if {$j % 6 == 1} {
852                    incr k
853                    if {$k <= 9} {
854                        set k "  $k"
855                    } elseif {$k <= 99} {
856                        set k " $k"
857                    }
858                    set col 1
859                    set keyA "CRS$phase  OD${k}A"
860                    set keyB "CRS$phase  OD${k}B"
861                    if {![existsexp $keyA]} {
862                        makeexprec $keyA
863                        makeexprec $keyB
864                    }
865                }
866                set col1 [expr {$col + 1}]
867                foreach n [lrange $item 0 2] {
868                    if ![validint n 3] {return 0}
869                    setexp $keyA $n $col1 3
870                    incr col1 3
871                }
872                incr col 10
873            }
874            for {incr j} {$j <= $oldlen} {incr j} {
875                if {$j % 6 == 1} {
876                    incr k
877                    if {$k <= 9} {
878                        set k "  $k"
879                    } elseif {$k <= 99} {
880                        set k " $k"
881                    }
882                    set col 1
883                    set keyA "CRS$phase  OD${k}A"
884                    set keyB "CRS$phase  OD${k}B"
885                    delexp $keyA
886                    delexp $keyB
887                }
888                if {[existsexp $keyA]} {
889                    setexp $keyA "          " $col 10
890                    setexp $keyB "          " $col 10
891                }
892                incr col 10
893            }
894        }
895        DistCalc-get {
896            set val [disagldat_get $phase]
897            return [lindex $val 0]
898        }
899        DistCalc-set {
900            set key "  DSGL CDAT$phase"
901            # for none delete the record & thats all folks
902            if {$value == "none"} {
903                catch {unset ::exparray($key)}
904                return
905            }
906            if {[existsexp $key] == 0} {
907                makeexprec $key
908            }
909            set line [readexp $key]
910            if {[string trim $line] == ""} {
911                # blank set to defaults
912                set line [string replace $line 2 15 "DRAD ARAD NOFO"]
913            }
914            if {$value == "radii"} {
915                if {[string range $line 2 5] == "DMAX"} {
916                    set line [string replace $line 2 13 "DRAD"]
917                } else {
918                    set line [string replace $line 2 5 "DRAD"]
919                }
920            } else {
921                if ![validreal value 8 2] {return 0}
922                if {[string range $line 2 5] == "DMAX"} {
923                    set line [string replace $line 6 13 $value]
924                } else {
925                    set line [string replace $line 2 5 "DMAX"]
926                    set line [string replace $line 6 6 "$value "]
927                }
928            }
929            setexp $key $line 0 68
930        }
931        AngCalc-get {
932            set val [disagldat_get $phase]
933            return [lindex $val 1]
934        }
935        AngCalc-set {
936            set key "  DSGL CDAT$phase"
937            # for none delete the record & thats all folks
938            if {$value == "none"} {
939                catch {unset ::exparray($key)}
940                return
941            }
942            if {[existsexp $key] == 0} {
943                makeexprec $key
944            }
945            set line [readexp $key]
946            if {[string trim $line] == ""} {
947                # blank set to defaults
948                set line [string replace $line 2 15 "DRAD ARAD NOFO"]
949            }
950            if {[string range $line 2 5] == "DMAX"} {
951                set i2 8
952            } else {
953                set i2 0
954            }
955            if {$value == "radii"} {
956                if {[string range $line [expr {$i2+7}] [expr {$i2+10}]] == "DAGL"} {
957                    set line [string replace $line [expr {$i2+7}] [expr {$i2+18}] "ARAD"]
958                } else {
959                    set line [string replace $line [expr {$i2+7}] [expr {$i2+10}] "ARAD"]
960                }
961            } else {
962                if ![validreal value 8 2] {return 0}
963                if {[string range $line [expr {$i2+7}] [expr {$i2+10}]] == "DAGL"} {
964                    set line [string replace $line [expr {$i2+11}] [expr {$i2+18}] $value]
965                } else {
966                    set line [string replace $line [expr {$i2+7}] [expr {$i2+10}] "DAGL"]
967                    set line [string replace $line [expr {$i2+11}] [expr {$i2+11}] "$value "]
968                }
969            }
970            setexp $key $line 0 68
971        }
972        default {
973            set msg "Unsupported phaseinfo access: parm=$parm action=$action"
974            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
975        }
976    }
977    return 1
978}
979
980
981
982# get atom information: atominfo phase atom parm action value
983#   phase: 1 to 9 (as defined)
984#   atom: a valid atom number [see expmap(atomlist_$phase)]
985#      Note that atom and phase can be paired lists, but if there are extra
986#      entries in the atoms list, the last phase will be repeated.
987#      so that atominfo 1 {1 2 3} xset 1
988#               will set the xflag for atoms 1-3 in phase 1
989#      but atominfo {1 2 3} {1 1 1} xset 1
990#               will set the xflag for atoms 1 in phase 1-3
991#   parm:
992#     type -- element code
993#     mult -- atom multiplicity
994#     label -- atom label (*)
995#     x y z -- coordinates (*)
996#     frac --  occupancy (*)
997#     temptype -- I or A for Isotropic/Anisotropic (*)
998#     Uiso  -- Isotropic temperature factor (*)
999#     U11  -- Anisotropic temperature factor (*)
1000#     U22  -- Anisotropic temperature factor (*)
1001#     U33  -- Anisotropic temperature factor (*)
1002#     U12  -- Anisotropic temperature factor (*)
1003#     U13  -- Anisotropic temperature factor (*)
1004#     U23  -- Anisotropic temperature factor (*)
1005#     xref/xdamp -- refinement flag/damping value for the coordinates (*)
1006#     uref/udamp -- refinement flag/damping value for the temperature factor(s)  (*)
1007#     fref/fdamp -- refinement flag/damping value for the occupancy (*)
1008#  action: get (default) or set
1009#  value: used only with set
1010#  * =>  read+write supported
1011proc atominfo {phaselist atomlist parm "action get" "value {}"} {
1012    foreach phase $phaselist atom $atomlist {
1013        if {$phase == ""} {set phase [lindex $phaselist end]}
1014        if {$atom < 10} {
1015            set key "CRS$phase  AT  $atom"
1016        } elseif {$atom < 100} {
1017            set key "CRS$phase  AT $atom"
1018        } else {
1019            set key "CRS$phase  AT$atom"
1020        }
1021        switch -glob ${parm}-$action {
1022            type-get {
1023                return [string trim [string range [readexp ${key}A] 2 9] ]
1024            }
1025            mult-get {
1026                return [string trim [string range [readexp ${key}A] 58 61] ]
1027            }
1028            label-get {
1029                return [string trim [string range [readexp ${key}A] 50 57] ]
1030            }
1031            label-set {
1032                setexp ${key}A $value 51 8
1033            }
1034            temptype-get {
1035                return [string trim [string range [readexp ${key}B] 62 62] ]
1036            }
1037            temptype-set {
1038                if {$value == "A"} {
1039                    setexp ${key}B A 63 1
1040                    # copy the Uiso to the diagonal terms
1041                    set Uiso [string range [readexp ${key}B] 0 9]
1042                    foreach value [CalcAniso $phase $Uiso] \
1043                            col {1 11 21 31 41 51} {
1044                        validreal value 10 6
1045                        setexp ${key}B $value $col 10
1046                    }
1047                } else {
1048                    setexp ${key}B I 63 1
1049                    set value 0.0
1050                    catch {
1051                        # get the trace
1052                        set value [expr {( \
1053                                [string range [readexp ${key}B] 0 9] + \
1054                                [string range [readexp ${key}B] 10 19] + \
1055                                [string range [readexp ${key}B] 20 29])/3.}]
1056                    }
1057                    validreal value 10 6
1058                    setexp ${key}B $value 1 10
1059                    # blank out the remaining terms
1060                    set value " "
1061                    setexp ${key}B $value 11 10
1062                    setexp ${key}B $value 21 10
1063                    setexp ${key}B $value 31 10
1064                    setexp ${key}B $value 41 10
1065                    setexp ${key}B $value 51 10
1066                }
1067            }
1068            x-get {
1069                return [string trim [string range [readexp ${key}A] 10 19] ]
1070            }
1071            x-set {
1072                if ![validreal value 10 6] {return 0}
1073                setexp ${key}A $value 11 10
1074            }
1075            y-get {
1076                return [string trim [string range [readexp ${key}A] 20 29] ]
1077            }
1078            y-set {
1079                if ![validreal value 10 6] {return 0}
1080                setexp ${key}A $value 21 10
1081            }
1082            z-get {
1083                return [string trim [string range [readexp ${key}A] 30 39] ]
1084            }
1085            z-set {
1086                if ![validreal value 10 6] {return 0}
1087                setexp ${key}A $value 31 10
1088            }
1089            frac-get {
1090                return [string trim [string range [readexp ${key}A] 40 49] ]
1091            }
1092            frac-set {
1093                if ![validreal value 10 6] {return 0}
1094                setexp ${key}A $value 41 10
1095            }
1096            U*-get {
1097                regsub U $parm {} type
1098                if {$type == "iso" || $type == "11"} {
1099                    return [string trim [string range [readexp ${key}B] 0 9] ]
1100                } elseif {$type == "22"} {
1101                    return [string trim [string range [readexp ${key}B] 10 19] ]
1102                } elseif {$type == "33"} {
1103                    return [string trim [string range [readexp ${key}B] 20 29] ]
1104                } elseif {$type == "12"} {
1105                    return [string trim [string range [readexp ${key}B] 30 39] ]
1106                } elseif {$type == "13"} {
1107                    return [string trim [string range [readexp ${key}B] 40 49] ]
1108                } elseif {$type == "23"} {
1109                    return [string trim [string range [readexp ${key}B] 50 59] ]
1110                }
1111            }
1112            U*-set {
1113                if ![validreal value 10 6] {return 0}
1114                regsub U $parm {} type
1115                if {$type == "iso" || $type == "11"} {
1116                    setexp ${key}B $value 1 10
1117                } elseif {$type == "22"} {
1118                    setexp ${key}B $value 11 10
1119                } elseif {$type == "33"} {
1120                    setexp ${key}B $value 21 10
1121                } elseif {$type == "12"} {
1122                    setexp ${key}B $value 31 10
1123                } elseif {$type == "13"} {
1124                    setexp ${key}B $value 41 10
1125                } elseif {$type == "23"} {
1126                    setexp ${key}B $value 51 10
1127                }
1128            }
1129            xref-get {
1130                if {[string toupper [string range [readexp ${key}B] 64 64]] == "X"} {
1131                    return 1
1132                }
1133                return 0
1134            }
1135            xref-set {
1136                if $value {
1137                    setexp ${key}B "X" 65 1
1138                } else {
1139                    setexp ${key}B " " 65 1
1140                }           
1141            }
1142            xdamp-get {
1143                set val [string range [readexp ${key}A] 64 64]
1144                if {$val == " "} {return 0}
1145                return $val
1146            }
1147            xdamp-set {
1148                setexp ${key}A $value 65 1
1149            }
1150            fref-get {
1151                if {[string toupper [string range [readexp ${key}B] 63 63]] == "F"} {
1152                    return 1
1153                }
1154                return 0
1155            }
1156            fref-set {
1157                if $value {
1158                    setexp ${key}B "F" 64 1
1159                } else {
1160                    setexp ${key}B " " 64 1
1161                }           
1162            }
1163            fdamp-get {
1164                set val [string range [readexp ${key}A] 63 63]
1165                if {$val == " "} {return 0}
1166                return $val
1167            }
1168            fdamp-set {
1169                setexp ${key}A $value 64 1
1170            }
1171
1172            uref-get {
1173                if {[string toupper [string range [readexp ${key}B] 65 65]] == "U"} {
1174                    return 1
1175                }
1176                return 0
1177            }
1178            uref-set {
1179                if $value {
1180                    setexp ${key}B "U" 66 1
1181                } else {
1182                    setexp ${key}B " " 66 1
1183                }           
1184            }
1185            udamp-get {
1186                set val [string range [readexp ${key}A] 65 65]
1187                if {$val == " "} {return 0}
1188                return $val
1189            }
1190            udamp-set {
1191                setexp ${key}A $value 66 1
1192            }
1193            default {
1194                set msg "Unsupported atominfo access: parm=$parm action=$action"
1195                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
1196            }
1197        }
1198    }
1199    return 1
1200}
1201
1202# get macromolecular atom information: mmatominfo phase atom parm action value
1203#   phase: 1 (at present only one mm phase can be defined)
1204#   atom: a valid atom number [see expmap(atomlist_$phase)]
1205#      Note that atoms can be lists
1206#      so that mmatominfo 1 {1 2 3} xset 1
1207#               will set the xflag for atoms 1-3 in phase 1
1208#   parm:
1209#     type -- element code
1210#     frac --  occupancy (*)
1211#     x y z -- coordinates (*)
1212#     Uiso  -- Isotropic temperature factor (*)
1213#     label -- atom label (*)
1214#     residue -- residue label (*)
1215#     group -- group label (*)
1216#     resnum -- residue number (*)
1217#     xref/xdamp -- refinement flag/damping value for the coordinates (*)
1218#     uref/udamp -- refinement flag/damping value for the temperature factor(s)  (*)
1219#     fref/fdamp -- refinement flag/damping value for the occupancy (*)
1220#  action: get (default) or set
1221#  value: used only with set
1222#  * =>  read+write supported
1223proc mmatominfo {phaselist atomlist parm "action get" "value {}"} {
1224    foreach phase $phaselist atom $atomlist {
1225        if {$phase == ""} {set phase [lindex $phaselist end]}
1226        set num [string toupper [format %.4x $atom]]
1227        set key "CRS$phase  AT$num"
1228        switch -glob ${parm}-$action {
1229            type-get {
1230                return [string trim [string range [readexp ${key}] 2 9] ]
1231            }
1232            frac-get {
1233                return [string trim [string range [readexp ${key}] 10 15] ]
1234            }
1235            frac-set {
1236                if ![validreal value 6 4] {return 0}
1237                setexp ${key} $value 11 6
1238            }
1239            x-get {
1240                return [string trim [string range [readexp ${key}] 16 23] ]
1241            }
1242            x-set {
1243                if ![validreal value 8 5] {return 0}
1244                setexp ${key} $value 17 8
1245            }
1246            y-get {
1247                return [string trim [string range [readexp ${key}] 24 31] ]
1248            }
1249            y-set {
1250                if ![validreal value 8 5] {return 0}
1251                setexp ${key} $value 25 8
1252            }
1253            z-get {
1254                return [string trim [string range [readexp ${key}] 32 39] ]
1255            }
1256            z-set {
1257                if ![validreal value 8 5] {return 0}
1258                setexp ${key} $value 33 8
1259            }
1260            Uiso-get {
1261                return [string trim [string range [readexp ${key}] 40 45] ]
1262            }
1263            Uiso-set {
1264                if ![validreal value 6 4] {return 0}
1265                setexp ${key} $value 41 6
1266            }
1267            label-get {
1268                return [string trim [string range [readexp ${key}] 46 50] ]
1269            }
1270            label-set {
1271                setexp ${key} $value 47 5
1272            }
1273            residue-get {
1274                return [string range [readexp ${key}] 51 53]
1275            }
1276            residue-set {
1277                setexp ${key} $value 52 3
1278            }
1279            group-get {
1280                return [string range [readexp ${key}] 54 55]
1281            }
1282            group-set {
1283                setexp ${key} $value 55 2
1284            }
1285            resnum-get {
1286                return [string trim [string range [readexp ${key}] 56 59] ]
1287            }
1288            resnum-set {
1289                if ![validint value 4] {return 0}
1290                setexp "${key} EPHAS" $value 57 4
1291            }
1292            fref-get {
1293                if {[string toupper [string range [readexp $key] 60 60]] == "F"} {
1294                    return 1
1295                }
1296                return 0
1297            }
1298            fref-set {
1299                if $value {
1300                    setexp $key "F" 61 1
1301                } else {
1302                    setexp $key " " 61 1
1303                }           
1304            }
1305            xref-get {
1306                if {[string toupper [string range [readexp $key] 61 61]] == "X"} {
1307                    return 1
1308                }
1309                return 0
1310            }
1311            xref-set {
1312                if $value {
1313                    setexp $key "X" 62 1
1314                } else {
1315                    setexp ${key}B " " 62 1
1316                }           
1317            }
1318            uref-get {
1319                if {[string toupper [string range [readexp $key] 62 62]] == "U"} {
1320                    return 1
1321                }
1322                return 0
1323            }
1324            uref-set {
1325                if $value {
1326                    setexp $key "U" 63 1
1327                } else {
1328                    setexp $key " " 63 1
1329                }           
1330            }
1331
1332            fdamp-get {
1333                set val [string range [readexp ${key}] 63 63]
1334                if {$val == " "} {return 0}
1335                return $val
1336            }
1337            fdamp-set {
1338                setexp ${key} $value 64 1
1339            }
1340            xdamp-get {
1341                set val [string range [readexp ${key}] 64 64]
1342                if {$val == " "} {return 0}
1343                return $val
1344            }
1345            xdamp-set {
1346                setexp ${key} $value 65 1
1347            }
1348
1349            udamp-get {
1350                set val [string range [readexp ${key}] 65 65]
1351                if {$val == " "} {return 0}
1352                return $val
1353            }
1354            udamp-set {
1355                setexp ${key} $value 66 1
1356            }
1357            default {
1358                set msg "Unsupported mmatominfo access: parm=$parm action=$action"
1359                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
1360            }
1361        }
1362    }
1363    return 1
1364}
1365
1366
1367
1368# get histogram information: histinfo histlist parm action value
1369# histlist is a list of histogram numbers
1370# parm:
1371#     title
1372#     file  -- file name of raw data for histogram (*)
1373#     scale (*)
1374#     sref/sdamp -- refinement flag/damping value for the scale factor (*)
1375#     lam1, lam2 (*)
1376#     ttref refinement flag for the 2theta (ED Xray) (*)
1377#     wref refinement flag for the wavelength (*)
1378#     ratref refinement flag for the wavelength ratio (*)
1379#     difc, difa -- TOF calibration constants (*)
1380#     dcref,daref -- refinement flag for difc, difa (*)
1381#     zero (*)
1382#     zref refinement flag for the zero correction (*)
1383#     ipola (*)
1384#     pola (*)
1385#     pref refinement flag for the polarization (*)
1386#     kratio (*)
1387#     ddamp -- damping value for the diffractometer constants (*)
1388#     backtype -- background function number *
1389#     backterms -- number of background terms *
1390#     bref/bdamp -- refinement flag/damping value for the background (*)
1391#     bterm$n -- background term #n (*)
1392#     bank -- Bank number
1393#     tofangle -- detector angle (TOF only)
1394#     foextract  -- Fobs extraction flag (*)
1395#     LBdamp  -- LeBail damping value (*)
1396#     tmin/tmax -- minimum & maximum usable 2theta/TOF/energy
1397#     excl -- excluded regions (*)
1398#     dmin -- minimum d-space for reflection generation (*)
1399#     use  -- use flag; 1 = use; 0 = do not use (*)
1400#     dstart -- dummy histogram starting tmin/emin/2theta (*)
1401#     dstep -- dummy histogram step size tmin/emin/2theta (*)
1402#     dpoints -- dummy histogram number of points (*)
1403#     dtype   -- dummy histogram type (CONST or SLOG)
1404#     abscor1 -- 1st absorption correction (*)
1405#     abscor2 -- 2nd absorption correction (*)
1406#     abstype -- absorption correction type (*)
1407#     absdamp -- damping for absorption refinement (*)
1408#     absref -- refinement damping for absorption refinement (*)
1409#     proftbl -- returns number of profile table terms
1410#     anomff -- returns a list of elements, f' and f"
1411#   parameters transferred from the instrument parameter file:
1412#     ITYP    -- returns the contents of the ITYP record
1413proc histinfo {histlist parm "action get" "value {}"} {
1414    global expgui
1415    foreach hist $histlist {
1416        if {$hist < 10} {
1417            set key "HST  $hist"
1418        } else {
1419            set key "HST $hist"
1420        }
1421        switch -glob ${parm}-$action {
1422            foextract-get {
1423                set line [readexp "${key} EPHAS"]
1424                # add a EPHAS if not exists
1425                if {$line == {}} {
1426                    makeexprec "${key} EPHAS"
1427                    # expedt defaults this to "F", but I think "T" is better
1428                    setexp "${key} EPHAS" "Y" 50 1
1429                    if $expgui(debug) {puts "Warning: creating a ${key} EPHAS record"}
1430                }
1431                if {[string toupper [string range $line 49 49]] == "T"} {
1432                    return 1
1433                }
1434                # the flag has changed to "Y/N" in the latest versions
1435                # of GSAS
1436                if {[string toupper [string range $line 49 49]] == "Y"} {
1437                    return 1
1438                }
1439                return 0
1440            }
1441            foextract-set {
1442                # the flag has changed to "Y/N" in the latest versions
1443                # of GSAS
1444                if $value {
1445                    setexp "${key} EPHAS" "Y" 50 1
1446                } else {
1447                    setexp "${key} EPHAS" "N" 50 1
1448                }
1449            }
1450            LBdamp-get {
1451                set v [string trim [string range [readexp "${key} EPHAS"] 54 54]]
1452                if {$v == ""} {return 0}
1453                return $v
1454            }
1455            LBdamp-set {
1456                if ![validint value 5] {return 0}
1457                setexp "${key} EPHAS" $value 51 5
1458            }
1459            title-get {
1460                return [string trim [readexp "${key}  HNAM"] ]
1461            }
1462            scale-get {
1463                if {![existsexp ${key}HSCALE]} {
1464                    # fix missing scale factor record
1465                    makeexprec ${key}HSCALE
1466                    set value 1.0
1467                    validreal value 15 6
1468                    setexp ${key}HSCALE $value 1 15
1469                    catch {incr ::expgui(changed)}
1470                    setexp ${key}HSCALE "N" 20 1
1471                }
1472                return [string trim [string range [readexp ${key}HSCALE] 0 14]]
1473            }
1474            scale-set {
1475                if ![validreal value 15 6] {return 0}
1476                setexp ${key}HSCALE $value 1 15
1477            }
1478            sref-get {
1479                if {[string toupper [string range [readexp ${key}HSCALE] 19 19]] == "Y"} {
1480                    return 1
1481                }
1482                return 0
1483            }
1484            sref-set {
1485                if $value {
1486                    setexp ${key}HSCALE "Y" 20 1
1487                } else {
1488                    setexp ${key}HSCALE "N" 20 1
1489                }           
1490            }
1491            sdamp-get {
1492                set val [string range [readexp ${key}HSCALE] 24 24]
1493                if {$val == " "} {return 0}
1494                return $val
1495            }
1496            sdamp-set {
1497                setexp ${key}HSCALE $value 25 1
1498            }
1499
1500            difc-get -
1501            lam1-get {
1502                return [string trim [string range [readexp "${key} ICONS"] 0 9]]
1503            }
1504            difc-set -
1505            lam1-set {
1506                if ![validreal value 10 7] {return 0}
1507                setexp "${key} ICONS" $value 1 10
1508                # set the powpref warning (1 = suggested)
1509                catch {
1510                    global expgui
1511                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1512                    set msg "Diffractometer constants" 
1513                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1514                        append expgui(needpowpref_why) "\t$msg were changed\n"
1515                    }
1516                }
1517            }
1518            difa-get -
1519            lam2-get {
1520                return [string trim [string range [readexp "${key} ICONS"] 10 19]]
1521            }
1522            difa-set -
1523            lam2-set {
1524                if ![validreal value 10 7] {return 0}
1525                setexp "${key} ICONS" $value 11 10
1526                # set the powpref warning (1 = suggested)
1527                catch {
1528                    global expgui
1529                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1530                    set msg "Diffractometer constants" 
1531                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1532                        append expgui(needpowpref_why) "\t$msg were changed\n"
1533                    }
1534                }
1535            }
1536            zero-get {
1537                return [string trim [string range [readexp "${key} ICONS"] 20 29]]
1538            }
1539            zero-set {
1540                if ![validreal value 10 5] {return 0}
1541                setexp "${key} ICONS" $value 21 10
1542                # set the powpref warning (1 = suggested)
1543                catch {
1544                    global expgui
1545                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1546                    set msg "Diffractometer constants" 
1547                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1548                        append expgui(needpowpref_why) "\t$msg were changed\n"
1549                    }
1550                }
1551            }
1552            ipola-get {
1553                return [string trim [string range [readexp "${key} ICONS"] 54 54]]
1554            }
1555            ipola-set {
1556                if ![validint value 1] {return 0}
1557                setexp "${key} ICONS" $value 55 1
1558            }
1559            pola-get {
1560                return [string trim [string range [readexp "${key} ICONS"] 40 49]]
1561            }
1562            pola-set {
1563                if ![validreal value 10 5] {return 0}
1564                setexp "${key} ICONS" $value 41 10
1565            }
1566            kratio-get {
1567                set val [string trim [string range [readexp "${key} ICONS"] 55 64]]
1568                if {$val == ""} {set val 0}
1569                # N.B. this code is used w/CW, where Kratio may not be 0.0
1570                set lam2 [string trim [string range [readexp "${key} ICONS"] 10 19]]
1571                if {$lam2 == ""} {set lam2 0}
1572                # Change kratio & flag the change (this is rather kludged)
1573                if {$val == 0 && $lam2 != 0} {
1574                    set val 0.5
1575                    validreal val 10 5
1576                    setexp "${key} ICONS" $val 56 10
1577                    catch {incr ::expgui(changed)}
1578                }
1579                return $val
1580            }
1581            kratio-set {
1582                if ![validreal value 10 5] {return 0}
1583                setexp "${key} ICONS" $value 56 10
1584            }
1585
1586            wref-get {
1587            #------------------------------------------------------
1588            # col 33: refine flag for lambda, difc, ratio and theta
1589            #------------------------------------------------------
1590                if {[string toupper [string range \
1591                        [readexp "${key} ICONS"] 32 32]] == "L"} {
1592                    return 1
1593                }
1594                return 0
1595            }
1596            wref-set {
1597                if $value {
1598                    setexp "${key} ICONS" "L" 33 1
1599                } else {
1600                    setexp "${key} ICONS" " " 33 1
1601                }           
1602            }
1603            ratref-get {
1604                if {[string toupper [string range \
1605                        [readexp "${key} ICONS"] 32 32]] == "R"} {
1606                    return 1
1607                }
1608                return 0
1609            }
1610            ratref-set {
1611                if $value {
1612                    setexp "${key} ICONS" "R" 33 1
1613                } else {
1614                    setexp "${key} ICONS" " " 33 1
1615                }           
1616            }
1617            dcref-get {
1618                if {[string toupper [string range \
1619                        [readexp "${key} ICONS"] 32 32]] == "C"} {
1620                    return 1
1621                }
1622                return 0
1623            }
1624            dcref-set {
1625                if $value {
1626                    setexp "${key} ICONS" "C" 33 1
1627                } else {
1628                    setexp "${key} ICONS" " " 33 1
1629                }           
1630            }
1631            ttref-get {
1632                if {[string toupper [string range \
1633                        [readexp "${key} ICONS"] 32 32]] == "T"} {
1634                    return 1
1635                }
1636                return 0
1637            }
1638            ttref-set {
1639                if $value {
1640                    setexp "${key} ICONS" "T" 33 1
1641                } else {
1642                    setexp "${key} ICONS" " " 33 1
1643                }           
1644            }
1645
1646
1647            pref-get {
1648            #------------------------------------------------------
1649            # col 34: refine flag for POLA & DIFA
1650            #------------------------------------------------------
1651                if {[string toupper [string range \
1652                        [readexp "${key} ICONS"] 33 33]] == "P"} {
1653                    return 1
1654                }
1655                return 0
1656            }
1657            pref-set {
1658                if $value {
1659                    setexp "${key} ICONS" "P" 34 1
1660                } else {
1661                    setexp "${key} ICONS" " " 34 1
1662                }           
1663            }
1664            daref-get {
1665                if {[string toupper [string range \
1666                        [readexp "${key} ICONS"] 33 33]] == "A"} {
1667                    return 1
1668                }
1669                return 0
1670            }
1671            daref-set {
1672                if $value {
1673                    setexp "${key} ICONS" "A" 34 1
1674                } else {
1675                    setexp "${key} ICONS" " " 34 1
1676                }           
1677            }
1678
1679            zref-get {
1680            #------------------------------------------------------
1681            # col 34: refine flag for zero correction
1682            #------------------------------------------------------
1683                if {[string toupper [string range [readexp "${key} ICONS"] 34 34]] == "Z"} {
1684                    return 1
1685                }
1686                return 0
1687            }
1688            zref-set {
1689                if $value {
1690                    setexp "${key} ICONS" "Z" 35 1
1691                } else {
1692                    setexp "${key} ICONS" " " 35 1
1693                }           
1694            }
1695
1696            ddamp-get {
1697                set val [string range [readexp "${key} ICONS"] 39 39]
1698                if {$val == " "} {return 0}
1699                return $val
1700            }
1701            ddamp-set {
1702                setexp "${key} ICONS" $value 40 1
1703            }
1704
1705            backtype-get {
1706                set val [string trim [string range [readexp "${key}BAKGD "] 0 4]]
1707                if {$val == " "} {return 0}
1708                return $val
1709            }
1710            backtype-set {
1711                if ![validint value 5] {return 0}
1712                setexp "${key}BAKGD " $value 1 5
1713            }
1714            backterms-get {
1715                set val [string trim [string range [readexp "${key}BAKGD "] 5 9]]
1716                if {$val == " "} {return 0}
1717                return $val
1718            }
1719            backterms-set {
1720                # this takes a bit of work -- if terms are added, add lines as needed to the .EXP
1721                set oldval [string trim [string range [readexp "${key}BAKGD "] 5 9]]
1722                if ![validint value 5] {return 0}
1723                if {$oldval < $value} {
1724                    set line1  [expr {2 + ($oldval - 1) / 4}]
1725                    set line2  [expr {1 + ($value - 1) / 4}]
1726                    for {set i $line1} {$i <= $line2} {incr i} {
1727                        # create a blank entry if needed
1728                        makeexprec ${key}BAKGD$i
1729                    }
1730                    incr oldval
1731                    for {set num $oldval} {$num <= $value} {incr num} {
1732                        set f1 [expr {15*(($num - 1) % 4)}]
1733                        set f2 [expr {15*(1 + ($num - 1) % 4)-1}]
1734                        set line  [expr {1 + ($num - 1) / 4}]
1735                        if {[string trim [string range [readexp ${key}BAKGD$line] $f1 $f2]] == ""} {
1736                            set f1 [expr {15*(($num - 1) % 4)+1}]
1737                            setexp ${key}BAKGD$line 0.0 $f1 15                 
1738                        }
1739                    }
1740                }
1741                setexp "${key}BAKGD " $value 6 5
1742
1743            }
1744            bref-get {
1745                if {[string toupper [string range [readexp "${key}BAKGD"] 14 14]] == "Y"} {
1746                    return 1
1747                }
1748                return 0
1749            }
1750            bref-set {
1751                if $value {
1752                    setexp "${key}BAKGD "  "Y" 15 1
1753                } else {
1754                    setexp "${key}BAKGD "  "N" 15 1
1755                }
1756            }
1757            bdamp-get {
1758                set val [string range [readexp "${key}BAKGD "] 19 19]
1759                if {$val == " "} {return 0}
1760                return $val
1761            }
1762            bdamp-set {
1763                setexp "${key}BAKGD " $value 20 1
1764            }
1765            bterm*-get {
1766                regsub bterm $parm {} num
1767                set f1 [expr {15*(($num - 1) % 4)}]
1768                set f2 [expr {15*(1 + ($num - 1) % 4)-1}]
1769                set line  [expr {1 + ($num - 1) / 4}]
1770                return [string trim [string range [readexp ${key}BAKGD$line] $f1 $f2] ]
1771            }
1772            bterm*-set {
1773                regsub bterm $parm {} num
1774                if ![validreal value 15 6] {return 0}
1775                set f1 [expr {15*(($num - 1) % 4)+1}]
1776                set line  [expr {1 + ($num - 1) / 4}]
1777                setexp ${key}BAKGD$line $value $f1 15
1778            }
1779            bank-get {
1780                return [string trim [string range [readexp "${key} BANK"] 0 4]]
1781            }
1782            tofangle-get {
1783                return [string trim [string range [readexp "${key}BNKPAR"] 10 19]]
1784            }
1785            tmin-get {
1786                return [string trim [string range [readexp "${key} TRNGE"] 0 9]]
1787            }
1788            tmax-get {
1789                return [string trim [string range [readexp "${key} TRNGE"] 10 19]]
1790            }
1791            excl-get {
1792                set n [string trim [string range [readexp "${key} NEXC"] 0 4]]
1793                set exlist {}
1794                for {set i 1} {$i <= $n} {incr i} {
1795                    set line [readexp [format "${key}EXC%3d" $i]]
1796                    lappend exlist [list \
1797                            [string trim [string range $line  0  9]] \
1798                            [string trim [string range $line 10 19]]]
1799                }
1800                return $exlist
1801            }
1802            excl-set {
1803                set n [llength $value]
1804                if ![validint n 5] {return 0}
1805                setexp "${key} NEXC" $n 1 5
1806                set i 0
1807                foreach p $value {
1808                    incr i
1809                    foreach {r1 r2} $p {}
1810                    validreal r1 10 3
1811                    validreal r2 10 3
1812                    set k [format "${key}EXC%3d" $i]
1813                    if {![existsexp $k]} {
1814                        makeexprec $k
1815                    }
1816                    setexp $k ${r1}${r2} 1 20
1817                }
1818                # set the powpref warning (2 = required)
1819                catch {
1820                    global expgui
1821                    set expgui(needpowpref) 2
1822                    set msg "Excluded regions" 
1823                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1824                        append expgui(needpowpref_why) "\t$msg were changed\n"
1825                    }
1826                }
1827            }
1828            file-get {
1829                return [string trim [readexp "${key}  HFIL"] ]
1830            }
1831            file-set {
1832                setexp "${key}  HFIL" $value 3 65
1833            }
1834            bank-get {
1835                return [string trim [string range [readexp "${key} BANK"] 0 4]]
1836            }
1837            dmin-get {
1838                return [string trim [string range [readexp "${key} NREF"] 5 14]]
1839            }
1840            dmin-set {
1841                if ![validreal value 10 4] {return 0}
1842                setexp "${key} NREF" $value 6 10
1843                # set the powpref warning (2 = required)
1844                catch {
1845                    global expgui
1846                    set expgui(needpowpref) 2
1847                    set msg "Dmin (reflection range)" 
1848                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1849                        append expgui(needpowpref_why) "\t$msg was changed\n"
1850                    }
1851                }
1852            }
1853            use-get {
1854                set k [expr {($hist+11)/12}]
1855                set line [readexp " EXPR  HTYP$k"]
1856                set j [expr {((($hist-1) % 12)+1)*5}]
1857                if {[string range $line $j $j] == "*"} {return 0}
1858                return 1
1859            }
1860            use-set {
1861                set k [expr {($hist+11)/12}]
1862                set line [readexp " EXPR  HTYP$k"]
1863                set j [expr {((($hist-1) % 12)+1)*5+1}]
1864                if {$value} {
1865                    setexp " EXPR  HTYP$k" " " $j 1
1866                } else {
1867                    setexp " EXPR  HTYP$k" "*" $j 1
1868                }
1869                # set the powpref warning (2 = required)
1870                catch {
1871                    global expgui
1872                    set expgui(needpowpref) 2
1873                    set msg "Histogram use flags" 
1874                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1875                        append expgui(needpowpref_why) "\t$msg were changed\n"
1876                    }
1877                }
1878            }
1879            dstart-get {
1880                return [string trim [string range [readexp "${key} DUMMY"] 20 29]]
1881            }
1882            dstart-set {
1883                if ![validreal value 10 3] {return 0}
1884                setexp "${key} DUMMY" $value 21 10
1885                # set the powpref warning (1 = suggested)
1886                catch {
1887                    global expgui
1888                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1889                    set msg "Dummy histogram parameters" 
1890                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1891                        append expgui(needpowpref_why) "\t$msg were changed\n"
1892                    }
1893                }
1894            }
1895            dstep-get {
1896                return [string trim [string range [readexp "${key} DUMMY"] 30 39]]
1897            }
1898            dstep-set {
1899                if ![validreal value 10 3] {return 0}
1900                setexp "${key} DUMMY" $value 31 10
1901                catch {
1902                    global expgui
1903                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1904                    set msg "Dummy histogram parameters" 
1905                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1906                        append expgui(needpowpref_why) "\t$msg were changed\n"
1907                    }
1908                }
1909            }
1910            dpoints-get {
1911                return [string trim [string range [readexp "${key} DUMMY"] 0 9]]
1912            }
1913            dpoints-set {
1914                if ![validint value 10] {return 0}
1915                setexp "${key} DUMMY" $value 1 10
1916                catch {
1917                    global expgui
1918                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
1919                    set msg "Dummy histogram parameters" 
1920                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
1921                        append expgui(needpowpref_why) "\t$msg were changed\n"
1922                    }
1923                }
1924            }
1925            dtype-get {
1926                return [string trim [string range [readexp "${key} DUMMY"] 10 19]]
1927            }
1928            abscor1-get {
1929                return [string trim [string range [readexp "${key}ABSCOR"] 0 14]]
1930            }
1931            abscor1-set {
1932                if ![validreal value 15 7] {return 0}
1933                setexp "${key}ABSCOR" $value 1 15
1934            }
1935            abscor2-get {
1936                return [string trim [string range [readexp "${key}ABSCOR"] 15 29]]
1937            }
1938            abscor2-set {
1939                # this must have a decimal as the 5th character, so that we end up with a
1940                # decimal point in column 20.
1941                set tmp $value
1942                if ![validreal tmp 12 7] {return 0}
1943                set pos [string first "." $tmp]
1944                while {$pos < 4} {
1945                    set tmp " $tmp"
1946                    set pos [string first "." $tmp]
1947                }
1948                if {$pos == 4} {
1949                    setexp "${key}ABSCOR" $tmp 16 15
1950                    return
1951                }
1952                catch {
1953                    set tmp [format "%12.6E" $value]
1954                    set pos [string first "." $tmp]
1955                    while {$pos < 4} {
1956                        set tmp " $tmp"
1957                        set pos [string first "." $tmp]
1958                    }
1959                    if {$pos == 4} {
1960                        setexp "${key}ABSCOR" $tmp 16 15
1961                        return
1962                    }
1963                }
1964                return 0
1965            }
1966            abstype-get {
1967                set val [string trim [string range [readexp "${key}ABSCOR"] 40 44]]
1968                if {$val == ""} {set val 0}
1969                return $val
1970            }
1971            abstype-set {
1972                if ![validint value 5] {return 0}
1973                setexp "${key}ABSCOR" $value 41 5
1974            }
1975            absdamp-get {
1976                set val [string range [readexp "${key}ABSCOR"] 39 39]
1977                if {$val == " "} {return 0}
1978                return $val
1979            }
1980            absdamp-set {
1981                if ![validint value 5] {return 0}
1982                setexp "${key}ABSCOR" $value 36 5
1983            }
1984            absref-get {
1985                if {[string toupper \
1986                        [string range [readexp "${key}ABSCOR"] 34 34]] == "Y"} {
1987                    return 1
1988                }
1989                return 0
1990            }
1991            absref-set {
1992                if $value {
1993                    setexp "${key}ABSCOR" "    Y" 31 5
1994                } else {
1995                    setexp "${key}ABSCOR" "    N" 31 5
1996                }
1997            }
1998            ITYP-get {
1999                return [string trim [readexp "${key}I ITYP"]]
2000            }
2001            proftbl-get {
2002                set line [readexp "${key}PAB3"]
2003                if {$line == ""} {return 0}
2004                set val [string trim [string range $line 0 4]]
2005                if {$val == ""} {return 0}
2006                return $val
2007            }
2008            anomff-get {
2009                set l {}
2010                foreach i {1 2 3 4 5 6 7 8 9} {
2011                    if {![existsexp "${key}FFANS$i"]} continue
2012                    set line [readexp "${key}FFANS$i"]
2013                    set elem [string trim [string range $line 2 9]]
2014                    set fp [string trim [string range $line 10 19]]
2015                    set fpp [string trim [string range $line 20 29]]
2016                    lappend l [list $elem $fp $fpp]
2017                }
2018                return $l
2019            }
2020            anomff-set {
2021                # match up input against elements in list.
2022                # change elements included, return any elements that are
2023                # not found.
2024                set errorlist {}
2025                foreach triplet $value {
2026                    foreach {e fp fpp} $triplet {}               
2027                    foreach i {1 2 3 4 5 6 7 8 9} {
2028                        if {![existsexp "${key}FFANS$i"]} continue
2029                        # note that the element name is not used or validated
2030                        set elem [string trim [string range \
2031                                                   [readexp "${key}FFANS$i"] 2 9]]
2032                        if {[string match -nocase $e $elem]} { 
2033                            if ![validreal fp 10 3] {return 0}
2034                            setexp "${key}FFANS$i" $fp 11 10
2035                            if ![validreal fpp 10 3] {return 0}
2036                            setexp "${key}FFANS$i" $fpp 21 10
2037                            set e {}
2038                            break
2039                        }
2040                    }
2041                    if {$e != ""} {
2042                        # oops, no match
2043                        lappend errorlist $e
2044                    }
2045                }
2046                if {$errorlist != ""} {return [list 0 $errorlist]}
2047            }
2048            default {
2049                set msg "Unsupported histinfo access: parm=$parm action=$action"
2050                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
2051            }
2052        }
2053    }
2054    return 1
2055}
2056
2057# read the information that differs by both histogram and phase (profile & phase fraction)
2058# use: hapinfo hist phase parm action value
2059
2060#     frac -- phase fraction (*)
2061#     frref/frdamp -- refinement flag/damping value for the phase fraction (*)
2062#     proftype -- profile function number (*)
2063#     profterms -- number of profile terms (*)
2064#     pdamp -- damping value for the profile (*)
2065#     pcut -- cutoff value for the profile (*)
2066#     pterm$n -- profile term #n (*)
2067#     pref$n -- refinement flag value for profile term #n (*)
2068#     extmeth -- Fobs extraction method (*)
2069#     POnaxis -- number of defined M-D preferred axes
2070proc hapinfo {histlist phaselist parm "action get" "value {}"} {
2071    foreach phase $phaselist hist $histlist {
2072        if {$phase == ""} {set phase [lindex $phaselist end]}
2073        if {$hist == ""} {set hist [lindex $histlist end]}
2074        if {$hist < 10} {
2075            set hist " $hist"
2076        }
2077        set key "HAP${phase}${hist}"
2078        switch -glob ${parm}-$action {
2079            extmeth-get {
2080                set i1 [expr {($phase - 1)*5}]
2081                set i2 [expr {$i1 + 4}]
2082                return [string trim [string range [readexp "HST $hist EPHAS"] $i1 $i2]]
2083            }
2084            extmeth-set {
2085                set i1 [expr {($phase - 1)*5 + 1}]
2086                if ![validint value 5] {return 0}
2087                setexp "HST $hist EPHAS" $value $i1 5
2088            }
2089            frac-get {
2090                return [string trim [string range [readexp ${key}PHSFR] 0 14]]
2091            }
2092            frac-set {
2093                if ![validreal value 15 6] {return 0}
2094                setexp ${key}PHSFR $value 1 15
2095            }
2096            frref-get {
2097                if {[string toupper [string range [readexp ${key}PHSFR] 19 19]] == "Y"} {
2098                    return 1
2099                }
2100                return 0
2101            }
2102            frref-set {
2103                if $value {
2104                    setexp ${key}PHSFR "Y" 20 1
2105                } else {
2106                    setexp ${key}PHSFR "N" 20 1
2107                }           
2108            }
2109            frdamp-get {
2110                set val [string range [readexp ${key}PHSFR] 24 24]
2111                if {$val == " "} {return 0}
2112                return $val
2113            }
2114            frdamp-set {
2115                setexp ${key}PHSFR $value 25 1
2116            }
2117            proftype-get {
2118                set val [string range [readexp "${key}PRCF "] 0 4]
2119                if {$val == " "} {return 0}
2120                return $val
2121            }
2122            proftype-set {
2123                if ![validint value 5] {return 0}
2124                setexp "${key}PRCF " $value 1 5
2125                # set the powpref warning (1 = suggested)
2126                catch {
2127                    global expgui
2128                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
2129                    set msg "Profile parameters" 
2130                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2131                        append expgui(needpowpref_why) "\t$msg were changed\n"
2132                    }
2133                }
2134            }
2135            profterms-get {
2136                set val [string range [readexp "${key}PRCF "] 5 9]
2137                if {$val == " "} {return 0}
2138                return $val
2139            }
2140            profterms-set {
2141                if ![validint value 5] {return 0}
2142                setexp "${key}PRCF " $value 6 5
2143                # now check that all needed entries exist
2144                set lines [expr {1 + ($value - 1) / 4}]
2145                for {set i 1} {$i <= $lines} {incr i} {
2146                    makeexprec "${key}PRCF $i"
2147                }
2148                # set the powpref warning (1 = suggested)
2149                catch {
2150                    global expgui
2151                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
2152                    set msg "Profile parameters" 
2153                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2154                        append expgui(needpowpref_why) "\t$msg were changed\n"
2155                    }
2156                }
2157            }
2158            pcut-get {
2159                return [string trim [string range [readexp "${key}PRCF "] 10 19]]
2160            }
2161            pcut-set {
2162                if ![validreal value 10 5] {return 0}
2163                setexp "${key}PRCF " $value 11 10
2164                # set the powpref warning (1 = suggested)
2165                catch {
2166                    global expgui
2167                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
2168                    set msg "Profile parameters" 
2169                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2170                        append expgui(needpowpref_why) "\t$msg were changed\n"
2171                    }
2172                }
2173            }
2174            pdamp-get {
2175                set val [string range [readexp "${key}PRCF "] 24 24]
2176                if {$val == " "} {return 0}
2177                return $val
2178            }
2179            pdamp-set {
2180                setexp "${key}PRCF   " $value 25 1
2181            }
2182            pterm*-get {
2183                regsub pterm $parm {} num
2184                set f1 [expr {15*(($num - 1) % 4)}]
2185                set f2 [expr {15*(1 + ($num - 1) % 4)-1}]
2186                set line  [expr {1 + ($num - 1) / 4}]
2187                return [string trim [string range [readexp "${key}PRCF $line"] $f1 $f2] ]
2188            }
2189            pterm*-set {
2190                if ![validreal value 15 6] {return 0}
2191                regsub pterm $parm {} num
2192                set f1 [expr {1+ 15*(($num - 1) % 4)}]
2193                set line  [expr {1 + ($num - 1) / 4}]
2194                setexp "${key}PRCF $line" $value $f1 15
2195                # set the powpref warning (1 = suggested)
2196                catch {
2197                    global expgui
2198                    if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
2199                    set msg "Profile parameters" 
2200                    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2201                        append expgui(needpowpref_why) "\t$msg were changed\n"
2202                    }
2203                }
2204            }
2205            pref*-get {
2206                regsub pref $parm {} num
2207                set f [expr {24+$num}]
2208                if {[string toupper [string range [readexp "${key}PRCF  "] $f $f]] == "Y"} {
2209                    return 1
2210                }
2211                return 0
2212            }
2213            pref*-set {
2214                regsub pref $parm {} num
2215                set f [expr {25+$num}]
2216                if $value {
2217                    setexp ${key}PRCF "Y" $f 1
2218                } else {
2219                    setexp ${key}PRCF "N" $f 1
2220                }           
2221            }
2222            POnaxis-get {
2223                set val [string trim \
2224                        [string range [readexp "${key}NAXIS"] 0 4]]
2225                if {$val == ""} {return 0}
2226                return $val
2227            }
2228            POnaxis-set {
2229                if ![validint value 5] {return 0}
2230                # there should be a NAXIS record, but if not make one
2231                if {![existsexp "${key}NAXIS"]} {
2232                    makeexprec "${key}NAXIS"
2233                }
2234                setexp "${key}NAXIS  " $value 1 5
2235            }
2236            default {
2237                set msg "Unsupported hapinfo access: parm=$parm action=$action"
2238                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
2239            }
2240        }
2241    }
2242    return 1
2243}
2244
2245#  read fixed constraints
2246
2247proc atom_constraint_read {phase} {
2248    set fix_list ""
2249    foreach k {1 2 3 4 5 6 7 8 9} {
2250        set key [format "LEQV HOLD%1d%2d" $phase $k]
2251        set line [readexp $key]
2252        foreach j {2 10 18 26 34 42 50 58} {
2253            set fix_param [string range $line $j [expr $j+7]]
2254            if {[string trim $fix_param] == ""} {return $fix_list}
2255            lappend fix_list $fix_param
2256        }
2257    }
2258}
2259
2260# load all atom constraints into global array fix_param
2261proc atom_constraint_load { } {
2262    catch {unset ::fix_param}
2263    foreach i $::expmap(phaselist) {
2264        set temp [atom_constraint_read $i]
2265        foreach j $temp {
2266            set atomnum [string trim [string range $j 2 3]]
2267            set param [string trim [string range $j 4 6]]
2268            set ::fix_param($i,$atomnum,$param) 1   
2269        }
2270    }
2271}
2272
2273proc atom_constraint_write {phase fix_list} {
2274    foreach key [array names ::exparray "LEQV HOLD$phase*"] {
2275        delexp $key
2276    }
2277    set k 0
2278    set j 1
2279    set line ""
2280    foreach fix $fix_list {
2281        incr k
2282        append line $fix
2283        if {$k == 8} {
2284            set key [format "LEQV HOLD%1d%2d" $phase $j]
2285            makeexprec $key
2286            setexp $key $line 3 [expr ($k * 8) + 2]
2287            set k 0
2288            incr j
2289            set line ""
2290        }
2291    }
2292    if {$line != ""} {
2293        set key [format "LEQV HOLD%1d%2d" $phase $j]
2294        makeexprec $key
2295        setexp $key $line 3 [expr ($k * 8) + 2]
2296    }   
2297}
2298
2299
2300#  get a logical constraint
2301#
2302#  type action
2303#  -----------
2304#  atom get  number        returns a list of constraints.
2305#   "   set  number value  replaces a list of constraints
2306#                          (value is a list of constraints)
2307#   "   add  number value  inserts a new list of constraints
2308#                          (number is ignored)
2309#   "   delete number      deletes a set of constraint entries
2310# Each item in the list of constraints is composed of 4 items:
2311#              phase, atom, variable, multiplier
2312# If variable=UISO atom can be ALL, otherwise atom is a number
2313# legal variable names: FRAC, X, Y, Z, UISO, U11, U22, U33, U12, U23, U13,
2314#                       MX, MY, MZ
2315#
2316#  type action
2317#  -----------
2318#  profileXX get number         returns a list of constraints for term XX=1-36
2319#                               use number=0 to get # of defined
2320#                                  constraints for term XX
2321#   "        set number value   replaces a list of constraints
2322#                               (value is a list of constraints)
2323#   "        add number value   inserts a new list of constraints
2324#                               (number is ignored)
2325#   "        delete number      deletes a set of constraint entries
2326# Each item in the list of constraints is composed of 3 items:
2327#              phase-list, histogram-list, multiplier
2328# Note that phase-list and/or histogram-list can be ALL
2329
2330proc constrinfo {type action number "value {}"} {
2331    global expmap
2332    if {[lindex $expmap(phasetype) 0] == 4} {
2333        set mm 1
2334    } else {
2335        set mm 0
2336    }
2337    switch -glob ${type}-$action {
2338        atom-get {
2339            # does this constraint exist?
2340            set key [format "LNCN%4d%4d" $number 1]
2341            if {![existsexp $key]} {return -1}
2342            set clist {}
2343            for {set i 1} {$i < 999} {incr i} {
2344                set key [format "LNCN%4d%4d" $number $i]
2345                if {![existsexp $key]} break
2346                set line [readexp $key]
2347                set j1 2
2348                set j2 17
2349                set seg [string range $line $j1 $j2]
2350                while {[string trim $seg] != ""} {
2351                    set p [string range $seg 0 0]
2352                    if {$p == 1 && $mm} {
2353                        set atom [string trim [string range $seg 1 4]]
2354                        set var [string trim [string range $seg 5 7]]
2355                        if {$atom == "ALL"} {
2356                            set var UIS
2357                        } else {
2358                            scan $atom %x atom
2359                        }
2360                        lappend clist [list $p $atom $var \
2361                                [string trim [string range $seg 8 end]]]
2362                    } else {
2363                        lappend clist [list $p \
2364                                [string trim [string range $seg 1 3]] \
2365                                [string trim [string range $seg 4 7]] \
2366                                [string trim [string range $seg 8 end]]]
2367                    }
2368                    incr j1 16
2369                    incr j2 16
2370                    set seg [string range $line $j1 $j2]
2371                }
2372            }
2373            return $clist
2374        }
2375        atom-set {
2376            # delete records for current constraint
2377            for {set i 1} {$i < 999} {incr i} {
2378                set key [format "LNCN%4d%4d" $number $i]
2379                if {![existsexp $key]} break
2380                delexp $key
2381            }
2382            set line {}
2383            set i 1
2384            foreach tuple $value {
2385                set p [lindex $tuple 0]
2386                if {$p == 1 && $mm && \
2387                        [string toupper [lindex $tuple 1]] == "ALL"} {
2388                    set seg [format %1dALL UIS%8.4f \
2389                            [lindex $tuple 0] \
2390                            [lindex $tuple 3]]
2391                } elseif {$p == 1 && $mm} {
2392                    set seg [eval format %1d%.4X%-3s%8.4f $tuple]
2393                } elseif {[string toupper [lindex $tuple 1]] == "ALL"} {
2394                    set seg [format %1dALL%-4s%8.4f \
2395                            [lindex $tuple 0] \
2396                            [lindex $tuple 2] \
2397                            [lindex $tuple 3]]
2398                } else {
2399                    set seg [eval format %1d%3d%-4s%8.4f $tuple]
2400                }
2401                append line $seg
2402                if {[string length $line] > 50} {
2403                    set key  [format "LNCN%4d%4d" $number $i]
2404                    makeexprec $key
2405                    setexp $key $line 3 68
2406                    set line {}
2407                    incr i
2408                }
2409            }
2410            if {$line != ""} {
2411                set key  [format "LNCN%4d%4d" $number $i]
2412                makeexprec $key
2413                setexp $key $line 3 68
2414            }
2415            return
2416        }
2417        atom-add {
2418            # loop over defined constraints
2419            for {set j 1} {$j < 9999} {incr j} {
2420                set key [format "LNCN%4d%4d" $j 1]
2421                if {![existsexp $key]} break
2422            }
2423            set number $j
2424            # save the constraint
2425            set line {}
2426            set i 1
2427            foreach tuple $value {
2428                set p [lindex $tuple 0]
2429                if {$p == 1 && $mm && \
2430                        [string toupper [lindex $tuple 1]] == "ALL"} {
2431                    set seg [format %1dALL UIS%8.4f \
2432                            [lindex $tuple 0] \
2433                            [lindex $tuple 3]]
2434                } elseif {$p == 1 && $mm} {
2435                    set seg [eval format %1d%.4X%-3s%8.4f $tuple]
2436                } elseif {[string toupper [lindex $tuple 1]] == "ALL"} {
2437                    set seg [format %1dALL%-4s%8.4f \
2438                            [lindex $tuple 0] \
2439                            [lindex $tuple 2] \
2440                            [lindex $tuple 3]]
2441                } else {
2442                    set seg [eval format %1d%3d%-4s%8.4f $tuple]
2443                }
2444                append line $seg
2445                if {[string length $line] > 50} {
2446                    set key  [format "LNCN%4d%4d" $number $i]
2447                    makeexprec $key
2448                    setexp $key $line 3 68
2449                    set line {}
2450                    incr i
2451                }
2452            }
2453            if {$line != ""} {
2454                set key  [format "LNCN%4d%4d" $number $i]
2455                makeexprec $key
2456                setexp $key $line 3 68
2457            }
2458            return
2459        }
2460        atom-delete {
2461            for {set j $number} {$j < 9999} {incr j} {
2462                # delete records for current constraint
2463                for {set i 1} {$i < 999} {incr i} {
2464                    set key [format "LNCN%4d%4d" $j $i]
2465                    if {![existsexp $key]} break
2466                    delexp $key
2467                }
2468                # now copy records, from the next entry, if any
2469                set j1 $j
2470                incr j1
2471                set key1 [format "LNCN%4d%4d" $j1 1]
2472                # if there is no record, there is nothing to copy -- done
2473                if {![existsexp $key1]} return
2474                for {set i 1} {$i < 999} {incr i} {
2475                    set key1 [format "LNCN%4d%4d" $j1 $i]
2476                    if {![existsexp $key1]} break
2477                    set key  [format "LNCN%4d%4d" $j  $i]
2478                    makeexprec $key
2479                    setexp $key [readexp $key1] 1 68
2480                }
2481            }
2482        }
2483        profile*-delete {
2484            regsub profile $type {} term
2485            if {$term < 10} {
2486                set term " $term"
2487            }
2488            set key "LEQV PF$term   "
2489            # return nothing if no term exists
2490            if {![existsexp $key]} {return 0}
2491
2492            # number of constraint terms
2493            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2494            # don't delete a non-existing entry
2495            if {$number > $nterms} {return 0}
2496            set val [expr {$nterms - 1}]
2497            validint val 5
2498            setexp $key $val 1 5
2499            for {set i1 $number} {$i1 < $nterms} {incr i1} {
2500                set i2 [expr {1 + $i1}]
2501                # move the contents of constraint #i2 -> i1
2502                if {$i1 > 9} {
2503                    set k1 [expr {($i1+1)/10}]
2504                    set l1 $i1
2505                } else {
2506                    set k1 " "
2507                    set l1 " $i1"
2508                }
2509                set key1 "LEQV PF$term  $k1"
2510                # number of constraint lines for #i1
2511                set n1 [string trim [string range [readexp ${key1}] \
2512                        [expr {($i1%10)*5}] [expr {4+(($i1%10)*5)}]] ]
2513                if {$i2 > 9} {
2514                    set k2 [expr {($i2+1)/10}]
2515                    set l2 $i2
2516                } else {
2517                    set k2 " "
2518                    set l2 " $i2"
2519                }
2520                set key2 "LEQV PF$term  $k2"
2521                # number of constraint lines for #i2
2522                set n2 [string trim [string range [readexp ${key2}] \
2523                        [expr {($i2%10)*5}] [expr {4+(($i2%10)*5)}]] ]
2524                set val $n2
2525                validint val 5
2526                # move the # of terms
2527                setexp $key1 $val [expr {1+(($i1%10)*5)}] 5
2528                # move the terms
2529                for {set j 1} {$j <= $n2} {incr j 1} {
2530                    set key "LEQV PF${term}${l1}$j"
2531                    makeexprec $key
2532                    setexp $key [readexp "LEQV PF${term}${l2}$j"] 1 68
2533                }
2534                # delete any remaining lines
2535                for {set j [expr {$n2+1}]} {$j <= $n1} {incr j 1} {
2536                    delexp "LEQV PF${term}${l1}$j"
2537                }
2538            }
2539
2540            # clear the last term
2541            if {$nterms > 9} {
2542                set i [expr {($nterms+1)/10}]
2543            } else {
2544                set i " "
2545            }
2546            set key "LEQV PF$term  $i"
2547            set cb [expr {($nterms%10)*5}]
2548            set ce [expr {4+(($nterms%10)*5)}]
2549            set n2 [string trim [string range [readexp ${key}] $cb $ce] ]
2550            incr cb
2551            setexp $key "     " $cb 5
2552            # delete any remaining lines
2553            for {set j 1} {$j <= $n2} {incr j 1} {
2554                delexp "LEQV PF${term}${nterms}$j"
2555            }
2556        }
2557        profile*-set {
2558            regsub profile $type {} term
2559            if {$term < 10} {
2560                set term " $term"
2561            }
2562            set key "LEQV PF$term   "
2563            # get number of constraint terms
2564            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2565            # don't change a non-existing entry
2566            if {$number > $nterms} {return 0}
2567            if {$number > 9} {
2568                set k1 [expr {($number+1)/10}]
2569                set l1 $number
2570            } else {
2571                set k1 " "
2572                set l1 " $number"
2573            }
2574            set key1 "LEQV PF$term  $k1"
2575            # old number of constraint lines
2576            set n1 [string trim [string range [readexp ${key1}] \
2577                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2578            # number of new constraints
2579            set j2 [llength $value]
2580            # number of new constraint lines
2581            set val [set n2 [expr {($j2 + 2)/3}]]
2582            # store the new # of lines
2583            validint val 5
2584            setexp $key1 $val [expr {1+(($number%10)*5)}] 5
2585
2586            # loop over the # of lines in the old or new, whichever is greater
2587            set v0 0
2588            for {set j 1} {$j <= [expr {($n1 > $n2) ? $n1 : $n2}]} {incr j 1} {
2589                set key "LEQV PF${term}${l1}$j"
2590                # were there more lines in the old?
2591                if {$j > $n2} {
2592                    # this line is not needed
2593                    if {$j % 3 == 1} {
2594                        delexp %key
2595                    }
2596                    continue
2597                }
2598                # are we adding new lines?
2599                if {$j > $n1} {
2600                    makeexprec $key
2601                }
2602                # add the three constraints to the line
2603                foreach s {3 23 43} \
2604                        item [lrange $value $v0 [expr {2+$v0}]] {
2605                    if {$item != ""} {
2606                        set val [format %-10s%9.3f \
2607                                [lindex $item 0],[lindex $item 1] \
2608                                [lindex $item 2]]
2609                        setexp $key $val $s 19
2610                    } else {
2611                        setexp $key " " $s 19
2612                    }
2613                }
2614                incr v0 3
2615            }
2616        }
2617        profile*-add {
2618            regsub profile $type {} term
2619            if {$term < 10} {
2620                set term " $term"
2621            }
2622            set key "LEQV PF$term   "
2623            if {![existsexp $key]} {makeexprec $key}
2624            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2625            if {$nterms == ""} {
2626                set nterms 1
2627            } elseif {$nterms >= 99} {
2628                return 0
2629            } else {
2630                incr nterms
2631            }
2632            # store the new # of constraints
2633            set val $nterms
2634            validint val 5
2635            setexp $key $val 1 5
2636
2637            if {$nterms > 9} {
2638                set k1 [expr {($nterms+1)/10}]
2639                set l1 $nterms
2640            } else {
2641                set k1 " "
2642                set l1 " $nterms"
2643            }
2644            set key1 "LEQV PF$term  $k1"
2645
2646            # number of new constraints
2647            set j2 [llength $value]
2648            # number of new constraint lines
2649            set val [set n2 [expr {($j2 + 2)/3}]]
2650            # store the new # of lines
2651            validint val 5
2652            setexp $key1 $val [expr {1+(($nterms%10)*5)}] 5
2653
2654            # loop over the # of lines to be added
2655            set v0 0
2656            for {set j 1} {$j <= $n2} {incr j 1} {
2657                set key "LEQV PF${term}${l1}$j"
2658                makeexprec $key
2659                # add the three constraints to the line
2660                foreach s {3 23 43} \
2661                        item [lrange $value $v0 [expr {2+$v0}]] {
2662                    if {$item != ""} {
2663                        set val [format %-10s%9.3f \
2664                                [lindex $item 0],[lindex $item 1] \
2665                                [lindex $item 2]]
2666                        setexp $key $val $s 19
2667                    } else {
2668                        setexp $key " " $s 19
2669                    }
2670                }
2671                incr v0 3
2672            }
2673        }
2674        profile*-get {
2675            regsub profile $type {} term
2676            if {$term < 10} {
2677                set term " $term"
2678            }
2679            if {$number > 9} {
2680                set i [expr {($number+1)/10}]
2681            } else {
2682                set i " "
2683            }
2684            set key "LEQV PF$term  $i"
2685            # return nothing if no term exists
2686            if {![existsexp $key]} {return 0}
2687            # number of constraint lines
2688           
2689            set numline [string trim [string range [readexp ${key}] \
2690                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2691            if {$number == 0} {return $numline}
2692            set clist {}
2693            if {$number < 10} {
2694                set number " $number"
2695            }
2696            for {set i 1} {$i <= $numline} {incr i} {
2697                set key "LEQV PF${term}${number}$i"
2698                set line [readexp ${key}]
2699                foreach s {1 21 41} e {20 40 60} {
2700                    set seg [string range $line $s $e]
2701                    if {[string trim $seg] == ""} continue
2702                    # parse the string segment
2703                    set parse [regexp { *([0-9AL]+),([0-9AL]+) +([0-9.]+)} \
2704                            $seg junk phase hist mult]
2705                    # was parse successful
2706                    if {!$parse} {continue}
2707                    lappend clist [list $phase $hist $mult]
2708                }
2709            }
2710            return $clist
2711        }
2712        default {
2713            set msg "Unsupported constrinfo access: type=$type action=$action"
2714            tk_dialog .badexp "Error in readexp access" $msg error 0 OK
2715        }
2716
2717    }
2718}
2719
2720# read the default profile information for a histogram
2721# use: profdefinfo hist set# parm action
2722
2723#     proftype -- profile function number
2724#     profterms -- number of profile terms
2725#     pdamp -- damping value for the profile (*)
2726#     pcut -- cutoff value for the profile (*)
2727#     pterm$n -- profile term #n
2728#     pref$n -- refinement flag value for profile term #n (*)
2729
2730proc profdefinfo {hist set parm "action get"} {
2731    global expgui
2732    if {$hist < 10} {
2733        set key "HST  $hist"
2734    } else {
2735        set key "HST $hist"
2736    }
2737    switch -glob ${parm}-$action {
2738        proftype-get {
2739            set val [string range [readexp "${key}PRCF$set"] 0 4]
2740            if {$val == " "} {return 0}
2741            return $val
2742        }
2743        profterms-get {
2744            set val [string range [readexp "${key}PRCF$set"] 5 9]
2745            if {$val == " "} {return 0}
2746            return $val
2747        }
2748        pcut-get {
2749            return [string trim [string range [readexp "${key}PRCF$set"] 10 19]]
2750        }
2751        pdamp-get {
2752                set val [string range [readexp "${key}PRCF$set"] 24 24]
2753            if {$val == " "} {return 0}
2754            return $val
2755        }
2756        pterm*-get {
2757            regsub pterm $parm {} num
2758            set f1 [expr {15*(($num - 1) % 4)}]
2759            set f2 [expr {15*(1 + ($num - 1) % 4)-1}]
2760            set line  [expr {1 + ($num - 1) / 4}]
2761            return [string trim [string range [\
2762                        readexp "${key}PRCF${set}$line"] $f1 $f2] ]
2763        }
2764        pref*-get {
2765            regsub pref $parm {} num
2766            set f [expr {24+$num}]
2767            if {[string toupper [string range [readexp "${key}PRCF$set"] $f $f]] == "Y"} {
2768                return 1
2769            }
2770            return 0
2771        }
2772        default {
2773            set msg "Unsupported profdefinfo access: parm=$parm action=$action"
2774            tk_dialog .badexp "Code Error" $msg error 0 Exit
2775        }
2776    }
2777}
2778
2779# get March-Dollase preferred orientation information
2780# use MDprefinfo hist phase axis-number parm action value
2781#    ratio    -- ratio of xtallites in PO direction vs random (>1 for more)
2782#    fraction -- fraction in this direction, when more than one axis is used
2783#    h k & l  -- indices of P.O. axis
2784#    ratioref -- flag to vary ratio
2785#    fracref  -- flag to vary fraction
2786#    damp     -- damping value
2787#    type     -- model type (0 = P.O. _|_ to beam, 1 = || to beam)
2788#    new      -- creates a new record with default values (set only)
2789proc MDprefinfo {histlist phaselist axislist parm "action get" "value {}"} {
2790    foreach phase $phaselist hist $histlist axis $axislist {
2791        if {$phase == ""} {set phase [lindex $phaselist end]}
2792        if {$hist == ""} {set hist [lindex $histlist end]}
2793        if {$axis == ""} {set axis [lindex $axislist end]}
2794        if {$hist < 10} {
2795            set hist " $hist"
2796        }
2797        if {$axis > 9} {
2798            set axis "0"
2799        }
2800        set key "HAP${phase}${hist}PREFO${axis}"
2801        switch -glob ${parm}-$action {
2802            ratio-get {
2803                return [string trim [string range [readexp $key] 0 9]]
2804            }
2805            ratio-set {
2806                if ![validreal value 10 6] {return 0}
2807                setexp $key $value 1 10
2808            }
2809            fraction-get {
2810                return [string trim [string range [readexp $key] 10 19]]
2811            }
2812            fraction-set {
2813                if ![validreal value 10 6] {return 0}
2814                setexp $key $value 11 10
2815            }
2816            h-get {
2817                set h [string trim [string range [readexp $key] 20 29]]
2818                # why not allow negative h values?
2819                #               if {$h < 1} {return 0}
2820                return $h
2821            }
2822            h-set {
2823                if ![validreal value 10 2] {return 0}
2824                setexp $key $value 21 10
2825            }
2826            k-get {
2827                set k [string trim [string range [readexp $key] 30 39]]
2828                #               if {$k < 1} {return 0}
2829                return $k
2830            }
2831            k-set {
2832                if ![validreal value 10 2] {return 0}
2833                setexp $key $value 31 10
2834            }
2835            l-get {
2836                set l [string trim [string range [readexp $key] 40 49]]
2837                #if {$l < 1} {return 0}
2838                return $l
2839            }
2840            l-set {
2841                if ![validreal value 10 2] {return 0}
2842                setexp $key $value 41 10
2843            }
2844            ratioref-get {
2845                if {[string toupper \
2846                        [string range [readexp $key] 53 53]] == "Y"} {
2847                    return 1
2848                }
2849                return 0
2850            }
2851            ratioref-set {
2852                if $value {
2853                    setexp $key "Y" 54 1
2854                } else {
2855                    setexp $key "N" 54 1
2856                }
2857            }
2858            fracref-get {
2859                if {[string toupper \
2860                        [string range [readexp $key] 54 54]] == "Y"} {
2861                    return 1
2862                }
2863                return 0
2864            }
2865            fracref-set {
2866                if $value {
2867                    setexp $key "Y" 55 1
2868                } else {
2869                    setexp $key "N" 55 1
2870              }
2871            }
2872            damp-get {
2873                set val [string trim [string range [readexp $key] 59 59]]
2874                if {$val == " "} {return 0}
2875                return $val
2876            }
2877            damp-set {
2878                setexp $key $value 60 1
2879            }
2880            type-get {
2881                set val [string trim [string range [readexp $key] 64 64]]
2882                if {$val == " "} {return 0}
2883                return $val
2884            }
2885            type-set {
2886                # only valid settings are 0 & 1
2887                if {$value != "0" && $value != "1"} {set value "0"}
2888                setexp $key $value 65 1
2889            }
2890            new-set {
2891                makeexprec $key
2892                setexp $key \
2893                        {  1.000000  1.000000  0.000000  0.000000  1.000000   NN    0    0} \
2894                        1 68
2895            }
2896            default {
2897                set msg "Unsupported MDprefinfo access: parm=$parm action=$action"
2898                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
2899            }
2900
2901        }
2902
2903    }
2904}
2905
2906# get list of defined atom types
2907proc AtmTypList {} {
2908    set natypes [readexp " EXPR  NATYP"]
2909    if {$natypes == ""} return
2910    set j 0
2911    set typelist {}
2912    for {set i 1} {$i <= $natypes} {incr i} {
2913        set key {this should never be matched}
2914        while {![existsexp $key]} {
2915            incr j
2916            if {$j > 99} {
2917                return $typelist
2918            } elseif {$j <10} {
2919                set key " EXPR ATYP $j"
2920            } else {
2921                set key " EXPR ATYP$j"
2922            }
2923        }
2924        lappend typelist [string trim [string range $::exparray($key) 2 9]]
2925    }
2926    return $typelist
2927}
2928
2929# read information about atom types
2930#     distrad    atomic distance search radius (get/set)
2931#     angrad     atomic angle search radius (get/set)
2932proc AtmTypInfo {parm atmtype "action get" "value {}"} {
2933    # first, search through the records to find the record matching the type
2934    set natypes [readexp " EXPR  NATYP"]
2935    if {$natypes == ""} return
2936    set j 0
2937    set typelist {}
2938    for {set i 1} {$i <= $natypes} {incr i} {
2939        set key {this should never be matched}
2940        while {![existsexp $key]} {
2941            incr j
2942            if {$j > 99} {
2943                return $typelist
2944            } elseif {$j <10} {
2945                set key " EXPR ATYP $j"
2946            } else {
2947                set key " EXPR ATYP$j"
2948            }
2949        }
2950        if {[string toupper $atmtype] == \
2951                [string toupper [string trim [string range $::exparray($key) 2 9]]]} break
2952        set key {}
2953    }
2954    if {$key == ""} {
2955        # atom type not found
2956        return {}
2957    }
2958    switch -glob ${parm}-$action {
2959        distrad-get {
2960            return [string trim [string range [readexp $key] 15 24]]
2961        }
2962        distrad-set {
2963            if ![validreal value 10 2] {return 0}
2964            setexp $key $value 16 10
2965        }
2966        angrad-get {
2967            return [string trim [string range [readexp $key] 25 34]]
2968        }
2969        angrad-set {
2970            if ![validreal value 10 2] {return 0}
2971            setexp $key $value 26 10
2972        }
2973        default {
2974            set msg "Unsupported AtmTypInfo access: parm=$parm action=$action"
2975            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
2976        }
2977    }
2978}
2979# read default information about atom types (records copied to the .EXP file
2980# from the gsas/data/atomdata.dat file as AFAC ...
2981#     distrad returns a list of atom types (one or two letters) and
2982#                the corresponding distance
2983# note that these values are read only (no set option)
2984proc DefAtmTypInfo {parm} {
2985    set keys [array names ::exparray " AFAC *_SIZ"]
2986    set elmlist {}
2987    if {[llength $keys] <= 0} {return ""}
2988    foreach key $keys {
2989        lappend elmlist [string trim [string range $key 6 7]]
2990    }
2991    switch -glob ${parm} {
2992        distrad {
2993            set out {}
2994            foreach key $keys elm $elmlist {
2995                set val [string range $::exparray($key) 0 9]
2996                lappend out "$elm [string trim $val]"
2997            }
2998            return $out
2999        }
3000        angrad {
3001            set out {}
3002            foreach key $keys elm $elmlist {
3003                set val [string range $::exparray($key) 10 19]
3004                lappend out "$elm [string trim $val]"
3005            }
3006            return $out
3007        }
3008        default {
3009            set msg "Unsupported DefAtmTypInfo access: parm=$parm"
3010            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3011        }
3012    }
3013}
3014# write the .EXP file
3015proc expwrite {expfile} {
3016    global exparray
3017    set blankline \
3018     "                                                                        "
3019    set fp [open ${expfile} w]
3020    fconfigure $fp -translation crlf -encoding ascii
3021    set keylist [lsort [array names exparray]]
3022    # reorder the keys so that VERSION comes 1st
3023    set pos [lsearch -exact $keylist {     VERSION}]
3024    set keylist "{     VERSION} [lreplace $keylist $pos $pos]"
3025    foreach key $keylist {
3026        puts $fp [string range \
3027                "$key$exparray($key)$blankline" 0 79]
3028    }
3029    close $fp
3030}
3031
3032# history commands -- delete all but last $keep history records,
3033# renumber if $renumber is true
3034proc DeleteHistory {keep renumber} {
3035    global exparray
3036    foreach y [lrange [lsort -decreasing \
3037            [array names exparray {    HSTRY*}]] $keep end] {
3038        unset exparray($y)
3039    }
3040    if !$renumber return
3041    # renumber
3042    set i 0
3043    foreach y [lsort -increasing \
3044            [array names exparray {    HSTRY*}]] {
3045        set key [format "    HSTRY%3d" [incr i]]
3046        set exparray($key) $exparray($y)
3047        unset exparray($y)
3048    }
3049    # list all history
3050    #    foreach y [lsort -decreasing [array names exparray {    HSTRY*}]] {puts "$y $exparray($y)"}
3051}
3052
3053proc CountHistory {} {
3054    global exparray
3055    return [llength [array names exparray {    HSTRY*}]]
3056}
3057
3058# set the phase flags for histogram $hist to $plist
3059proc SetPhaseFlag {hist plist} {
3060    # make a 2 digit key -- hh
3061    if {$hist < 10} {
3062        set hh " $hist"
3063    } else {
3064        set hh $hist
3065    }
3066    set key "HST $hh NPHAS"
3067    set str {}
3068    foreach iph {1 2 3 4 5 6 7 8 9} {
3069        if {[lsearch $plist $iph] != -1} {
3070            append str {    1}
3071        } else {
3072            append str {    0}     
3073        }
3074    }
3075    setexp $key $str 1 68
3076}
3077
3078# erase atom $atom from phase $phase
3079# update the list of atom types, erasing the record if not needed.
3080proc EraseAtom {atom phase} {
3081    set type [atominfo $phase $atom type]
3082    if {$type == ""} return
3083    if {$atom < 10} {
3084        set key "CRS$phase  AT  $atom"
3085    } elseif {$atom < 100} {
3086        set key "CRS$phase  AT $atom"
3087    } else {
3088        set key "CRS$phase  AT$atom"
3089    }
3090    # delete the records for the atom
3091    global exparray
3092    foreach k [array names exparray ${key}*] {
3093        delexp $k
3094    }
3095    # change the number of atoms in the phase
3096    phaseinfo $phase natoms set [expr {[phaseinfo $phase natoms] -1}]
3097
3098    # now adjust numbers in "EXPR ATYP" records and delete, if needed.
3099    set natypes [readexp " EXPR  NATYP"]
3100    if {$natypes == ""} return
3101    set j 0
3102    for {set i 1} {$i <= $natypes} {incr i} {
3103        incr j
3104        if {$j <10} {
3105            set key " EXPR ATYP $j"
3106        } else {
3107            set key " EXPR ATYP$j"
3108        }
3109        while {![existsexp $key]} {
3110            incr j
3111            if {$j > 99} {
3112                return
3113            } elseif {$j <10} {
3114                set key " EXPR ATYP $j"
3115            } else {
3116                set key " EXPR ATYP$j"
3117            }
3118        }
3119        set keytype [string trim [string range $exparray($key) 2 9]]
3120        if {$type == $keytype} {
3121            # found the type record
3122            set val [string trim [string range $exparray($key) 10 14]]
3123            incr val -1
3124            # if this is the last reference, remove the record,
3125            # otherwise, decrement the counter
3126            if {$val <= 0} {
3127                incr natypes -1 
3128                validint natypes 5
3129                setexp " EXPR  NATYP" $natypes 1 5
3130                delexp $key
3131            } else {
3132                validint val 5
3133                setexp $key $val 11 5
3134            }
3135            return
3136        }
3137    }
3138}
3139
3140# compute equivalent anisotropic temperature factor for Uequiv
3141proc CalcAniso {phase Uequiv} {
3142    foreach var {a b c alpha beta gamma} {
3143        set $var [phaseinfo $phase $var]
3144    }
3145
3146    set G(1,1) [expr {$a * $a}]
3147    set G(2,2) [expr {$b * $b}]
3148    set G(3,3) [expr {$c * $c}]
3149    set G(1,2) [expr {$a * $b * cos($gamma*0.017453292519943)}]
3150    set G(2,1) $G(1,2)
3151    set G(1,3) [expr {$a * $c * cos($beta *0.017453292519943)}]
3152    set G(3,1) $G(1,3)
3153    set G(2,3) [expr {$b * $c * cos($alpha*0.017453292519943)}]
3154    set G(3,2) $G(2,3)
3155
3156    # Calculate the volume**2
3157    set v2 0.0
3158    foreach i {1 2 3} {
3159        set J [expr {($i%3) + 1}]
3160        set K [expr {(($i+1)%3) + 1}]
3161        set v2 [expr {$v2+ $G(1,$i)*($G(2,$J)*$G(3,$K)-$G(3,$J)*$G(2,$K))}]
3162    }
3163    if {$v2 > 0} {
3164        set v [expr {sqrt($v2)}]
3165        foreach i {1 2 3} {
3166            set i1 [expr {($i%3) + 1}]
3167            set i2 [expr {(($i+1)%3) + 1}]
3168            foreach j {1 2 3} {
3169                set j1 [expr {($j%3) + 1}]
3170                set j2 [expr {(($j+1)%3) + 1}]
3171                set C($j,$i) [expr {(\
3172                        $G($i1,$j1) * $G($i2,$j2) - \
3173                        $G($i1,$j2)  * $G($i2,$j1)\
3174                        )/ $v}]
3175            }
3176        }
3177        set A(1,2) [expr {0.5 * ($C(1,2)+$C(2,1)) / sqrt( $C(1,1)* $C(2,2) )}]
3178        set A(1,3) [expr {0.5 * ($C(1,3)+$C(3,1)) / sqrt( $C(1,1)* $C(3,3) )}]
3179        set A(2,3) [expr {0.5 * ($C(2,3)+$C(3,2)) / sqrt( $C(2,2)* $C(3,3) )}]
3180        foreach i {1 1 2} j {2 3 3} {
3181            set A($i,$j) [expr {0.5 * ($C($i,$j) + $C($j,$i)) / \
3182                    sqrt( $C($i,$i)* $C($j,$j) )}]
3183            # clean up roundoff
3184            if {abs($A($i,$j)) < 1e-5} {set A($i,$j) 0.0}
3185        }
3186    } else {
3187        set A(1,2) 0.0
3188        set A(1,3) 0.0
3189        set A(2,3) 0.0
3190    }
3191    return "$Uequiv $Uequiv $Uequiv \
3192            [expr {$Uequiv * $A(1,2)}] \
3193            [expr {$Uequiv * $A(1,3)}] \
3194            [expr {$Uequiv * $A(2,3)}]"
3195}
3196
3197# read/edit soft (distance) restraint info
3198#  parm:
3199#    weight -- histogram weight (factr) *
3200#    restraintlist -- list of restraints *
3201#  action: get (default) or set
3202#  value: used only with set
3203#  * =>  read+write supported
3204proc SoftConst {parm "action get" "value {}"} {
3205    set HST {}
3206    # look for RSN record
3207    set n 0
3208    for {set i 0} {$i < $::expmap(nhst)} {incr i} {
3209        set ihist [expr {$i + 1}]
3210        if {[expr {$i % 12}] == 0} {
3211            incr n
3212            set line [readexp " EXPR  HTYP$n"]
3213            if {$line == ""} {
3214                set msg "No HTYP$n entry for Histogram $ihist. This is an invalid .EXP file"
3215                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3216            }
3217            set j 0
3218        } else {
3219            incr j
3220        }
3221        if {[string range $line [expr 2+5*$j] [expr 5*($j+1)]] == "RSN "} {
3222            set HST $ihist
3223        }
3224    }
3225    if {$HST <=9} {
3226        set key "HST  $HST"
3227    } else {
3228        set key "HST $HST"
3229    }
3230    if {$HST == "" && $action == "set"} {
3231        # no RSN found need to add the soft constr. histogram
3232        # increment number of histograms
3233        set hst [string trim [string range [readexp { EXPR  NHST }] 0 4]]
3234        incr hst
3235        set HST $hst
3236        if ![validint hst 5] {return 0}
3237        setexp  { EXPR  NHST } $hst 1 5
3238        # add to EXPR HTYPx rec, creating if needed
3239        set n [expr { 1+ (($HST - 1) / 12) }]
3240        set key " EXPR  HTYP$n"
3241        if {[array names ::exparray $key] == ""} {
3242            makeexprec $key
3243        }
3244        setexp $key "RSN " [expr 3 + 5*(($HST-1) % 12)] 5
3245        # create other HST  xx recs
3246        if {$HST <=9} {
3247            set key "HST  $HST"
3248        } else {
3249            set key "HST $HST"
3250        }
3251        makeexprec "$key  HNAM"
3252        setexp "$key  HNAM" "Bond distance restraints" 3 24
3253        makeexprec "$key FACTR"
3254        makeexprec "$key NBNDS"
3255        mapexp
3256    } elseif {$HST == ""} {
3257        if $::expgui(debug) {puts "no restraints"}
3258        return "1"
3259    }
3260
3261    switch -glob ${parm}-$action {
3262        weight-get {
3263            return [string trim [string range [readexp "$key FACTR"] 0 14]]
3264        }
3265        weight-set {
3266            # update FACTR
3267            if ![validreal value 15 6] {return 0}
3268            setexp "$key FACTR" $value 1 15
3269        }
3270        restraintlist-get {
3271            set ncons [string trim [string range [readexp "$key NBNDS"] 0 4]]
3272            set conslist {}
3273            for {set i 1} {$i <= $ncons} {incr i} {
3274                set fi [string toupper [format %.4x $i]]
3275                set line [readexp "${key}BD$fi"]
3276                set const {}
3277                foreach len {3 5 5 3 3 3 3 3 6 6} {
3278                  set lenm1 [expr {$len - 1}]
3279                  lappend const [string trim [string range $line 0 $lenm1]]
3280                  set line [string range $line $len end]
3281                }
3282                lappend conslist $const
3283            }
3284            return $conslist
3285        }
3286        restraintlist-set {
3287            set num [llength $value]
3288            if ![validint num 5] {return 0}
3289            setexp "$key NBNDS" $num 1 5
3290            # delete all old records
3291            foreach i [array names ::exparray "${key}BD*"] {unset ::exparray($i)}
3292            set i 0
3293            foreach cons $value {
3294                incr i
3295                set fi [string toupper [format %.4x $i]]
3296                makeexprec "${key}BD$fi"
3297                set pos 1
3298                foreach num $cons len {3 5 5 3 3 3 3 3 -6 -6} {
3299                    if {$len > 0} {
3300                        validint num $len
3301                        setexp "${key}BD$fi" $num $pos $len
3302                    } else {
3303                        set len [expr abs($len)]
3304                        validreal num $len 3
3305                        setexp "${key}BD$fi" $num $pos $len
3306                    }
3307                    incr pos $len
3308                }
3309            }
3310        }
3311        default {
3312            set msg "Unsupported phaseinfo access: parm=$parm action=$action"
3313            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3314        }
3315    return 1
3316    }
3317}
3318
3319#======================================================================
3320# conversion routines
3321#======================================================================
3322
3323# convert x values to d-space
3324proc tod {xlist hst} {
3325    global expmap
3326    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3327        return [toftod $xlist $hst]
3328    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3329        return [tttod $xlist $hst]
3330    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3331        return [engtod $xlist $hst]
3332    } else {
3333        return {}
3334    }
3335}
3336
3337# convert tof to d-space
3338proc toftod {toflist hst} {
3339    set difc [expr {[histinfo $hst difc]/1000.}]
3340    set difc2 [expr {$difc*$difc}]
3341    set difa [expr {[histinfo $hst difa]/1000.}]
3342    set zero [expr {[histinfo $hst zero]/1000.}]
3343    set ans {}
3344    foreach tof $toflist {
3345        if {$tof == 0.} {
3346            lappend ans 0.
3347        } elseif {$tof == 1000.} {
3348            lappend ans 1000.
3349        } else {
3350            set td [expr {$tof-$zero}]
3351            lappend ans [expr {$td*($difc2+$difa*$td)/ \
3352                    ($difc2*$difc+2.0*$difa*$td)}]
3353        }
3354    }
3355    return $ans
3356}
3357
3358# convert two-theta to d-space
3359proc tttod {twotheta hst} {
3360    set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3361    set zero [expr [histinfo $hst zero]/100.]
3362    set ans {}
3363    set cnv [expr {acos(0.)/180.}]
3364    foreach tt $twotheta {
3365        if {$tt == 0.} {
3366            lappend ans 99999.
3367        } elseif {$tt == 1000.} {
3368            lappend ans 0.
3369        } else {
3370            lappend ans [expr {$lamo2 / sin($cnv*($tt-$zero))}]
3371        }
3372    }
3373    return $ans
3374}
3375
3376# convert energy (edx-ray) to d-space
3377# (note that this ignores the zero correction)
3378proc engtod {eng hst} {
3379    set lam [histinfo $hst lam1]
3380    set zero [histinfo $hst zero]
3381    set ans {}
3382    set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3383    foreach e $eng {
3384        if {$e == 0.} {
3385            lappend ans 1000.
3386        } elseif {$e == 1000.} {
3387            lappend ans 0.
3388        } else {
3389            lappend ans [expr {$v/$e}]
3390        }
3391    }
3392    return $ans
3393}
3394
3395# convert x values to Q
3396proc toQ {xlist hst} {
3397    global expmap
3398    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3399        return [toftoQ $xlist $hst]
3400    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3401        return [tttoQ $xlist $hst]
3402    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3403        return [engtoQ $xlist $hst]
3404    } else {
3405        return {}
3406    }
3407}
3408# convert tof to Q
3409proc toftoQ {toflist hst} {
3410    set difc [expr {[histinfo $hst difc]/1000.}]
3411    set difc2 [expr {$difc*$difc}]
3412    set difa [expr {[histinfo $hst difa]/1000.}]
3413    set zero [expr {[histinfo $hst zero]/1000.}]
3414    set 2pi [expr {4.*acos(0.)}]
3415    set ans {}
3416    foreach tof $toflist {
3417        if {$tof == 0.} {
3418            lappend ans 99999.
3419        } elseif {$tof == 1000.} {
3420            lappend ans 0.
3421        } else {
3422            set td [expr {$tof-$zero}]
3423            lappend ans [expr {$2pi * \
3424                    ($difc2*$difc+2.0*$difa*$td)/($td*($difc2+$difa*$td))}]
3425        }
3426    }
3427    return $ans
3428}
3429
3430# convert two-theta to Q
3431proc tttoQ {twotheta hst} {
3432    set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3433    set zero [expr [histinfo $hst zero]/100.]
3434    set ans {}
3435    set cnv [expr {acos(0.)/180.}]
3436    set 2pi [expr {4.*acos(0.)}]
3437    foreach tt $twotheta {
3438        if {$tt == 0.} {
3439            lappend ans 0.
3440        } elseif {$tt == 1000.} {
3441            lappend ans 1000.
3442        } else {
3443            lappend ans [expr {$2pi * sin($cnv*($tt-$zero)) / $lamo2}]
3444        }
3445    }
3446    return $ans
3447}
3448# convert energy (edx-ray) to Q
3449# (note that this ignores the zero correction)
3450proc engtoQ {eng hst} {
3451    set lam [histinfo $hst lam1]
3452    set zero [histinfo $hst zero]
3453    set ans {}
3454    set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3455    set 2pi [expr {4.*acos(0.)}]
3456    foreach e $eng {
3457        if {$e == 0.} {
3458            lappend ans 0.
3459        } elseif {$e == 1000.} {
3460            lappend ans 1000.
3461        } else {
3462            lappend ans [expr {$2pi * $e / $v}]
3463        }
3464    }
3465    return $ans
3466}
3467proc sind {angle} {
3468    return [expr {sin($angle*acos(0.)/90.)}]
3469}
3470
3471# convert d-space values to 2theta, TOF or KeV
3472proc fromd {dlist hst} {
3473    global expmap
3474    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3475        set difc [expr {[histinfo $hst difc]/1000.}]
3476        set difa [expr {[histinfo $hst difa]/1000.}]
3477        set zero [expr {[histinfo $hst zero]/1000.}]
3478        set ans {}
3479        foreach d $dlist {
3480            if {$d == 0.} {
3481                lappend ans 0.
3482            } elseif {$d == 1000.} {
3483                lappend ans 1000.
3484            } else {
3485                lappend ans [expr {$difc*$d + $difa*$d*$d + $zero}]
3486            }
3487        }
3488        return $ans
3489    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3490        set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3491        set zero [expr [histinfo $hst zero]/100.]
3492        set ans {}
3493        set cnv [expr {180./acos(0.)}]
3494        foreach d $dlist {
3495            if {$d == 99999.} {
3496                lappend ans 0
3497            } elseif {$d == 0.} {
3498                lappend ans 1000.
3499            } else {
3500                lappend ans [expr {$cnv*asin($lamo2/$d) + $zero}]
3501            }
3502        }
3503        return $ans
3504    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3505        set lam [histinfo $hst lam1]
3506        set zero [histinfo $hst zero]
3507        set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3508        set ans {}
3509        foreach d $dlist {
3510            if {$d == 1000.} {
3511                lappend ans 0
3512            } elseif {$d == 0.} {
3513                lappend ans 1000.
3514            } else {
3515                lappend ans [expr {$v/$d}]
3516            }
3517        }
3518        return $ans
3519    } else {
3520        return {}
3521    }
3522}
3523
3524# convert Q values to 2theta, TOF or KeV
3525proc fromQ {Qlist hst} {
3526    global expmap
3527    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3528        set difc [expr {[histinfo $hst difc]/1000.}]
3529        set difa [expr {[histinfo $hst difa]/1000.}]
3530        set zero [expr {[histinfo $hst zero]/1000.}]
3531        set ans {}
3532        foreach Q $Qlist {
3533            if {$Q == 0.} {
3534                lappend ans 1000.
3535            } elseif {$Q == 99999.} {
3536                lappend ans 1000.
3537            } else {
3538                set d [expr {4.*acos(0.)/$Q}]
3539                lappend ans [expr {$difc*$d + $difa*$d*$d + $zero}]
3540            }
3541        }
3542        return $ans
3543    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3544        set lamo4pi [expr {[histinfo $hst lam1]/(8.*acos(0.))}]
3545        set zero [expr [histinfo $hst zero]/100.]
3546        set ans {}
3547        set cnv [expr {180./acos(0.)}]
3548        foreach Q $Qlist {
3549            if {$Q == 0.} {
3550                lappend ans 0
3551            } elseif {$Q == 1000.} {
3552                lappend ans 1000.
3553            } else {
3554                lappend ans [expr {$cnv*asin($Q*$lamo4pi) + $zero}]
3555            }
3556        }
3557        return $ans
3558    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3559        set lam [histinfo $hst lam1]
3560        set zero [histinfo $hst zero]
3561        set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3562        set ans {}
3563        set 2pi [expr {4.*acos(0.)}]
3564        foreach Q $Qlist {
3565            if {$Q == 1000.} {
3566                lappend ans 0
3567            } elseif {$Q == 0.} {
3568                lappend ans 1000.
3569            } else {
3570                lappend ans [expr {$Q * $v/$2pi}]
3571            }
3572        }
3573        return $ans
3574    } else {
3575        return {}
3576    }
3577}
3578#============================================================================
3579# rigid body EXP editing routines (to move into readexp.tcl)
3580# RigidBodyList -- returns a list of the defined rigid body types
3581# SetRigidBodyVar -- set variables and damping for rigid body type multipliers
3582# ReadRigidBody  -- # of times a body is mapped, scaling factors, var #s & coordinates
3583# RigidBodyMappingList - return a list instances where a RB is mapped in phase
3584# RigidBodyEnableTLS -- Enable or Disable TLS use for a rigid body mapping
3585# RigidBodySetTLS  -- change the TLS values for a rigid body mapping
3586# RigidBodySetDamp -- change the damping values for a rigid body mapping
3587# RigidBodyVary    -- set refinement variable numbers for a rigid body mapping
3588# RigidBodyTLSVary -- set TLS refinement variable nums for a rigid body mapping
3589# AddRigidBody -- defines a new rigid body type
3590# DeleteRigidBody -- remove a rigid body definition
3591# ReplaceRigidBody -- replaces a previous rigid body type
3592# ReadRigidBodyMapping  -- get parameters for a rigid body mapping
3593# MapRigidBody -- map a rigid body type into a phase
3594# EditRigidBodyMapping -- change the parameters in a rigid body mapping
3595# UnMapRigidBody --remove a rigid body constraint by removing a RB "instance"
3596#----- note that these older routines should not be used ------
3597# RigidBodyCount -- returns the number of defined rigid bodies (body types)
3598#    use RigidBodyList instead
3599# RigidBodyMappingCount -- # of times a rigid body is mapped in phase
3600#    use RigidBodyMappingList instead
3601#============================================================================
3602# returns the number of defined rigid bodies
3603proc RigidBodyCount {} {
3604    set n [string trim [readexp "RGBD  NRBDS"]]
3605    if {$n == ""} {
3606        set n 0
3607    }
3608    return $n
3609}
3610
3611# returns a list of the defined rigid body types
3612proc RigidBodyList {} {
3613    set n [string trim [readexp "RGBD  NRBDS"]]
3614    if {$n == ""} {
3615        set n 0
3616    }
3617    set rblist {}
3618    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
3619        set value $rbnum
3620        validint value 2
3621        set key "RGBD${value}"
3622        if {[existsexp "$key NATR "]} {
3623            lappend rblist $rbnum
3624        }
3625        if {[llength $rblist] == $n} break
3626    }
3627    return $rblist
3628}
3629
3630# ReadRigidBody provides all information associated with a rigid body type
3631#  rbnum is the rigid body type number
3632# it returns two items:
3633#   the number of times the rigid body is mapped
3634#   a list containing an element for each scaling factor in rigid body #rbnum.
3635# in each element there are four items:
3636#    a multiplier value for the rigid body coordinates
3637#    a damping value (0-9) for the refinement of the multiplier
3638#    a variable number if the multiplier will be refined
3639#    a list of cartesian coordinates coordinates
3640# each cartesian coordinate contains 4 items: x,y,z and a label
3641#  note that the label is present only when the RB is created in EXPGUI and is
3642#  not used in GSAS.
3643proc ReadRigidBody {rbnum} {
3644    if {[lsearch [RigidBodyList] $rbnum] == -1} {
3645        return ""
3646    }
3647    set value $rbnum
3648    validint value 2
3649    set key "RGBD${value}"
3650    set n [string trim [string range [readexp "$key NATR"] 0 4]]
3651    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
3652    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
3653    set out {}
3654    for {set i 1} {$i <= $nmult} {incr i} {
3655        set line [readexp "${key}${i}PARM"]
3656        set mult [string trim [string range $line 0 9]]
3657        set var [string trim [string range $line 10 14]]
3658        set damp [string trim [string range $line 15 19]]
3659        set coordlist {}
3660        for {set j 1} {$j <= $n} {incr j} {
3661            set value $j
3662            validint value 3
3663            set line [readexp "${key}${i}SC$value"]
3664            set x [string trim [string range $line 0 9]]
3665            set y [string trim [string range $line 10 19]]
3666            set z [string trim [string range $line 20 29]]
3667            set lbl [string trim [string range $line 30 39]]
3668            lappend coordlist [list $x $y $z $lbl]
3669        }
3670        lappend out [list $mult $damp $var $coordlist]
3671    }
3672    return [list $used $out]
3673}
3674
3675# SetRigidBodyVar
3676#   rbnum is the rigid body type number
3677#   varnumlist is a list of variable numbers
3678#      note that if this list is shorter than the number of actual multipliers
3679#      for the body, the unspecified variable will not be changed
3680#   damplist   is a list of damping values (0-9)
3681#      note that if the damplist is shorter than the number of actual multipliers
3682#      the unspecified values are not changed
3683#  SetRigidBodVar 2 {1 2 3} {}
3684#       will vary the (first 3) translations in body #3 and will not change the
3685#       damping values
3686#  SetRigidBodVar 3 {} {0 0 0}
3687#       will not change variable settings but will change the (first 3) damping values
3688#  SetRigidBodVar 4 {11 11} {8 8}
3689#      changes both variable numbers and damping at the same time
3690# Nothing is returned
3691proc SetRigidBodyVar {rbnum varnumlist damplist} {
3692    if {[lsearch [RigidBodyList] $rbnum] == -1} {
3693        return ""
3694    }
3695    set value $rbnum
3696    validint value 2
3697    set key "RGBD${value}"
3698    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
3699    for {set i 1} {$i <= $nmult} {incr i} {
3700        set j $i
3701        incr j -1
3702        set var [lindex $varnumlist $j]
3703        if {$var != ""} {
3704            validint var 5
3705            setexp "${key}${i}PARM" $var 11 15
3706        }
3707        set damp [lindex $damplist $j]
3708        if {$damp != ""} {
3709            if {$damp > 9} {set damp 9}
3710            if {$damp < 0} {set damp 0}
3711            validint damp 5
3712        }
3713        setexp "${key}${i}PARM" $damp 16 20
3714    }
3715}
3716
3717
3718# return the number of times rigid body $bodytyp is mapped in phase $phase
3719proc RigidBodyMappingCount {phase bodytyp} {
3720    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
3721    if {! [existsexp "$key  NBDS"]} {return 0}
3722    set n [string trim [readexp "$key  NBDS"]]
3723    if {$n == ""} {
3724        set n 0
3725    }
3726    return $n
3727}
3728# return a list of the instances where rigid body $bodytyp is mapped in phase $phase
3729proc RigidBodyMappingList {phase bodytyp} {
3730    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
3731    if {! [existsexp "$key  NBDS"]} {return {}}
3732    set n [string trim [readexp "$key  NBDS"]]
3733    if {$n == ""} {
3734        set n 0
3735    }
3736    set rblist {}
3737    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
3738        set value $rbnum
3739        validint value 2
3740        set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
3741        if {[existsexp "$key  NDA"]} {
3742            lappend rblist $rbnum
3743        }
3744        if {[llength $rblist] == $n} break
3745    }
3746    return $rblist
3747}
3748
3749
3750
3751# reads rigid body mapping parameters for phase ($phase), body type # ($bodytyp) and instance # ($num)
3752# returns a list of items (most lists) as follows:
3753#   1) sequence # of first atom in body
3754#   2) origin of body in fractional coordinates (3 elements)
3755#   3) Euler angles as 6 pairs of numbers (see below)
3756#   4) variable numbers for the 9 position variables (origin followed by rotations)
3757#   5) damping vals for the 9 position variables (origin followed by rotations)
3758#   6) the TLS values, in order below (empty list if TLS is not in use)
3759#   7) the variable numbers for each TLS values, in order below (or empty)
3760#   8) three damping values for the T, L and S terms.
3761# returns an empty list if no such body exists.
3762#
3763# Euler angles are a list of axes and angles to rotate:
3764#   { {axis1 angle1} {axis2 angle2} ...}
3765# where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
3766#
3767# The 20 TLS terms are ordered:
3768#    T11, T22, T33, T12, T13, T23
3769#    L11, L22, L33, L12, L13, L23
3770#    S12, S13, S21, S23, S31, S32, SAA, SBB
3771#
3772proc ReadRigidBodyMapping {phase bodytyp num} {
3773    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3774        return ""
3775    }
3776    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3777    set first [string trim [string range [readexp "$key  NDA"] 0 4]]
3778    set line [readexp "$key BDFL"]
3779    set varlist {}
3780    set damplist {}
3781    foreach i {0 1 2 3 4 5 6 7 8} {
3782        lappend varlist [string trim [string range $line [expr {5*$i}] [expr {4 + 5*$i}] ]]
3783        lappend damplist [string trim [string range $line [expr {45 + $i}] [expr {45 + $i}] ]]
3784    }
3785    set TLSdamplist {}
3786    foreach i {54 55 56} {
3787        lappend TLSdamplist [string trim [string range $line $i $i ]]
3788    }
3789    set line [readexp "${key} BDLC"]
3790    set x [string trim [string range $line 0 9]]
3791    set y [string trim [string range $line 10 19]]
3792    set z [string trim [string range $line 20 29]]
3793    set origin [list $x $y $z]
3794    set line [readexp "${key} BDOR"]
3795    set rotations {}
3796    foreach i {0 10 20 30 40 50} {
3797        set angle [string trim [string range $line $i [expr {$i+7}]]]
3798        set axis [string trim [string range $line [expr {$i+8}] [expr {$i+9}]]]
3799        lappend rotations [list $angle $axis]
3800    }
3801    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
3802    set tlsvars {}
3803    set tlsvals {}
3804    if {$TLS != 0} {
3805        set line [readexp "${key}TLSF1"]
3806        for {set j 0} {$j < 20} {incr j} {
3807            set var [string trim [string range $line [expr {3*$j}] [expr {3*$j+2}]]]
3808            if {$var == ""} {set var 0}
3809            lappend tlsvars $var
3810        }
3811        for {set j 0} {$j < 20} {incr j} {
3812            set i 0
3813            if {$j == 0} {
3814                set i 1
3815            } elseif {$j == 8} {
3816                set i 2
3817            } elseif {$j == 16} {
3818                set i 3
3819            }
3820            if {$i != 0} {
3821                set line [readexp "${key}TLSP$i"]
3822                set i 0
3823                set j1 0
3824                set j2 7
3825            } else {
3826                incr j1 8
3827                incr j2 8
3828            }
3829            set val [string trim [string range $line $j1 $j2]]
3830            if {$val == ""} {set val 0}
3831            lappend tlsvals $val
3832        }
3833    }
3834    return [list $first $origin $rotations $varlist $damplist $tlsvals $tlsvars $TLSdamplist]
3835}
3836
3837# Control TLS representation for phase, body # and instance number of a Rigid body mapping
3838#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
3839# Enable TLS use if TLS is non-zero (true). Disable if zero
3840proc RigidBodyEnableTLS {phase bodytyp num TLS} {
3841    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3842        return ""
3843    }
3844    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3845    if {$TLS} {
3846        setexp "${key} LSTF" [format "%5d" 1] 1 5
3847        if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
3848        if {![existsexp "${key}TLSP1"]} {
3849            makeexprec "${key}TLSP1"
3850            set str {}
3851            foreach v {.01 .01 .01 0 0 0 0 0} d {4 4 4 4 4 4 2 2} {
3852                validreal v 8 $d
3853                append str $v
3854            }
3855            setexp "${key}TLSP1" $str 1 64
3856        }
3857        if {![existsexp "${key}TLSP2"]} {
3858            makeexprec "${key}TLSP2"
3859            set str {}
3860            set v 0
3861            foreach d {2 2 2 2 4 4 4 4} {
3862                validreal v 8 $d
3863                append str $v
3864            }
3865            setexp "${key}TLSP2" $str 1 64
3866        }
3867        if {![existsexp "${key}TLSP3"]} {
3868            makeexprec "${key}TLSP3"
3869            set str {}
3870            set v 0
3871            foreach d {4 4 4 4} {
3872                validreal v 8 $d
3873                append str $v
3874            }
3875            setexp "${key}TLSP3" $str 1 64
3876        }
3877    } else {
3878        setexp "${key} LSTF" [format "%5d" 0] 1 5
3879    }
3880    return 1
3881}
3882
3883# Control the TLS values for Rigid body mapping for mapping with
3884#    phase ($phase), body type # ($bodytyp) and instance # ($num)
3885# set the 20 TLS values to the values in TLSvals
3886# There must be exactly 20 TLS terms, which are ordered:
3887#    T11, T22, T33, T12, T13, T23
3888#    L11, L22, L33, L12, L13, L23
3889#    S12, S13, S21, S23, S31, S32, SAA, SBB
3890proc RigidBodySetTLS {phase bodytyp num TLSvals} {
3891    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3892        return ""
3893    }
3894    if {[llength $TLSvals] != 20} {return ""}
3895    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3896    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
3897    if {$TLS == 0} {return ""}
3898    if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
3899    foreach n {1 2 3} {
3900        if {![existsexp "${key}TLSP$n"]} {makeexprec "${key}TLSP$n"}
3901    }
3902    set str {}
3903    set n 1
3904    set i 0
3905    foreach v $TLSvals d {4 4 4 4 4 4 2 2 2 2 2 2 4 4 4 4 4 4 4 4} {
3906        incr i
3907        validreal v 8 $d
3908        append str $v
3909        if {$i == 8} {
3910            set i 0
3911            setexp "${key}TLSP$n" $str 1 64
3912            incr n
3913            set str {}
3914        }
3915    }
3916    setexp "${key}TLSP$n" $str 1 64
3917    return 1
3918}
3919
3920# set damping values for a Rigid body mapping
3921#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
3922# there must be 9 damping values in RBdamp for the 9 position variables (origin followed by rotations)
3923# Use of TLSdamp is optional, but to be used, TLS representation must be enabled and there must be
3924# three damping terms (for all T terms; for all L terms and for all S terms)
3925proc RigidBodySetDamp {phase bodytyp num RBdamp "TLSdamp {}"} {
3926    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3927        return ""
3928    }
3929    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3930    if {[llength $RBdamp] != 9} {return ""}
3931    set str {}
3932    foreach v $RBdamp {
3933        if {[validint v 1] != 1} {set v " "}
3934        append str $v
3935    }
3936    setexp "$key BDFL" $str 46 9
3937    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
3938    if {$TLS != 0 &&  [llength $TLSdamp] == 3} {
3939        set str {}
3940        foreach v $TLSdamp {
3941        if {[validint v 1] != 1} {set v " "}
3942            append str $v
3943        }
3944        setexp "$key BDFL" $str 55 3
3945    }
3946    return 1
3947}
3948
3949# set refinement variable numbers for a Rigid body mapping
3950#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
3951# there must be 9 variable values in RBvar for the 9 position variables (origin followed by rotations)
3952# note that the variable values should be unique integers
3953proc RigidBodyVary {phase bodytyp num RBvar} {
3954    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3955        return ""
3956    }
3957    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3958    if {[llength $RBvar] != 9} {return ""}
3959    set str {}
3960    foreach v $RBvar {
3961        if {[validint v 5] != 1} {set v " "}
3962        append str $v
3963    }
3964    setexp "$key BDFL" $str 1 45   
3965}
3966
3967# set TLS refinement variable numbers for a Rigid body mapping
3968#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
3969# there must be 20 variable values in TLSvar for the 20 parameters:
3970#    T11, T22, T33, T12, T13, T23
3971#    L11, L22, L33, L12, L13, L23
3972#    S12, S13, S21, S23, S31, S32, SAA, SBB
3973# note that the variable values should be unique integers
3974proc RigidBodyTLSVary {phase bodytyp num TLSvar} {
3975    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
3976        return ""
3977    }
3978    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
3979    if {[llength $TLSvar] != 20} {return ""}
3980    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
3981    if {$TLS == 0} {return ""}
3982    set str {}
3983    foreach v $TLSvar {
3984        if {[validint v 3] != 1} {set v " "}
3985        append str $v
3986    }
3987    setexp "${key}TLSF1" $str 1 60
3988
3989# AddRigidBody: add a new rigid body definition into the .EXP file
3990# arguments are:
3991#   multlist: defines a list of multipliers for each set of coordinates. In the
3992#             simplest case this will be {1}
3993#   coordlist: a nested list of coordinates such as { { {0 0 0} {.1 .1 .1} {.2 .2 .2} } }
3994# note that when the length of multlist > 1 then coordlist must have the same length.
3995# for input where
3996#     multlist = {s1 s2} and
3997#     coordlist = { { {0 0 0} {1 1 0} {.0 .0 .0} ...}
3998#                     {0 0 0} {1 1 0} {2 1 2} ...}
3999#                 }
4000# the cartesian coordinates are defined from the input as
4001#    atom 1 = s1 * (0,0,0) + s2*(0,0,0) [ = (0,0,0)]
4002#    atom 2 = s1 * (1,1,0) + s2*(1,1,0) [ = (s1+s2) * (1,1,0)]
4003#    atom 3 = s1 * (0,0,0) + s2*(2,1,2) [ = s2 * (2,1,2)]
4004#    ...
4005# Returns the number of the rigid body that has been created
4006proc AddRigidBody {multlist coordlist} {
4007    # find the first unused body #
4008    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
4009        set value $rbnum
4010        validint value 2
4011        set key "RGBD${value}"
4012        if {! [existsexp "$key NATR "]} {break}
4013    }
4014    # did we go too far?
4015    if {$rbnum == 16} {return ""}
4016    # increment the RB counter
4017    set n [string trim [readexp "RGBD  NRBDS"]]
4018    if {$n == ""} {
4019        makeexprec "RGBD  NRBDS"
4020        set n 0
4021    }
4022    incr n
4023    validint n 5
4024    setexp "RGBD  NRBDS" $n 1 5
4025    SetRigidBody $rbnum $multlist $coordlist
4026    return $rbnum
4027}
4028
4029# DeleteRigidBody: remove a rigid body definition from the .EXP file
4030# The body may not be mapped. I am not sure if GSAS allows more than 9 bodies,
4031# but if it does, the simplifed approach used here will fail, so this
4032# is not allowed.
4033# Input:
4034#   Rigid body number
4035# Returns:
4036#   1 on success
4037#   -1 if the body number is 11 or greater
4038#   -2 if the body is mapped
4039#   -3 if the body is not defined
4040proc DeleteRigidBody {rbnum} {
4041    # can't delete bodies with numbers higher than 10, since the key prefix
4042    # (RGBD11... will overlap with rigid body instance records, which would be
4043    # deleted below
4044    if {$rbnum > 10} {
4045        return -1
4046    }
4047    set value $rbnum
4048    validint value 2
4049    set key "RGBD${value}"
4050    if {![existsexp "$key NATR "]} {
4051        return -2
4052    }
4053    # make sure the body is not mapped
4054    if {[string trim [string range [readexp "$key NBDS"] 0 4]] != 0} {
4055        return -3
4056    }
4057    # delete the records starting with "RGBD x" or "RGBD10"
4058    foreach key [array names ::exparray "${key}*"] {
4059        #puts $key
4060        delexp $key
4061    }
4062    # decrement the RB counter
4063    set n [string trim [readexp "RGBD  NRBDS"]]
4064    if {$n == ""} {
4065        set n 0
4066    }
4067    incr n -1
4068    validint n 5
4069    if {$n > 0} {
4070        setexp "RGBD  NRBDS" $n 1 5
4071    } else {
4072        delexp "RGBD  NRBDS"
4073    }
4074    return 1
4075}
4076
4077# ReplaceRigidBody: replace all the information for rigid body #rbnum
4078# Works the sames as AddRigidBody (see above) except that the rigid body is replaced rather
4079# than added.
4080# Note that count of the # of times the body is used is preserved
4081proc ReplaceRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
4082    set value $rbnum
4083    validint value 2
4084    set key "RGBD${value}"
4085    set line [readexp "$key NBDS"]
4086    foreach key [array names ::exparray "${key}*"] {
4087        #puts $key
4088        delexp $key
4089    }
4090    SetRigidBody $rbnum $multlist $coordlist $varlist $damplist
4091    setexp "$key NBDS" $line 1 68
4092}
4093
4094# Edit the parameters for rigid body #rbnum
4095# (normally called from ReplaceRigidBody or AddRigidBody)
4096proc SetRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
4097    set value $rbnum
4098    validint value 2
4099    set key "RGBD${value}"
4100    # number of atoms
4101    set value [llength [lindex $coordlist 0]]
4102    validint value 5
4103    makeexprec "$key NATR"
4104    setexp "$key NATR" $value 1 5
4105    # number of times used
4106    set value 0
4107    validint value 5
4108    makeexprec "$key NBDS"
4109    setexp "$key NBDS" $value 1 5
4110    # number of coordinate matrices
4111    set value [llength $multlist]
4112    validint value 5
4113    makeexprec "$key NSMP"
4114    setexp "$key NSMP" $value 1 5
4115    set i 0
4116    foreach mult $multlist coords $coordlist {
4117        set var [lindex $varlist $i]
4118        if {$var == ""} {set var 0}
4119        set damp [lindex $damplist $i]
4120        if {$damp == ""} {set damp 0}
4121        incr i
4122        makeexprec "${key}${i}PARM"
4123        setexp "${key}${i}PARM" [format "%10.5f%5d%5d" $mult $var $damp] 1 20
4124        set j 0
4125        foreach item $coords {
4126            #puts $item
4127            incr j
4128            set value $j
4129            validint value 3
4130            makeexprec "${key}${i}SC$value"
4131            if {[llength $item] == 4} {
4132                setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f%10s" $item] 1 40
4133            } elseif {[llength $item] == 3} {
4134                setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f" $item] 1 30
4135            } else {
4136                return -code 3 "Invalid number of coordinates"
4137            }
4138        }
4139    }
4140}
4141
4142# convert a decimal to the GSAS hex encoding with a field $digits long.
4143proc ToHex {num digits} {
4144    return [string toupper [format "%${digits}x" $num]]
4145}
4146
4147# convert a GSAS hex encoding to a decimal integer
4148proc FromHex {hex} {
4149    return [scan $hex "%x"]
4150}
4151
4152# MapRigidBody: define an "instance" of a rigid body: meaning that the coordinates
4153# (and optionally U values) for a set of atoms will be generated from the rigid body
4154# arguments:
4155#   phase: phase number (1-9)
4156#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4157#   firstatom: sequence number of the first atom in phase (note that atoms may
4158#              not be numbered sequentially)
4159#   position: list of three fractional coordinates for the origin of the rigid body coordinates
4160#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the
4161#           cartesian system before the body is translated to position.
4162# returns the instance # (number of times body $bodytyp has been used in phase $phase)
4163proc MapRigidBody {phase bodytyp firstatom position angles} {
4164    # find the first unused body # for this phase & type
4165    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
4166        set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
4167        if {! [existsexp "$key  NDA"]} {break}
4168    }
4169    # did we go too far?
4170    if {$rbnum == 16} {return ""}
4171    # increment number of mapped bodies of this type overall
4172    set value $bodytyp
4173    validint value 2
4174    set key "RGBD${value}"
4175    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
4176    incr used
4177    set value $used
4178    validint value 5
4179    setexp "$key NBDS" $value 1 5
4180    # increment number of mapped bodies of this type in this phase
4181    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
4182    if {[existsexp "$key  NBDS"]} {
4183        set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
4184    } else {
4185        makeexprec "$key  NBDS"
4186        set used 0
4187    }
4188    incr used
4189    set value $used
4190    validint value 5
4191    setexp "$key  NBDS" $value 1 5
4192    # now write the mapping parameters
4193    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
4194    set value $firstatom
4195    validint value 5
4196    makeexprec "$key  NDA"
4197    setexp "$key  NDA" $value 1 5
4198    set l1 {}
4199    set l2 {}
4200    for {set i 0} {$i < 9} {incr i} {
4201        append l1 [format %5d 0]
4202        append l2 [format %1d 0]
4203    }
4204    makeexprec "$key BDFL"
4205    setexp "$key BDFL" $l1$l2 1 54
4206    makeexprec "${key} BDLC"
4207    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
4208    makeexprec "${key} BDOR"
4209    set l1 {}
4210    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
4211        append l1 [format "%8.2f%2d" $val $dir]
4212    }
4213    setexp "${key} BDOR" $l1 1 60
4214    makeexprec "${key} LSTF"
4215    setexp "${key} LSTF" [format "%5d" 0] 1 5
4216    # turn off the X refinement flags for the new body
4217    set st [lsearch $::expmap(atomlist_$phase) $firstatom]
4218    set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodytyp] 1] 0] 3]]
4219    set en [expr {$st+$natoms-1}]
4220    set atomlist [lrange $::expmap(atomlist_$phase) $st $en]
4221    atominfo $phase $atomlist xref set 0
4222    # redo the mapping to capture the newly mapped atoms
4223    mapexp
4224    return $rbnum
4225}
4226
4227# EditRigidBodyMapping: edit parameters that define an "instance" of a rigid body (see MapRigidBody)
4228# arguments:
4229#   phase: phase number (1-9)
4230#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4231#   bodynum: instance number, as returned by MapRigidBody
4232#   position: list of three fractional coordinates for the origin of the rigid body coordinates
4233#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the
4234#           cartesian system before the body is translated to position.
4235#
4236proc EditRigidBodyMapping {phase bodytyp bodynum position angles} {
4237    # number of bodies of this type in this phase
4238    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $bodynum 1]"
4239    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
4240    set l1 {}
4241    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
4242        append l1 [format "%8.2f%2d" $val $dir]
4243    }
4244    setexp "${key} BDOR" $l1 1 60
4245}
4246
4247# UnMapRigidBody: remove a rigid body constraint by removing a RB "instance"
4248# (undoes MapRigidBody)
4249# arguments:
4250#   phase: phase number (1-9)
4251#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4252#   bodynum: instance number, as returned by MapRigidBody
4253proc UnMapRigidBody {phase bodytyp mapnum} {
4254    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $mapnum] == -1} {
4255        return ""
4256    }
4257    # decrement number of mapped bodies of this type overall
4258    set value $bodytyp
4259    validint value 2
4260    set key "RGBD${value}"
4261    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
4262    incr used -1
4263    set value $used
4264    validint value 5
4265    setexp "$key NBDS" $value 1 5
4266    # decrement number of mapped bodies of this type in this phase
4267    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
4268    if {[existsexp "$key  NBDS"]} {
4269        set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
4270    } else {
4271        set used 0
4272    }
4273    incr used -1
4274    set value $used
4275    validint value 5
4276    if {$used > 0} {
4277        setexp "$key  NBDS" $value 1 5
4278    } else {
4279        delexp "$key  NBDS"
4280    }
4281    # now delete the mapping parameter records
4282    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $mapnum 1]"
4283    foreach key [array names ::exparray "${key}*"] {
4284        delexp $key
4285    }
4286    return $used
4287}
4288
Note: See TracBrowser for help on using the repository browser.