source: branches/sandbox/readexp.tcl @ 1209

Last change on this file since 1209 was 1209, checked in by toby, 13 years ago

start on Fourier calc and absorption constraints

  • Property svn:keywords set to Author Date Revision Id
File size: 136.4 KB
Line 
1# $Id: readexp.tcl 1209 2012-08-15 19:27:31Z toby $
2# Routines to deal with the .EXP "data structure"
3set expmap(Revision) {$Revision: 1209 $ $Date: 2012-08-15 19:27:31 +0000 (Wed, 15 Aug 2012) $}
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 for a phase
2246proc atom_constraint_read {phase} {
2247    set fixlist ""
2248    foreach k {1 2 3 4 5 6 7 8 9} {
2249        set key [format "LEQV HOLD%1d%2d" $phase $k]
2250        set line [readexp $key]
2251        foreach j {2 10 18 26 34 42 50 58} {
2252            set fix_param [string range $line $j [expr $j+7]]
2253            if {[string trim $fix_param] == ""} {return $fixlist}
2254            lappend fixlist $fix_param
2255        }
2256    }
2257    return $fixlist
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
2273# returns 1 if the specified variable is fixed
2274proc atom_constraint_get {phase atom type} {
2275    if {[array names ::fix_param "$phase,$atom,$type"] == ""} {
2276        return 0
2277    }
2278    return 1
2279}
2280
2281proc atom_constraint_set {phase atomlist type mode} {
2282    foreach atom $atomlist {
2283        set key "$phase,$atom,$type"
2284        if {$mode} {
2285            set ::fix_param($key) 1
2286        } else {
2287            array unset ::fix_param $key
2288        }
2289    } 
2290    set fixlist {}
2291    foreach key [array names ::fix_param "$phase,*"] {
2292        foreach {j atom parm} [split $key ","] {}
2293        lappend fixlist \
2294            [format "%1s %+2s%-4s" $phase $atom $parm]
2295    }
2296    foreach key [array names ::exparray "LEQV HOLD$phase*"] {
2297        delexp $key
2298    }
2299    set k 0
2300    set j 1
2301    set line ""
2302    foreach fix $fixlist {
2303        incr k
2304        append line $fix
2305        if {$k == 8} {
2306            set key [format "LEQV HOLD%1d%2d" $phase $j]
2307            makeexprec $key
2308            setexp $key $line 3 [expr ($k * 8) + 2]
2309            set k 0
2310            incr j
2311            set line ""
2312        }
2313    }
2314    if {$line != ""} {
2315        set key [format "LEQV HOLD%1d%2d" $phase $j]
2316        makeexprec $key
2317        setexp $key $line 3 [expr ($k * 8) + 2]
2318    }   
2319}
2320
2321
2322#  get a logical constraint
2323#
2324#  type action
2325#  -----------
2326#  atom get  number        returns a list of constraints.
2327#   "   set  number value  replaces a list of constraints
2328#                          (value is a list of constraints)
2329#   "   add  number value  inserts a new list of constraints
2330#                          (number is ignored)
2331#   "   delete number      deletes a set of constraint entries
2332# Each item in the list of constraints is composed of 4 items:
2333#              phase, atom, variable, multiplier
2334# If variable=UISO atom can be ALL, otherwise atom is a number
2335# legal variable names: FRAC, X, Y, Z, UISO, U11, U22, U33, U12, U23, U13,
2336#                       MX, MY, MZ
2337#
2338#  type action
2339#  -----------
2340#  profileXX get number         returns a list of constraints for term XX=1-36
2341#                               use number=0 to get # of defined
2342#                                  constraints for term XX
2343#   "        set number value   replaces a list of constraints
2344#                               (value is a list of constraints)
2345#   "        add number value   inserts a new list of constraints
2346#                               (number is ignored)
2347#   "        delete number      deletes a set of constraint entries
2348# Each item in the list of constraints is composed of 3 items:
2349#              phase-list, histogram-list, multiplier
2350# Note that phase-list and/or histogram-list can be ALL
2351#
2352#  type action
2353#  -----------
2354#  absorbX get number         returns a list of constraints for term X=1 or 2
2355#                             use number=0 to get # of defined
2356#                             constraints for term X
2357#   "        set number value   replaces a list of constraints
2358#                               (value is a list of constraints)
2359#   "        add number value   inserts a new list of constraints
2360#                               (number is ignored)
2361#   "        delete number      deletes a set of constraint entries
2362# Each item in the list of constraints is composed of 3 items:
2363#              phase-list, histogram-list, multiplier
2364# Note that phase-list and/or histogram-list can be ALL
2365
2366
2367proc constrinfo {type action number "value {}"} {
2368    global expmap
2369    if {[lindex $expmap(phasetype) 0] == 4} {
2370        set mm 1
2371    } else {
2372        set mm 0
2373    }
2374    switch -glob ${type}-$action {
2375        atom-get {
2376            # does this constraint exist?
2377            set key [format "LNCN%4d%4d" $number 1]
2378            if {![existsexp $key]} {return -1}
2379            set clist {}
2380            for {set i 1} {$i < 999} {incr i} {
2381                set key [format "LNCN%4d%4d" $number $i]
2382                if {![existsexp $key]} break
2383                set line [readexp $key]
2384                set j1 2
2385                set j2 17
2386                set seg [string range $line $j1 $j2]
2387                while {[string trim $seg] != ""} {
2388                    set p [string range $seg 0 0]
2389                    if {$p == 1 && $mm} {
2390                        set atom [string trim [string range $seg 1 4]]
2391                        set var [string trim [string range $seg 5 7]]
2392                        if {$atom == "ALL"} {
2393                            set var UIS
2394                        } else {
2395                            scan $atom %x atom
2396                        }
2397                        lappend clist [list $p $atom $var \
2398                                [string trim [string range $seg 8 end]]]
2399                    } else {
2400                        lappend clist [list $p \
2401                                [string trim [string range $seg 1 3]] \
2402                                [string trim [string range $seg 4 7]] \
2403                                [string trim [string range $seg 8 end]]]
2404                    }
2405                    incr j1 16
2406                    incr j2 16
2407                    set seg [string range $line $j1 $j2]
2408                }
2409            }
2410            return $clist
2411        }
2412        atom-set {
2413            # delete records for current constraint
2414            for {set i 1} {$i < 999} {incr i} {
2415                set key [format "LNCN%4d%4d" $number $i]
2416                if {![existsexp $key]} break
2417                delexp $key
2418            }
2419            set line {}
2420            set i 1
2421            foreach tuple $value {
2422                set p [lindex $tuple 0]
2423                if {$p == 1 && $mm && \
2424                        [string toupper [lindex $tuple 1]] == "ALL"} {
2425                    set seg [format %1dALL UIS%8.4f \
2426                            [lindex $tuple 0] \
2427                            [lindex $tuple 3]]
2428                } elseif {$p == 1 && $mm} {
2429                    set seg [eval format %1d%.4X%-3s%8.4f $tuple]
2430                } elseif {[string toupper [lindex $tuple 1]] == "ALL"} {
2431                    set seg [format %1dALL%-4s%8.4f \
2432                            [lindex $tuple 0] \
2433                            [lindex $tuple 2] \
2434                            [lindex $tuple 3]]
2435                } else {
2436                    set seg [eval format %1d%3d%-4s%8.4f $tuple]
2437                }
2438                append line $seg
2439                if {[string length $line] > 50} {
2440                    set key  [format "LNCN%4d%4d" $number $i]
2441                    makeexprec $key
2442                    setexp $key $line 3 68
2443                    set line {}
2444                    incr i
2445                }
2446            }
2447            if {$line != ""} {
2448                set key  [format "LNCN%4d%4d" $number $i]
2449                makeexprec $key
2450                setexp $key $line 3 68
2451            }
2452            return
2453        }
2454        atom-add {
2455            # loop over defined constraints
2456            for {set j 1} {$j < 9999} {incr j} {
2457                set key [format "LNCN%4d%4d" $j 1]
2458                if {![existsexp $key]} break
2459            }
2460            set number $j
2461            # save the constraint
2462            set line {}
2463            set i 1
2464            foreach tuple $value {
2465                set p [lindex $tuple 0]
2466                if {$p == 1 && $mm && \
2467                        [string toupper [lindex $tuple 1]] == "ALL"} {
2468                    set seg [format %1dALL UIS%8.4f \
2469                            [lindex $tuple 0] \
2470                            [lindex $tuple 3]]
2471                } elseif {$p == 1 && $mm} {
2472                    set seg [eval format %1d%.4X%-3s%8.4f $tuple]
2473                } elseif {[string toupper [lindex $tuple 1]] == "ALL"} {
2474                    set seg [format %1dALL%-4s%8.4f \
2475                            [lindex $tuple 0] \
2476                            [lindex $tuple 2] \
2477                            [lindex $tuple 3]]
2478                } else {
2479                    set seg [eval format %1d%3d%-4s%8.4f $tuple]
2480                }
2481                append line $seg
2482                if {[string length $line] > 50} {
2483                    set key  [format "LNCN%4d%4d" $number $i]
2484                    makeexprec $key
2485                    setexp $key $line 3 68
2486                    set line {}
2487                    incr i
2488                }
2489            }
2490            if {$line != ""} {
2491                set key  [format "LNCN%4d%4d" $number $i]
2492                makeexprec $key
2493                setexp $key $line 3 68
2494            }
2495            return
2496        }
2497        atom-delete {
2498            for {set j $number} {$j < 9999} {incr j} {
2499                # delete records for current constraint
2500                for {set i 1} {$i < 999} {incr i} {
2501                    set key [format "LNCN%4d%4d" $j $i]
2502                    if {![existsexp $key]} break
2503                    delexp $key
2504                }
2505                # now copy records, from the next entry, if any
2506                set j1 $j
2507                incr j1
2508                set key1 [format "LNCN%4d%4d" $j1 1]
2509                # if there is no record, there is nothing to copy -- done
2510                if {![existsexp $key1]} return
2511                for {set i 1} {$i < 999} {incr i} {
2512                    set key1 [format "LNCN%4d%4d" $j1 $i]
2513                    if {![existsexp $key1]} break
2514                    set key  [format "LNCN%4d%4d" $j  $i]
2515                    makeexprec $key
2516                    setexp $key [readexp $key1] 1 68
2517                }
2518            }
2519        }
2520        profile*-delete {
2521            regsub profile $type {} term
2522            if {$term < 10} {
2523                set term " $term"
2524            }
2525            set key "LEQV PF$term   "
2526            # return nothing if no term exists
2527            if {![existsexp $key]} {return 0}
2528
2529            # number of constraint terms
2530            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2531            # don't delete a non-existing entry
2532            if {$number > $nterms} {return 0}
2533            set val [expr {$nterms - 1}]
2534            validint val 5
2535            setexp $key $val 1 5
2536            for {set i1 $number} {$i1 < $nterms} {incr i1} {
2537                set i2 [expr {1 + $i1}]
2538                # move the contents of constraint #i2 -> i1
2539                if {$i1 > 9} {
2540                    set k1 [expr {($i1+1)/10}]
2541                    set l1 $i1
2542                } else {
2543                    set k1 " "
2544                    set l1 " $i1"
2545                }
2546                set key1 "LEQV PF$term  $k1"
2547                # number of constraint lines for #i1
2548                set n1 [string trim [string range [readexp ${key1}] \
2549                        [expr {($i1%10)*5}] [expr {4+(($i1%10)*5)}]] ]
2550                if {$i2 > 9} {
2551                    set k2 [expr {($i2+1)/10}]
2552                    set l2 $i2
2553                } else {
2554                    set k2 " "
2555                    set l2 " $i2"
2556                }
2557                set key2 "LEQV PF$term  $k2"
2558                # number of constraint lines for #i2
2559                set n2 [string trim [string range [readexp ${key2}] \
2560                        [expr {($i2%10)*5}] [expr {4+(($i2%10)*5)}]] ]
2561                set val $n2
2562                validint val 5
2563                # move the # of terms
2564                setexp $key1 $val [expr {1+(($i1%10)*5)}] 5
2565                # move the terms
2566                for {set j 1} {$j <= $n2} {incr j 1} {
2567                    set key "LEQV PF${term}${l1}$j"
2568                    makeexprec $key
2569                    setexp $key [readexp "LEQV PF${term}${l2}$j"] 1 68
2570                }
2571                # delete any remaining lines
2572                for {set j [expr {$n2+1}]} {$j <= $n1} {incr j 1} {
2573                    delexp "LEQV PF${term}${l1}$j"
2574                }
2575            }
2576
2577            # clear the last term
2578            if {$nterms > 9} {
2579                set i [expr {($nterms+1)/10}]
2580            } else {
2581                set i " "
2582            }
2583            set key "LEQV PF$term  $i"
2584            set cb [expr {($nterms%10)*5}]
2585            set ce [expr {4+(($nterms%10)*5)}]
2586            set n2 [string trim [string range [readexp ${key}] $cb $ce] ]
2587            incr cb
2588            setexp $key "     " $cb 5
2589            # delete any remaining lines
2590            for {set j 1} {$j <= $n2} {incr j 1} {
2591                delexp "LEQV PF${term}${nterms}$j"
2592            }
2593        }
2594        profile*-set {
2595            regsub profile $type {} term
2596            if {$term < 10} {
2597                set term " $term"
2598            }
2599            set key "LEQV PF$term   "
2600            # get number of constraint terms
2601            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2602            # don't change a non-existing entry
2603            if {$number > $nterms} {return 0}
2604            if {$number > 9} {
2605                set k1 [expr {($number+1)/10}]
2606                set l1 $number
2607            } else {
2608                set k1 " "
2609                set l1 " $number"
2610            }
2611            set key1 "LEQV PF$term  $k1"
2612            # old number of constraint lines
2613            set n1 [string trim [string range [readexp ${key1}] \
2614                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2615            # number of new constraints
2616            set j2 [llength $value]
2617            # number of new constraint lines
2618            set val [set n2 [expr {($j2 + 2)/3}]]
2619            # store the new # of lines
2620            validint val 5
2621            setexp $key1 $val [expr {1+(($number%10)*5)}] 5
2622
2623            # loop over the # of lines in the old or new, whichever is greater
2624            set v0 0
2625            for {set j 1} {$j <= [expr {($n1 > $n2) ? $n1 : $n2}]} {incr j 1} {
2626                set key "LEQV PF${term}${l1}$j"
2627                # were there more lines in the old?
2628                if {$j > $n2} {
2629                    # this line is not needed
2630                    if {$j % 3 == 1} {
2631                        delexp %key
2632                    }
2633                    continue
2634                }
2635                # are we adding new lines?
2636                if {$j > $n1} {
2637                    makeexprec $key
2638                }
2639                # add the three constraints to the line
2640                foreach s {3 23 43} \
2641                        item [lrange $value $v0 [expr {2+$v0}]] {
2642                    if {$item != ""} {
2643                        set val [format %-10s%9.3f \
2644                                [lindex $item 0],[lindex $item 1] \
2645                                [lindex $item 2]]
2646                        setexp $key $val $s 19
2647                    } else {
2648                        setexp $key " " $s 19
2649                    }
2650                }
2651                incr v0 3
2652            }
2653        }
2654        profile*-add {
2655            regsub profile $type {} term
2656            if {$term < 10} {
2657                set term " $term"
2658            }
2659            set key "LEQV PF$term   "
2660            if {![existsexp $key]} {makeexprec $key}
2661            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2662            if {$nterms == ""} {
2663                set nterms 1
2664            } elseif {$nterms >= 99} {
2665                return 0
2666            } else {
2667                incr nterms
2668            }
2669            # store the new # of constraints
2670            set val $nterms
2671            validint val 5
2672            setexp $key $val 1 5
2673
2674            if {$nterms > 9} {
2675                set k1 [expr {($nterms+1)/10}]
2676                set l1 $nterms
2677            } else {
2678                set k1 " "
2679                set l1 " $nterms"
2680            }
2681            set key1 "LEQV PF$term  $k1"
2682
2683            # number of new constraints
2684            set j2 [llength $value]
2685            # number of new constraint lines
2686            set val [set n2 [expr {($j2 + 2)/3}]]
2687            # store the new # of lines
2688            validint val 5
2689            setexp $key1 $val [expr {1+(($nterms%10)*5)}] 5
2690
2691            # loop over the # of lines to be added
2692            set v0 0
2693            for {set j 1} {$j <= $n2} {incr j 1} {
2694                set key "LEQV PF${term}${l1}$j"
2695                makeexprec $key
2696                # add the three constraints to the line
2697                foreach s {3 23 43} \
2698                        item [lrange $value $v0 [expr {2+$v0}]] {
2699                    if {$item != ""} {
2700                        set val [format %-10s%9.3f \
2701                                [lindex $item 0],[lindex $item 1] \
2702                                [lindex $item 2]]
2703                        setexp $key $val $s 19
2704                    } else {
2705                        setexp $key " " $s 19
2706                    }
2707                }
2708                incr v0 3
2709            }
2710        }
2711        profile*-get {
2712            regsub profile $type {} term
2713            if {$term < 10} {
2714                set term " $term"
2715            }
2716            if {$number > 9} {
2717                set i [expr {($number+1)/10}]
2718            } else {
2719                set i " "
2720            }
2721            set key "LEQV PF$term  $i"
2722            # return nothing if no term exists
2723            if {![existsexp $key]} {return 0}
2724            # number of constraint lines
2725           
2726            set numline [string trim [string range [readexp ${key}] \
2727                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2728            if {$number == 0} {return $numline}
2729            set clist {}
2730            if {$number < 10} {
2731                set number " $number"
2732            }
2733            for {set i 1} {$i <= $numline} {incr i} {
2734                set key "LEQV PF${term}${number}$i"
2735                set line [readexp ${key}]
2736                foreach s {1 21 41} e {20 40 60} {
2737                    set seg [string range $line $s $e]
2738                    if {[string trim $seg] == ""} continue
2739                    # parse the string segment
2740                    set parse [regexp { *([0-9AL]+),([0-9AL]+) +([0-9.]+)} \
2741                            $seg junk phase hist mult]
2742                    # was parse successful
2743                    if {!$parse} {continue}
2744                    lappend clist [list $phase $hist $mult]
2745                }
2746            }
2747            return $clist
2748        }
2749        absorb*-delete {
2750            regsub absorb $type {} term
2751            if {$term < 10} {
2752                set term " $term"
2753            }
2754            set key "LEQV PF$term   "
2755            # return nothing if no term exists
2756            if {![existsexp $key]} {return 0}
2757
2758            # number of constraint terms
2759            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2760            # don't delete a non-existing entry
2761            if {$number > $nterms} {return 0}
2762            set val [expr {$nterms - 1}]
2763            validint val 5
2764            setexp $key $val 1 5
2765            for {set i1 $number} {$i1 < $nterms} {incr i1} {
2766                set i2 [expr {1 + $i1}]
2767                # move the contents of constraint #i2 -> i1
2768                if {$i1 > 9} {
2769                    set k1 [expr {($i1+1)/10}]
2770                    set l1 $i1
2771                } else {
2772                    set k1 " "
2773                    set l1 " $i1"
2774                }
2775                set key1 "LEQV PF$term  $k1"
2776                # number of constraint lines for #i1
2777                set n1 [string trim [string range [readexp ${key1}] \
2778                        [expr {($i1%10)*5}] [expr {4+(($i1%10)*5)}]] ]
2779                if {$i2 > 9} {
2780                    set k2 [expr {($i2+1)/10}]
2781                    set l2 $i2
2782                } else {
2783                    set k2 " "
2784                    set l2 " $i2"
2785                }
2786                set key2 "LEQV PF$term  $k2"
2787                # number of constraint lines for #i2
2788                set n2 [string trim [string range [readexp ${key2}] \
2789                        [expr {($i2%10)*5}] [expr {4+(($i2%10)*5)}]] ]
2790                set val $n2
2791                validint val 5
2792                # move the # of terms
2793                setexp $key1 $val [expr {1+(($i1%10)*5)}] 5
2794                # move the terms
2795                for {set j 1} {$j <= $n2} {incr j 1} {
2796                    set key "LEQV PF${term}${l1}$j"
2797                    makeexprec $key
2798                    setexp $key [readexp "LEQV PF${term}${l2}$j"] 1 68
2799                }
2800                # delete any remaining lines
2801                for {set j [expr {$n2+1}]} {$j <= $n1} {incr j 1} {
2802                    delexp "LEQV PF${term}${l1}$j"
2803                }
2804            }
2805
2806            # clear the last term
2807            if {$nterms > 9} {
2808                set i [expr {($nterms+1)/10}]
2809            } else {
2810                set i " "
2811            }
2812            set key "LEQV PF$term  $i"
2813            set cb [expr {($nterms%10)*5}]
2814            set ce [expr {4+(($nterms%10)*5)}]
2815            set n2 [string trim [string range [readexp ${key}] $cb $ce] ]
2816            incr cb
2817            setexp $key "     " $cb 5
2818            # delete any remaining lines
2819            for {set j 1} {$j <= $n2} {incr j 1} {
2820                delexp "LEQV PF${term}${nterms}$j"
2821            }
2822        }
2823        absorb*-set {
2824            regsub absorb $type {} term
2825            if {$term < 10} {
2826                set term " $term"
2827            }
2828            set key "LEQV PF$term   "
2829            # get number of constraint terms
2830            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2831            # don't change a non-existing entry
2832            if {$number > $nterms} {return 0}
2833            if {$number > 9} {
2834                set k1 [expr {($number+1)/10}]
2835                set l1 $number
2836            } else {
2837                set k1 " "
2838                set l1 " $number"
2839            }
2840            set key1 "LEQV PF$term  $k1"
2841            # old number of constraint lines
2842            set n1 [string trim [string range [readexp ${key1}] \
2843                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2844            # number of new constraints
2845            set j2 [llength $value]
2846            # number of new constraint lines
2847            set val [set n2 [expr {($j2 + 2)/3}]]
2848            # store the new # of lines
2849            validint val 5
2850            setexp $key1 $val [expr {1+(($number%10)*5)}] 5
2851
2852            # loop over the # of lines in the old or new, whichever is greater
2853            set v0 0
2854            for {set j 1} {$j <= [expr {($n1 > $n2) ? $n1 : $n2}]} {incr j 1} {
2855                set key "LEQV PF${term}${l1}$j"
2856                # were there more lines in the old?
2857                if {$j > $n2} {
2858                    # this line is not needed
2859                    if {$j % 3 == 1} {
2860                        delexp %key
2861                    }
2862                    continue
2863                }
2864                # are we adding new lines?
2865                if {$j > $n1} {
2866                    makeexprec $key
2867                }
2868                # add the three constraints to the line
2869                foreach s {3 23 43} \
2870                        item [lrange $value $v0 [expr {2+$v0}]] {
2871                    if {$item != ""} {
2872                        set val [format %-10s%9.3f \
2873                                [lindex $item 0],[lindex $item 1] \
2874                                [lindex $item 2]]
2875                        setexp $key $val $s 19
2876                    } else {
2877                        setexp $key " " $s 19
2878                    }
2879                }
2880                incr v0 3
2881            }
2882        }
2883        absorb*-add {
2884            regsub absorb $type {} term
2885            if {$term < 10} {
2886                set term " $term"
2887            }
2888            set key "LEQV PF$term   "
2889            if {![existsexp $key]} {makeexprec $key}
2890            set nterms [string trim [string range [readexp ${key}] 0 4] ]
2891            if {$nterms == ""} {
2892                set nterms 1
2893            } elseif {$nterms >= 99} {
2894                return 0
2895            } else {
2896                incr nterms
2897            }
2898            # store the new # of constraints
2899            set val $nterms
2900            validint val 5
2901            setexp $key $val 1 5
2902
2903            if {$nterms > 9} {
2904                set k1 [expr {($nterms+1)/10}]
2905                set l1 $nterms
2906            } else {
2907                set k1 " "
2908                set l1 " $nterms"
2909            }
2910            set key1 "LEQV PF$term  $k1"
2911
2912            # number of new constraints
2913            set j2 [llength $value]
2914            # number of new constraint lines
2915            set val [set n2 [expr {($j2 + 2)/3}]]
2916            # store the new # of lines
2917            validint val 5
2918            setexp $key1 $val [expr {1+(($nterms%10)*5)}] 5
2919
2920            # loop over the # of lines to be added
2921            set v0 0
2922            for {set j 1} {$j <= $n2} {incr j 1} {
2923                set key "LEQV PF${term}${l1}$j"
2924                makeexprec $key
2925                # add the three constraints to the line
2926                foreach s {3 23 43} \
2927                        item [lrange $value $v0 [expr {2+$v0}]] {
2928                    if {$item != ""} {
2929                        set val [format %-10s%9.3f \
2930                                [lindex $item 0],[lindex $item 1] \
2931                                [lindex $item 2]]
2932                        setexp $key $val $s 19
2933                    } else {
2934                        setexp $key " " $s 19
2935                    }
2936                }
2937                incr v0 3
2938            }
2939        }
2940        absorb*-get {
2941            regsub absorb $type {} term
2942            set key "LEQV ABS$term   "
2943            if {$number == 0} {
2944                puts [readexp ${key}]
2945                puts [string range [readexp ${key}] 0 5]
2946                puts [string trim [string range [readexp ${key}] 0 5]]
2947            }
2948            puts "**${term}**"
2949            return
2950            set key "LEQV ABS$term  $i"
2951            # return nothing if no term exists
2952            if {![existsexp $key]} {return 0}
2953            # number of constraint lines
2954           
2955            set numline [string trim [string range [readexp ${key}] \
2956                    [expr {($number%10)*5}] [expr {4+(($number%10)*5)}]] ]
2957            if {$number == 0} {return $numline}
2958            set clist {}
2959            if {$number < 10} {
2960                set number " $number"
2961            }
2962            for {set i 1} {$i <= $numline} {incr i} {
2963                set key "LEQV PF${term}${number}$i"
2964                set line [readexp ${key}]
2965                foreach s {1 21 41} e {20 40 60} {
2966                    set seg [string range $line $s $e]
2967                    if {[string trim $seg] == ""} continue
2968                    # parse the string segment
2969                    set parse [regexp { *([0-9AL]+),([0-9AL]+) +([0-9.]+)} \
2970                            $seg junk phase hist mult]
2971                    # was parse successful
2972                    if {!$parse} {continue}
2973                    lappend clist [list $phase $hist $mult]
2974                }
2975            }
2976            return $clist
2977        }
2978        default {
2979            set msg "Unsupported constrinfo access: type=$type action=$action"
2980            tk_dialog .badexp "Error in readexp access" $msg error 0 OK
2981        }
2982
2983    }
2984}
2985
2986# read the default profile information for a histogram
2987# use: profdefinfo hist set# parm action
2988
2989#     proftype -- profile function number
2990#     profterms -- number of profile terms
2991#     pdamp -- damping value for the profile (*)
2992#     pcut -- cutoff value for the profile (*)
2993#     pterm$n -- profile term #n
2994#     pref$n -- refinement flag value for profile term #n (*)
2995
2996proc profdefinfo {hist set parm "action get"} {
2997    global expgui
2998    if {$hist < 10} {
2999        set key "HST  $hist"
3000    } else {
3001        set key "HST $hist"
3002    }
3003    switch -glob ${parm}-$action {
3004        proftype-get {
3005            set val [string range [readexp "${key}PRCF$set"] 0 4]
3006            if {$val == " "} {return 0}
3007            return $val
3008        }
3009        profterms-get {
3010            set val [string range [readexp "${key}PRCF$set"] 5 9]
3011            if {$val == " "} {return 0}
3012            return $val
3013        }
3014        pcut-get {
3015            return [string trim [string range [readexp "${key}PRCF$set"] 10 19]]
3016        }
3017        pdamp-get {
3018                set val [string range [readexp "${key}PRCF$set"] 24 24]
3019            if {$val == " "} {return 0}
3020            return $val
3021        }
3022        pterm*-get {
3023            regsub pterm $parm {} num
3024            set f1 [expr {15*(($num - 1) % 4)}]
3025            set f2 [expr {15*(1 + ($num - 1) % 4)-1}]
3026            set line  [expr {1 + ($num - 1) / 4}]
3027            return [string trim [string range [\
3028                        readexp "${key}PRCF${set}$line"] $f1 $f2] ]
3029        }
3030        pref*-get {
3031            regsub pref $parm {} num
3032            set f [expr {24+$num}]
3033            if {[string toupper [string range [readexp "${key}PRCF$set"] $f $f]] == "Y"} {
3034                return 1
3035            }
3036            return 0
3037        }
3038        default {
3039            set msg "Unsupported profdefinfo access: parm=$parm action=$action"
3040            tk_dialog .badexp "Code Error" $msg error 0 Exit
3041        }
3042    }
3043}
3044
3045# get March-Dollase preferred orientation information
3046# use MDprefinfo hist phase axis-number parm action value
3047#    ratio    -- ratio of xtallites in PO direction vs random (>1 for more)
3048#    fraction -- fraction in this direction, when more than one axis is used
3049#    h k & l  -- indices of P.O. axis
3050#    ratioref -- flag to vary ratio
3051#    fracref  -- flag to vary fraction
3052#    damp     -- damping value
3053#    type     -- model type (0 = P.O. _|_ to beam, 1 = || to beam)
3054#    new      -- creates a new record with default values (set only)
3055proc MDprefinfo {histlist phaselist axislist parm "action get" "value {}"} {
3056    foreach phase $phaselist hist $histlist axis $axislist {
3057        if {$phase == ""} {set phase [lindex $phaselist end]}
3058        if {$hist == ""} {set hist [lindex $histlist end]}
3059        if {$axis == ""} {set axis [lindex $axislist end]}
3060        if {$hist < 10} {
3061            set hist " $hist"
3062        }
3063        if {$axis > 9} {
3064            set axis "0"
3065        }
3066        set key "HAP${phase}${hist}PREFO${axis}"
3067        switch -glob ${parm}-$action {
3068            ratio-get {
3069                return [string trim [string range [readexp $key] 0 9]]
3070            }
3071            ratio-set {
3072                if ![validreal value 10 6] {return 0}
3073                setexp $key $value 1 10
3074            }
3075            fraction-get {
3076                return [string trim [string range [readexp $key] 10 19]]
3077            }
3078            fraction-set {
3079                if ![validreal value 10 6] {return 0}
3080                setexp $key $value 11 10
3081            }
3082            h-get {
3083                set h [string trim [string range [readexp $key] 20 29]]
3084                # why not allow negative h values?
3085                #               if {$h < 1} {return 0}
3086                return $h
3087            }
3088            h-set {
3089                if ![validreal value 10 2] {return 0}
3090                setexp $key $value 21 10
3091            }
3092            k-get {
3093                set k [string trim [string range [readexp $key] 30 39]]
3094                #               if {$k < 1} {return 0}
3095                return $k
3096            }
3097            k-set {
3098                if ![validreal value 10 2] {return 0}
3099                setexp $key $value 31 10
3100            }
3101            l-get {
3102                set l [string trim [string range [readexp $key] 40 49]]
3103                #if {$l < 1} {return 0}
3104                return $l
3105            }
3106            l-set {
3107                if ![validreal value 10 2] {return 0}
3108                setexp $key $value 41 10
3109            }
3110            ratioref-get {
3111                if {[string toupper \
3112                        [string range [readexp $key] 53 53]] == "Y"} {
3113                    return 1
3114                }
3115                return 0
3116            }
3117            ratioref-set {
3118                if $value {
3119                    setexp $key "Y" 54 1
3120                } else {
3121                    setexp $key "N" 54 1
3122                }
3123            }
3124            fracref-get {
3125                if {[string toupper \
3126                        [string range [readexp $key] 54 54]] == "Y"} {
3127                    return 1
3128                }
3129                return 0
3130            }
3131            fracref-set {
3132                if $value {
3133                    setexp $key "Y" 55 1
3134                } else {
3135                    setexp $key "N" 55 1
3136              }
3137            }
3138            damp-get {
3139                set val [string trim [string range [readexp $key] 59 59]]
3140                if {$val == " "} {return 0}
3141                return $val
3142            }
3143            damp-set {
3144                setexp $key $value 60 1
3145            }
3146            type-get {
3147                set val [string trim [string range [readexp $key] 64 64]]
3148                if {$val == " "} {return 0}
3149                return $val
3150            }
3151            type-set {
3152                # only valid settings are 0 & 1
3153                if {$value != "0" && $value != "1"} {set value "0"}
3154                setexp $key $value 65 1
3155            }
3156            new-set {
3157                makeexprec $key
3158                setexp $key \
3159                        {  1.000000  1.000000  0.000000  0.000000  1.000000   NN    0    0} \
3160                        1 68
3161            }
3162            default {
3163                set msg "Unsupported MDprefinfo access: parm=$parm action=$action"
3164                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3165            }
3166
3167        }
3168
3169    }
3170}
3171
3172# get list of defined atom types
3173proc AtmTypList {} {
3174    set natypes [readexp " EXPR  NATYP"]
3175    if {$natypes == ""} return
3176    set j 0
3177    set typelist {}
3178    for {set i 1} {$i <= $natypes} {incr i} {
3179        set key {this should never be matched}
3180        while {![existsexp $key]} {
3181            incr j
3182            if {$j > 99} {
3183                return $typelist
3184            } elseif {$j <10} {
3185                set key " EXPR ATYP $j"
3186            } else {
3187                set key " EXPR ATYP$j"
3188            }
3189        }
3190        lappend typelist [string trim [string range $::exparray($key) 2 9]]
3191    }
3192    return $typelist
3193}
3194
3195# read information about atom types
3196#     distrad    atomic distance search radius (get/set)
3197#     angrad     atomic angle search radius (get/set)
3198proc AtmTypInfo {parm atmtype "action get" "value {}"} {
3199    # first, search through the records to find the record matching the type
3200    set natypes [readexp " EXPR  NATYP"]
3201    if {$natypes == ""} return
3202    set j 0
3203    set typelist {}
3204    for {set i 1} {$i <= $natypes} {incr i} {
3205        set key {this should never be matched}
3206        while {![existsexp $key]} {
3207            incr j
3208            if {$j > 99} {
3209                return $typelist
3210            } elseif {$j <10} {
3211                set key " EXPR ATYP $j"
3212            } else {
3213                set key " EXPR ATYP$j"
3214            }
3215        }
3216        if {[string toupper $atmtype] == \
3217                [string toupper [string trim [string range $::exparray($key) 2 9]]]} break
3218        set key {}
3219    }
3220    if {$key == ""} {
3221        # atom type not found
3222        return {}
3223    }
3224    switch -glob ${parm}-$action {
3225        distrad-get {
3226            return [string trim [string range [readexp $key] 15 24]]
3227        }
3228        distrad-set {
3229            if ![validreal value 10 2] {return 0}
3230            setexp $key $value 16 10
3231        }
3232        angrad-get {
3233            return [string trim [string range [readexp $key] 25 34]]
3234        }
3235        angrad-set {
3236            if ![validreal value 10 2] {return 0}
3237            setexp $key $value 26 10
3238        }
3239        default {
3240            set msg "Unsupported AtmTypInfo access: parm=$parm action=$action"
3241            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3242        }
3243    }
3244}
3245# read default information about atom types (records copied to the .EXP file
3246# from the gsas/data/atomdata.dat file as AFAC ...
3247#     distrad returns a list of atom types (one or two letters) and
3248#                the corresponding distance
3249# note that these values are read only (no set option)
3250proc DefAtmTypInfo {parm} {
3251    set keys [array names ::exparray " AFAC *_SIZ"]
3252    set elmlist {}
3253    if {[llength $keys] <= 0} {return ""}
3254    foreach key $keys {
3255        lappend elmlist [string trim [string range $key 6 7]]
3256    }
3257    switch -glob ${parm} {
3258        distrad {
3259            set out {}
3260            foreach key $keys elm $elmlist {
3261                set val [string range $::exparray($key) 0 9]
3262                lappend out "$elm [string trim $val]"
3263            }
3264            return $out
3265        }
3266        angrad {
3267            set out {}
3268            foreach key $keys elm $elmlist {
3269                set val [string range $::exparray($key) 10 19]
3270                lappend out "$elm [string trim $val]"
3271            }
3272            return $out
3273        }
3274        default {
3275            set msg "Unsupported DefAtmTypInfo access: parm=$parm"
3276            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3277        }
3278    }
3279}
3280# write the .EXP file
3281proc expwrite {expfile} {
3282    global exparray
3283    set blankline \
3284     "                                                                        "
3285    set fp [open ${expfile} w]
3286    fconfigure $fp -translation crlf -encoding ascii
3287    set keylist [lsort [array names exparray]]
3288    # reorder the keys so that VERSION comes 1st
3289    set pos [lsearch -exact $keylist {     VERSION}]
3290    set keylist "{     VERSION} [lreplace $keylist $pos $pos]"
3291    foreach key $keylist {
3292        puts $fp [string range \
3293                "$key$exparray($key)$blankline" 0 79]
3294    }
3295    close $fp
3296}
3297
3298# history commands -- delete all but last $keep history records,
3299# renumber if $renumber is true
3300proc DeleteHistory {keep renumber} {
3301    global exparray
3302    foreach y [lrange [lsort -decreasing \
3303            [array names exparray {    HSTRY*}]] $keep end] {
3304        unset exparray($y)
3305    }
3306    if !$renumber return
3307    # renumber
3308    set i 0
3309    foreach y [lsort -increasing \
3310            [array names exparray {    HSTRY*}]] {
3311        set key [format "    HSTRY%3d" [incr i]]
3312        set exparray($key) $exparray($y)
3313        unset exparray($y)
3314    }
3315    # list all history
3316    #    foreach y [lsort -decreasing [array names exparray {    HSTRY*}]] {puts "$y $exparray($y)"}
3317}
3318
3319proc CountHistory {} {
3320    global exparray
3321    return [llength [array names exparray {    HSTRY*}]]
3322}
3323
3324# set the phase flags for histogram $hist to $plist
3325proc SetPhaseFlag {hist plist} {
3326    # make a 2 digit key -- hh
3327    if {$hist < 10} {
3328        set hh " $hist"
3329    } else {
3330        set hh $hist
3331    }
3332    set key "HST $hh NPHAS"
3333    set str {}
3334    foreach iph {1 2 3 4 5 6 7 8 9} {
3335        if {[lsearch $plist $iph] != -1} {
3336            append str {    1}
3337        } else {
3338            append str {    0}     
3339        }
3340    }
3341    setexp $key $str 1 68
3342}
3343
3344# erase atom $atom from phase $phase
3345# update the list of atom types, erasing the record if not needed.
3346proc EraseAtom {atom phase} {
3347    set type [atominfo $phase $atom type]
3348    if {$type == ""} return
3349    if {$atom < 10} {
3350        set key "CRS$phase  AT  $atom"
3351    } elseif {$atom < 100} {
3352        set key "CRS$phase  AT $atom"
3353    } else {
3354        set key "CRS$phase  AT$atom"
3355    }
3356    # delete the records for the atom
3357    global exparray
3358    foreach k [array names exparray ${key}*] {
3359        delexp $k
3360    }
3361    # change the number of atoms in the phase
3362    phaseinfo $phase natoms set [expr {[phaseinfo $phase natoms] -1}]
3363
3364    # now adjust numbers in "EXPR ATYP" records and delete, if needed.
3365    set natypes [readexp " EXPR  NATYP"]
3366    if {$natypes == ""} return
3367    set j 0
3368    for {set i 1} {$i <= $natypes} {incr i} {
3369        incr j
3370        if {$j <10} {
3371            set key " EXPR ATYP $j"
3372        } else {
3373            set key " EXPR ATYP$j"
3374        }
3375        while {![existsexp $key]} {
3376            incr j
3377            if {$j > 99} {
3378                return
3379            } elseif {$j <10} {
3380                set key " EXPR ATYP $j"
3381            } else {
3382                set key " EXPR ATYP$j"
3383            }
3384        }
3385        set keytype [string trim [string range $exparray($key) 2 9]]
3386        if {$type == $keytype} {
3387            # found the type record
3388            set val [string trim [string range $exparray($key) 10 14]]
3389            incr val -1
3390            # if this is the last reference, remove the record,
3391            # otherwise, decrement the counter
3392            if {$val <= 0} {
3393                incr natypes -1 
3394                validint natypes 5
3395                setexp " EXPR  NATYP" $natypes 1 5
3396                delexp $key
3397            } else {
3398                validint val 5
3399                setexp $key $val 11 5
3400            }
3401            return
3402        }
3403    }
3404}
3405
3406# compute equivalent anisotropic temperature factor for Uequiv
3407proc CalcAniso {phase Uequiv} {
3408    foreach var {a b c alpha beta gamma} {
3409        set $var [phaseinfo $phase $var]
3410    }
3411
3412    set G(1,1) [expr {$a * $a}]
3413    set G(2,2) [expr {$b * $b}]
3414    set G(3,3) [expr {$c * $c}]
3415    set G(1,2) [expr {$a * $b * cos($gamma*0.017453292519943)}]
3416    set G(2,1) $G(1,2)
3417    set G(1,3) [expr {$a * $c * cos($beta *0.017453292519943)}]
3418    set G(3,1) $G(1,3)
3419    set G(2,3) [expr {$b * $c * cos($alpha*0.017453292519943)}]
3420    set G(3,2) $G(2,3)
3421
3422    # Calculate the volume**2
3423    set v2 0.0
3424    foreach i {1 2 3} {
3425        set J [expr {($i%3) + 1}]
3426        set K [expr {(($i+1)%3) + 1}]
3427        set v2 [expr {$v2+ $G(1,$i)*($G(2,$J)*$G(3,$K)-$G(3,$J)*$G(2,$K))}]
3428    }
3429    if {$v2 > 0} {
3430        set v [expr {sqrt($v2)}]
3431        foreach i {1 2 3} {
3432            set i1 [expr {($i%3) + 1}]
3433            set i2 [expr {(($i+1)%3) + 1}]
3434            foreach j {1 2 3} {
3435                set j1 [expr {($j%3) + 1}]
3436                set j2 [expr {(($j+1)%3) + 1}]
3437                set C($j,$i) [expr {(\
3438                        $G($i1,$j1) * $G($i2,$j2) - \
3439                        $G($i1,$j2)  * $G($i2,$j1)\
3440                        )/ $v}]
3441            }
3442        }
3443        set A(1,2) [expr {0.5 * ($C(1,2)+$C(2,1)) / sqrt( $C(1,1)* $C(2,2) )}]
3444        set A(1,3) [expr {0.5 * ($C(1,3)+$C(3,1)) / sqrt( $C(1,1)* $C(3,3) )}]
3445        set A(2,3) [expr {0.5 * ($C(2,3)+$C(3,2)) / sqrt( $C(2,2)* $C(3,3) )}]
3446        foreach i {1 1 2} j {2 3 3} {
3447            set A($i,$j) [expr {0.5 * ($C($i,$j) + $C($j,$i)) / \
3448                    sqrt( $C($i,$i)* $C($j,$j) )}]
3449            # clean up roundoff
3450            if {abs($A($i,$j)) < 1e-5} {set A($i,$j) 0.0}
3451        }
3452    } else {
3453        set A(1,2) 0.0
3454        set A(1,3) 0.0
3455        set A(2,3) 0.0
3456    }
3457    return "$Uequiv $Uequiv $Uequiv \
3458            [expr {$Uequiv * $A(1,2)}] \
3459            [expr {$Uequiv * $A(1,3)}] \
3460            [expr {$Uequiv * $A(2,3)}]"
3461}
3462
3463# read/edit soft (distance) restraint info
3464#  parm:
3465#    weight -- histogram weight (factr) *
3466#    restraintlist -- list of restraints *
3467#  action: get (default) or set
3468#  value: used only with set
3469#  * =>  read+write supported
3470proc SoftConst {parm "action get" "value {}"} {
3471    set HST {}
3472    # look for RSN record
3473    set n 0
3474    for {set i 0} {$i < $::expmap(nhst)} {incr i} {
3475        set ihist [expr {$i + 1}]
3476        if {[expr {$i % 12}] == 0} {
3477            incr n
3478            set line [readexp " EXPR  HTYP$n"]
3479            if {$line == ""} {
3480                set msg "No HTYP$n entry for Histogram $ihist. This is an invalid .EXP file"
3481                tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3482            }
3483            set j 0
3484        } else {
3485            incr j
3486        }
3487        if {[string range $line [expr 2+5*$j] [expr 5*($j+1)]] == "RSN "} {
3488            set HST $ihist
3489        }
3490    }
3491    if {$HST <=9} {
3492        set key "HST  $HST"
3493    } else {
3494        set key "HST $HST"
3495    }
3496    if {$HST == "" && $action == "set"} {
3497        # no RSN found need to add the soft constr. histogram
3498        # increment number of histograms
3499        set hst [string trim [string range [readexp { EXPR  NHST }] 0 4]]
3500        incr hst
3501        set HST $hst
3502        if ![validint hst 5] {return 0}
3503        setexp  { EXPR  NHST } $hst 1 5
3504        # add to EXPR HTYPx rec, creating if needed
3505        set n [expr { 1+ (($HST - 1) / 12) }]
3506        set key " EXPR  HTYP$n"
3507        if {[array names ::exparray $key] == ""} {
3508            makeexprec $key
3509        }
3510        setexp $key "RSN " [expr 3 + 5*(($HST-1) % 12)] 5
3511        # create other HST  xx recs
3512        if {$HST <=9} {
3513            set key "HST  $HST"
3514        } else {
3515            set key "HST $HST"
3516        }
3517        makeexprec "$key  HNAM"
3518        setexp "$key  HNAM" "Bond distance restraints" 3 24
3519        makeexprec "$key FACTR"
3520        makeexprec "$key NBNDS"
3521        mapexp
3522    } elseif {$HST == ""} {
3523        if $::expgui(debug) {puts "no restraints"}
3524        return "1"
3525    }
3526
3527    switch -glob ${parm}-$action {
3528        weight-get {
3529            return [string trim [string range [readexp "$key FACTR"] 0 14]]
3530        }
3531        weight-set {
3532            # update FACTR
3533            if ![validreal value 15 6] {return 0}
3534            setexp "$key FACTR" $value 1 15
3535        }
3536        restraintlist-get {
3537            set ncons [string trim [string range [readexp "$key NBNDS"] 0 4]]
3538            set conslist {}
3539            for {set i 1} {$i <= $ncons} {incr i} {
3540                set fi [string toupper [format %.4x $i]]
3541                set line [readexp "${key}BD$fi"]
3542                set const {}
3543                foreach len {3 5 5 3 3 3 3 3 6 6} {
3544                  set lenm1 [expr {$len - 1}]
3545                  lappend const [string trim [string range $line 0 $lenm1]]
3546                  set line [string range $line $len end]
3547                }
3548                lappend conslist $const
3549            }
3550            return $conslist
3551        }
3552        restraintlist-set {
3553            set num [llength $value]
3554            if ![validint num 5] {return 0}
3555            setexp "$key NBNDS" $num 1 5
3556            # delete all old records
3557            foreach i [array names ::exparray "${key}BD*"] {unset ::exparray($i)}
3558            set i 0
3559            foreach cons $value {
3560                incr i
3561                set fi [string toupper [format %.4x $i]]
3562                makeexprec "${key}BD$fi"
3563                set pos 1
3564                foreach num $cons len {3 5 5 3 3 3 3 3 -6 -6} {
3565                    if {$len > 0} {
3566                        validint num $len
3567                        setexp "${key}BD$fi" $num $pos $len
3568                    } else {
3569                        set len [expr abs($len)]
3570                        validreal num $len 3
3571                        setexp "${key}BD$fi" $num $pos $len
3572                    }
3573                    incr pos $len
3574                }
3575            }
3576        }
3577        default {
3578            set msg "Unsupported phaseinfo access: parm=$parm action=$action"
3579            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
3580        }
3581    return 1
3582    }
3583}
3584
3585#======================================================================
3586# conversion routines
3587#======================================================================
3588
3589# convert x values to d-space
3590proc tod {xlist hst} {
3591    global expmap
3592    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3593        return [toftod $xlist $hst]
3594    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3595        return [tttod $xlist $hst]
3596    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3597        return [engtod $xlist $hst]
3598    } else {
3599        return {}
3600    }
3601}
3602
3603# convert tof to d-space
3604proc toftod {toflist hst} {
3605    set difc [expr {[histinfo $hst difc]/1000.}]
3606    set difc2 [expr {$difc*$difc}]
3607    set difa [expr {[histinfo $hst difa]/1000.}]
3608    set zero [expr {[histinfo $hst zero]/1000.}]
3609    set ans {}
3610    foreach tof $toflist {
3611        if {$tof == 0.} {
3612            lappend ans 0.
3613        } elseif {$tof == 1000.} {
3614            lappend ans 1000.
3615        } else {
3616            set td [expr {$tof-$zero}]
3617            lappend ans [expr {$td*($difc2+$difa*$td)/ \
3618                    ($difc2*$difc+2.0*$difa*$td)}]
3619        }
3620    }
3621    return $ans
3622}
3623
3624# convert two-theta to d-space
3625proc tttod {twotheta hst} {
3626    set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3627    set zero [expr [histinfo $hst zero]/100.]
3628    set ans {}
3629    set cnv [expr {acos(0.)/180.}]
3630    foreach tt $twotheta {
3631        if {$tt == 0.} {
3632            lappend ans 99999.
3633        } elseif {$tt == 1000.} {
3634            lappend ans 0.
3635        } else {
3636            lappend ans [expr {$lamo2 / sin($cnv*($tt-$zero))}]
3637        }
3638    }
3639    return $ans
3640}
3641
3642# convert energy (edx-ray) to d-space
3643# (note that this ignores the zero correction)
3644proc engtod {eng hst} {
3645    set lam [histinfo $hst lam1]
3646    set zero [histinfo $hst zero]
3647    set ans {}
3648    set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3649    foreach e $eng {
3650        if {$e == 0.} {
3651            lappend ans 1000.
3652        } elseif {$e == 1000.} {
3653            lappend ans 0.
3654        } else {
3655            lappend ans [expr {$v/$e}]
3656        }
3657    }
3658    return $ans
3659}
3660
3661# convert x values to Q
3662proc toQ {xlist hst} {
3663    global expmap
3664    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3665        return [toftoQ $xlist $hst]
3666    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3667        return [tttoQ $xlist $hst]
3668    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3669        return [engtoQ $xlist $hst]
3670    } else {
3671        return {}
3672    }
3673}
3674# convert tof to Q
3675proc toftoQ {toflist hst} {
3676    set difc [expr {[histinfo $hst difc]/1000.}]
3677    set difc2 [expr {$difc*$difc}]
3678    set difa [expr {[histinfo $hst difa]/1000.}]
3679    set zero [expr {[histinfo $hst zero]/1000.}]
3680    set 2pi [expr {4.*acos(0.)}]
3681    set ans {}
3682    foreach tof $toflist {
3683        if {$tof == 0.} {
3684            lappend ans 99999.
3685        } elseif {$tof == 1000.} {
3686            lappend ans 0.
3687        } else {
3688            set td [expr {$tof-$zero}]
3689            lappend ans [expr {$2pi * \
3690                    ($difc2*$difc+2.0*$difa*$td)/($td*($difc2+$difa*$td))}]
3691        }
3692    }
3693    return $ans
3694}
3695
3696# convert two-theta to Q
3697proc tttoQ {twotheta hst} {
3698    set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3699    set zero [expr [histinfo $hst zero]/100.]
3700    set ans {}
3701    set cnv [expr {acos(0.)/180.}]
3702    set 2pi [expr {4.*acos(0.)}]
3703    foreach tt $twotheta {
3704        if {$tt == 0.} {
3705            lappend ans 0.
3706        } elseif {$tt == 1000.} {
3707            lappend ans 1000.
3708        } else {
3709            lappend ans [expr {$2pi * sin($cnv*($tt-$zero)) / $lamo2}]
3710        }
3711    }
3712    return $ans
3713}
3714# convert energy (edx-ray) to Q
3715# (note that this ignores the zero correction)
3716proc engtoQ {eng hst} {
3717    set lam [histinfo $hst lam1]
3718    set zero [histinfo $hst zero]
3719    set ans {}
3720    set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3721    set 2pi [expr {4.*acos(0.)}]
3722    foreach e $eng {
3723        if {$e == 0.} {
3724            lappend ans 0.
3725        } elseif {$e == 1000.} {
3726            lappend ans 1000.
3727        } else {
3728            lappend ans [expr {$2pi * $e / $v}]
3729        }
3730    }
3731    return $ans
3732}
3733proc sind {angle} {
3734    return [expr {sin($angle*acos(0.)/90.)}]
3735}
3736
3737# convert d-space values to 2theta, TOF or KeV
3738proc fromd {dlist hst} {
3739    global expmap
3740    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3741        set difc [expr {[histinfo $hst difc]/1000.}]
3742        set difa [expr {[histinfo $hst difa]/1000.}]
3743        set zero [expr {[histinfo $hst zero]/1000.}]
3744        set ans {}
3745        foreach d $dlist {
3746            if {$d == 0.} {
3747                lappend ans 0.
3748            } elseif {$d == 1000.} {
3749                lappend ans 1000.
3750            } else {
3751                lappend ans [expr {$difc*$d + $difa*$d*$d + $zero}]
3752            }
3753        }
3754        return $ans
3755    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3756        set lamo2 [expr {0.5 * [histinfo $hst lam1]}]
3757        set zero [expr [histinfo $hst zero]/100.]
3758        set ans {}
3759        set cnv [expr {180./acos(0.)}]
3760        foreach d $dlist {
3761            if {$d == 99999.} {
3762                lappend ans 0
3763            } elseif {$d == 0.} {
3764                lappend ans 1000.
3765            } else {
3766                lappend ans [expr {$cnv*asin($lamo2/$d) + $zero}]
3767            }
3768        }
3769        return $ans
3770    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3771        set lam [histinfo $hst lam1]
3772        set zero [histinfo $hst zero]
3773        set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3774        set ans {}
3775        foreach d $dlist {
3776            if {$d == 1000.} {
3777                lappend ans 0
3778            } elseif {$d == 0.} {
3779                lappend ans 1000.
3780            } else {
3781                lappend ans [expr {$v/$d}]
3782            }
3783        }
3784        return $ans
3785    } else {
3786        return {}
3787    }
3788}
3789
3790# convert Q values to 2theta, TOF or KeV
3791proc fromQ {Qlist hst} {
3792    global expmap
3793    if {[string range $expmap(htype_$hst) 2 2] == "T"} {
3794        set difc [expr {[histinfo $hst difc]/1000.}]
3795        set difa [expr {[histinfo $hst difa]/1000.}]
3796        set zero [expr {[histinfo $hst zero]/1000.}]
3797        set ans {}
3798        foreach Q $Qlist {
3799            if {$Q == 0.} {
3800                lappend ans 1000.
3801            } elseif {$Q == 99999.} {
3802                lappend ans 1000.
3803            } else {
3804                set d [expr {4.*acos(0.)/$Q}]
3805                lappend ans [expr {$difc*$d + $difa*$d*$d + $zero}]
3806            }
3807        }
3808        return $ans
3809    } elseif {[string range $expmap(htype_$hst) 2 2] == "C"} {
3810        set lamo4pi [expr {[histinfo $hst lam1]/(8.*acos(0.))}]
3811        set zero [expr [histinfo $hst zero]/100.]
3812        set ans {}
3813        set cnv [expr {180./acos(0.)}]
3814        foreach Q $Qlist {
3815            if {$Q == 0.} {
3816                lappend ans 0
3817            } elseif {$Q == 1000.} {
3818                lappend ans 1000.
3819            } else {
3820                lappend ans [expr {$cnv*asin($Q*$lamo4pi) + $zero}]
3821            }
3822        }
3823        return $ans
3824    } elseif {[string range $expmap(htype_$hst) 2 2] == "E"} {
3825        set lam [histinfo $hst lam1]
3826        set zero [histinfo $hst zero]
3827        set v [expr {12.398/(2.0*[sind[expr ($lam/2.0)]])}]
3828        set ans {}
3829        set 2pi [expr {4.*acos(0.)}]
3830        foreach Q $Qlist {
3831            if {$Q == 1000.} {
3832                lappend ans 0
3833            } elseif {$Q == 0.} {
3834                lappend ans 1000.
3835            } else {
3836                lappend ans [expr {$Q * $v/$2pi}]
3837            }
3838        }
3839        return $ans
3840    } else {
3841        return {}
3842    }
3843}
3844#============================================================================
3845# rigid body EXP editing routines (to move into readexp.tcl)
3846# RigidBodyList -- returns a list of the defined rigid body types
3847# SetRigidBodyVar -- set variables and damping for rigid body type multipliers
3848# ReadRigidBody  -- # of times a body is mapped, scaling factors, var #s & coordinates
3849# RigidBodyMappingList - return a list instances where a RB is mapped in phase
3850# RigidBodyEnableTLS -- Enable or Disable TLS use for a rigid body mapping
3851# RigidBodySetTLS  -- change the TLS values for a rigid body mapping
3852# RigidBodySetDamp -- change the damping values for a rigid body mapping
3853# RigidBodyVary    -- set refinement variable numbers for a rigid body mapping
3854# RigidBodyTLSVary -- set TLS refinement variable nums for a rigid body mapping
3855# AddRigidBody -- defines a new rigid body type
3856# DeleteRigidBody -- remove a rigid body definition
3857# ReplaceRigidBody -- replaces a previous rigid body type
3858# ReadRigidBodyMapping  -- get parameters for a rigid body mapping
3859# MapRigidBody -- map a rigid body type into a phase
3860# EditRigidBodyMapping -- change the parameters in a rigid body mapping
3861# UnMapRigidBody --remove a rigid body constraint by removing a RB "instance"
3862#----- note that these older routines should not be used ------
3863# RigidBodyCount -- returns the number of defined rigid bodies (body types)
3864#    use RigidBodyList instead
3865# RigidBodyMappingCount -- # of times a rigid body is mapped in phase
3866#    use RigidBodyMappingList instead
3867#============================================================================
3868# returns the number of defined rigid bodies
3869proc RigidBodyCount {} {
3870    set n [string trim [readexp "RGBD  NRBDS"]]
3871    if {$n == ""} {
3872        set n 0
3873    }
3874    return $n
3875}
3876
3877# returns a list of the defined rigid body types
3878proc RigidBodyList {} {
3879    set n [string trim [readexp "RGBD  NRBDS"]]
3880    if {$n == ""} {
3881        set n 0
3882    }
3883    set rblist {}
3884    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
3885        set value $rbnum
3886        validint value 2
3887        set key "RGBD${value}"
3888        if {[existsexp "$key NATR "]} {
3889            lappend rblist $rbnum
3890        }
3891        if {[llength $rblist] == $n} break
3892    }
3893    return $rblist
3894}
3895
3896# ReadRigidBody provides all information associated with a rigid body type
3897#  rbnum is the rigid body type number
3898# it returns two items:
3899#   the number of times the rigid body is mapped
3900#   a list containing an element for each scaling factor in rigid body #rbnum.
3901# in each element there are four items:
3902#    a multiplier value for the rigid body coordinates
3903#    a damping value (0-9) for the refinement of the multiplier
3904#    a variable number if the multiplier will be refined
3905#    a list of cartesian coordinates coordinates
3906# each cartesian coordinate contains 4 items: x,y,z and a label
3907#  note that the label is present only when the RB is created in EXPGUI and is
3908#  not used in GSAS.
3909proc ReadRigidBody {rbnum} {
3910    if {[lsearch [RigidBodyList] $rbnum] == -1} {
3911        return ""
3912    }
3913    set value $rbnum
3914    validint value 2
3915    set key "RGBD${value}"
3916    set n [string trim [string range [readexp "$key NATR"] 0 4]]
3917    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
3918    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
3919    set out {}
3920    for {set i 1} {$i <= $nmult} {incr i} {
3921        set line [readexp "${key}${i}PARM"]
3922        set mult [string trim [string range $line 0 9]]
3923        set var [string trim [string range $line 10 14]]
3924        set damp [string trim [string range $line 15 19]]
3925        set coordlist {}
3926        for {set j 1} {$j <= $n} {incr j} {
3927            set value $j
3928            validint value 3
3929            set line [readexp "${key}${i}SC$value"]
3930            set x [string trim [string range $line 0 9]]
3931            set y [string trim [string range $line 10 19]]
3932            set z [string trim [string range $line 20 29]]
3933            set lbl [string trim [string range $line 30 39]]
3934            lappend coordlist [list $x $y $z $lbl]
3935        }
3936        lappend out [list $mult $damp $var $coordlist]
3937    }
3938    return [list $used $out]
3939}
3940
3941# SetRigidBodyVar
3942#   rbnum is the rigid body type number
3943#   varnumlist is a list of variable numbers
3944#      note that if this list is shorter than the number of actual multipliers
3945#      for the body, the unspecified variable will not be changed
3946#   damplist   is a list of damping values (0-9)
3947#      note that if the damplist is shorter than the number of actual multipliers
3948#      the unspecified values are not changed
3949#  SetRigidBodVar 2 {1 2 3} {}
3950#       will vary the (first 3) translations in body #3 and will not change the
3951#       damping values
3952#  SetRigidBodVar 3 {} {0 0 0}
3953#       will not change variable settings but will change the (first 3) damping values
3954#  SetRigidBodVar 4 {11 11} {8 8}
3955#      changes both variable numbers and damping at the same time
3956# Nothing is returned
3957proc SetRigidBodyVar {rbnum varnumlist damplist} {
3958    if {[lsearch [RigidBodyList] $rbnum] == -1} {
3959        return ""
3960    }
3961    set value $rbnum
3962    validint value 2
3963    set key "RGBD${value}"
3964    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
3965    for {set i 1} {$i <= $nmult} {incr i} {
3966        set j $i
3967        incr j -1
3968        set var [lindex $varnumlist $j]
3969        if {$var != ""} {
3970            validint var 5
3971            setexp "${key}${i}PARM" $var 11 15
3972        }
3973        set damp [lindex $damplist $j]
3974        if {$damp != ""} {
3975            if {$damp > 9} {set damp 9}
3976            if {$damp < 0} {set damp 0}
3977            validint damp 5
3978        }
3979        setexp "${key}${i}PARM" $damp 16 20
3980    }
3981}
3982
3983
3984# return the number of times rigid body $bodytyp is mapped in phase $phase
3985proc RigidBodyMappingCount {phase bodytyp} {
3986    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
3987    if {! [existsexp "$key  NBDS"]} {return 0}
3988    set n [string trim [readexp "$key  NBDS"]]
3989    if {$n == ""} {
3990        set n 0
3991    }
3992    return $n
3993}
3994# return a list of the instances where rigid body $bodytyp is mapped in phase $phase
3995proc RigidBodyMappingList {phase bodytyp} {
3996    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
3997    if {! [existsexp "$key  NBDS"]} {return {}}
3998    set n [string trim [readexp "$key  NBDS"]]
3999    if {$n == ""} {
4000        set n 0
4001    }
4002    set rblist {}
4003    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
4004        set value $rbnum
4005        validint value 2
4006        set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
4007        if {[existsexp "$key  NDA"]} {
4008            lappend rblist $rbnum
4009        }
4010        if {[llength $rblist] == $n} break
4011    }
4012    return $rblist
4013}
4014
4015
4016
4017# reads rigid body mapping parameters for phase ($phase), body type # ($bodytyp) and instance # ($num)
4018# returns a list of items (most lists) as follows:
4019#   1) sequence # of first atom in body
4020#   2) origin of body in fractional coordinates (3 elements)
4021#   3) Euler angles as 6 pairs of numbers (see below)
4022#   4) variable numbers for the 9 position variables (origin followed by rotations)
4023#   5) damping vals for the 9 position variables (origin followed by rotations)
4024#   6) the TLS values, in order below (empty list if TLS is not in use)
4025#   7) the variable numbers for each TLS values, in order below (or empty)
4026#   8) three damping values for the T, L and S terms.
4027# returns an empty list if no such body exists.
4028#
4029# Euler angles are a list of axes and angles to rotate:
4030#   { {axis1 angle1} {axis2 angle2} ...}
4031# where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
4032#
4033# The 20 TLS terms are ordered:
4034#    T11, T22, T33, T12, T13, T23
4035#    L11, L22, L33, L12, L13, L23
4036#    S12, S13, S21, S23, S31, S32, SAA, SBB
4037#
4038proc ReadRigidBodyMapping {phase bodytyp num} {
4039    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4040        return ""
4041    }
4042    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4043    set first [string trim [string range [readexp "$key  NDA"] 0 4]]
4044    set line [readexp "$key BDFL"]
4045    set varlist {}
4046    set damplist {}
4047    foreach i {0 1 2 3 4 5 6 7 8} {
4048        lappend varlist [string trim [string range $line [expr {5*$i}] [expr {4 + 5*$i}] ]]
4049        lappend damplist [string trim [string range $line [expr {45 + $i}] [expr {45 + $i}] ]]
4050    }
4051    set TLSdamplist {}
4052    foreach i {54 55 56} {
4053        lappend TLSdamplist [string trim [string range $line $i $i ]]
4054    }
4055    set line [readexp "${key} BDLC"]
4056    set x [string trim [string range $line 0 9]]
4057    set y [string trim [string range $line 10 19]]
4058    set z [string trim [string range $line 20 29]]
4059    set origin [list $x $y $z]
4060    set line [readexp "${key} BDOR"]
4061    set rotations {}
4062    foreach i {0 10 20 30 40 50} {
4063        set angle [string trim [string range $line $i [expr {$i+7}]]]
4064        set axis [string trim [string range $line [expr {$i+8}] [expr {$i+9}]]]
4065        lappend rotations [list $angle $axis]
4066    }
4067    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
4068    set tlsvars {}
4069    set tlsvals {}
4070    if {$TLS != 0} {
4071        set line [readexp "${key}TLSF1"]
4072        for {set j 0} {$j < 20} {incr j} {
4073            set var [string trim [string range $line [expr {3*$j}] [expr {3*$j+2}]]]
4074            if {$var == ""} {set var 0}
4075            lappend tlsvars $var
4076        }
4077        for {set j 0} {$j < 20} {incr j} {
4078            set i 0
4079            if {$j == 0} {
4080                set i 1
4081            } elseif {$j == 8} {
4082                set i 2
4083            } elseif {$j == 16} {
4084                set i 3
4085            }
4086            if {$i != 0} {
4087                set line [readexp "${key}TLSP$i"]
4088                set i 0
4089                set j1 0
4090                set j2 7
4091            } else {
4092                incr j1 8
4093                incr j2 8
4094            }
4095            set val [string trim [string range $line $j1 $j2]]
4096            if {$val == ""} {set val 0}
4097            lappend tlsvals $val
4098        }
4099    }
4100    return [list $first $origin $rotations $varlist $damplist $tlsvals $tlsvars $TLSdamplist]
4101}
4102
4103# Control TLS representation for phase, body # and instance number of a Rigid body mapping
4104#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
4105# Enable TLS use if TLS is non-zero (true). Disable if zero
4106proc RigidBodyEnableTLS {phase bodytyp num TLS} {
4107    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4108        return ""
4109    }
4110    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4111    if {$TLS} {
4112        setexp "${key} LSTF" [format "%5d" 1] 1 5
4113        if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
4114        if {![existsexp "${key}TLSP1"]} {
4115            makeexprec "${key}TLSP1"
4116            set str {}
4117            foreach v {.01 .01 .01 0 0 0 0 0} d {4 4 4 4 4 4 2 2} {
4118                validreal v 8 $d
4119                append str $v
4120            }
4121            setexp "${key}TLSP1" $str 1 64
4122        }
4123        if {![existsexp "${key}TLSP2"]} {
4124            makeexprec "${key}TLSP2"
4125            set str {}
4126            set v 0
4127            foreach d {2 2 2 2 4 4 4 4} {
4128                validreal v 8 $d
4129                append str $v
4130            }
4131            setexp "${key}TLSP2" $str 1 64
4132        }
4133        if {![existsexp "${key}TLSP3"]} {
4134            makeexprec "${key}TLSP3"
4135            set str {}
4136            set v 0
4137            foreach d {4 4 4 4} {
4138                validreal v 8 $d
4139                append str $v
4140            }
4141            setexp "${key}TLSP3" $str 1 64
4142        }
4143    } else {
4144        setexp "${key} LSTF" [format "%5d" 0] 1 5
4145    }
4146    return 1
4147}
4148
4149# Control the TLS values for Rigid body mapping for mapping with
4150#    phase ($phase), body type # ($bodytyp) and instance # ($num)
4151# set the 20 TLS values to the values in TLSvals
4152# There must be exactly 20 TLS terms, which are ordered:
4153#    T11, T22, T33, T12, T13, T23
4154#    L11, L22, L33, L12, L13, L23
4155#    S12, S13, S21, S23, S31, S32, SAA, SBB
4156proc RigidBodySetTLS {phase bodytyp num TLSvals} {
4157    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4158        return ""
4159    }
4160    if {[llength $TLSvals] != 20} {return ""}
4161    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4162    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
4163    if {$TLS == 0} {return ""}
4164    if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
4165    foreach n {1 2 3} {
4166        if {![existsexp "${key}TLSP$n"]} {makeexprec "${key}TLSP$n"}
4167    }
4168    set str {}
4169    set n 1
4170    set i 0
4171    foreach v $TLSvals d {4 4 4 4 4 4 2 2 2 2 2 2 4 4 4 4 4 4 4 4} {
4172        incr i
4173        validreal v 8 $d
4174        append str $v
4175        if {$i == 8} {
4176            set i 0
4177            setexp "${key}TLSP$n" $str 1 64
4178            incr n
4179            set str {}
4180        }
4181    }
4182    setexp "${key}TLSP$n" $str 1 64
4183    return 1
4184}
4185
4186# set damping values for a Rigid body mapping
4187#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
4188# there must be 9 damping values in RBdamp for the 9 position variables (origin followed by rotations)
4189# Use of TLSdamp is optional, but to be used, TLS representation must be enabled and there must be
4190# three damping terms (for all T terms; for all L terms and for all S terms)
4191proc RigidBodySetDamp {phase bodytyp num RBdamp "TLSdamp {}"} {
4192    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4193        return ""
4194    }
4195    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4196    if {[llength $RBdamp] != 9} {return ""}
4197    set str {}
4198    foreach v $RBdamp {
4199        if {[validint v 1] != 1} {set v " "}
4200        append str $v
4201    }
4202    setexp "$key BDFL" $str 46 9
4203    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
4204    if {$TLS != 0 &&  [llength $TLSdamp] == 3} {
4205        set str {}
4206        foreach v $TLSdamp {
4207        if {[validint v 1] != 1} {set v " "}
4208            append str $v
4209        }
4210        setexp "$key BDFL" $str 55 3
4211    }
4212    return 1
4213}
4214
4215# set refinement variable numbers for a Rigid body mapping
4216#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
4217# there must be 9 variable values in RBvar for the 9 position variables (origin followed by rotations)
4218# note that the variable values should be unique integers
4219proc RigidBodyVary {phase bodytyp num RBvar} {
4220    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4221        return ""
4222    }
4223    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4224    if {[llength $RBvar] != 9} {return ""}
4225    set str {}
4226    foreach v $RBvar {
4227        if {[validint v 5] != 1} {set v " "}
4228        append str $v
4229    }
4230    setexp "$key BDFL" $str 1 45   
4231}
4232
4233# set TLS refinement variable numbers for a Rigid body mapping
4234#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
4235# there must be 20 variable values in TLSvar for the 20 parameters:
4236#    T11, T22, T33, T12, T13, T23
4237#    L11, L22, L33, L12, L13, L23
4238#    S12, S13, S21, S23, S31, S32, SAA, SBB
4239# note that the variable values should be unique integers
4240proc RigidBodyTLSVary {phase bodytyp num TLSvar} {
4241    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
4242        return ""
4243    }
4244    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
4245    if {[llength $TLSvar] != 20} {return ""}
4246    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
4247    if {$TLS == 0} {return ""}
4248    set str {}
4249    foreach v $TLSvar {
4250        if {[validint v 3] != 1} {set v " "}
4251        append str $v
4252    }
4253    setexp "${key}TLSF1" $str 1 60
4254
4255# AddRigidBody: add a new rigid body definition into the .EXP file
4256# arguments are:
4257#   multlist: defines a list of multipliers for each set of coordinates. In the
4258#             simplest case this will be {1}
4259#   coordlist: a nested list of coordinates such as { { {0 0 0} {.1 .1 .1} {.2 .2 .2} } }
4260# note that when the length of multlist > 1 then coordlist must have the same length.
4261# for input where
4262#     multlist = {s1 s2} and
4263#     coordlist = { { {0 0 0} {1 1 0} {.0 .0 .0} ...}
4264#                     {0 0 0} {1 1 0} {2 1 2} ...}
4265#                 }
4266# the cartesian coordinates are defined from the input as
4267#    atom 1 = s1 * (0,0,0) + s2*(0,0,0) [ = (0,0,0)]
4268#    atom 2 = s1 * (1,1,0) + s2*(1,1,0) [ = (s1+s2) * (1,1,0)]
4269#    atom 3 = s1 * (0,0,0) + s2*(2,1,2) [ = s2 * (2,1,2)]
4270#    ...
4271# Returns the number of the rigid body that has been created
4272proc AddRigidBody {multlist coordlist} {
4273    # find the first unused body #
4274    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
4275        set value $rbnum
4276        validint value 2
4277        set key "RGBD${value}"
4278        if {! [existsexp "$key NATR "]} {break}
4279    }
4280    # did we go too far?
4281    if {$rbnum == 16} {return ""}
4282    # increment the RB counter
4283    set n [string trim [readexp "RGBD  NRBDS"]]
4284    if {$n == ""} {
4285        makeexprec "RGBD  NRBDS"
4286        set n 0
4287    }
4288    incr n
4289    validint n 5
4290    setexp "RGBD  NRBDS" $n 1 5
4291    SetRigidBody $rbnum $multlist $coordlist
4292    return $rbnum
4293}
4294
4295# DeleteRigidBody: remove a rigid body definition from the .EXP file
4296# The body may not be mapped. I am not sure if GSAS allows more than 9 bodies,
4297# but if it does, the simplifed approach used here will fail, so this
4298# is not allowed.
4299# Input:
4300#   Rigid body number
4301# Returns:
4302#   1 on success
4303#   -1 if the body number is 11 or greater
4304#   -2 if the body is mapped
4305#   -3 if the body is not defined
4306proc DeleteRigidBody {rbnum} {
4307    # can't delete bodies with numbers higher than 10, since the key prefix
4308    # (RGBD11... will overlap with rigid body instance records, which would be
4309    # deleted below
4310    if {$rbnum > 10} {
4311        return -1
4312    }
4313    set value $rbnum
4314    validint value 2
4315    set key "RGBD${value}"
4316    if {![existsexp "$key NATR "]} {
4317        return -2
4318    }
4319    # make sure the body is not mapped
4320    if {[string trim [string range [readexp "$key NBDS"] 0 4]] != 0} {
4321        return -3
4322    }
4323    # delete the records starting with "RGBD x" or "RGBD10"
4324    foreach key [array names ::exparray "${key}*"] {
4325        #puts $key
4326        delexp $key
4327    }
4328    # decrement the RB counter
4329    set n [string trim [readexp "RGBD  NRBDS"]]
4330    if {$n == ""} {
4331        set n 0
4332    }
4333    incr n -1
4334    validint n 5
4335    if {$n > 0} {
4336        setexp "RGBD  NRBDS" $n 1 5
4337    } else {
4338        delexp "RGBD  NRBDS"
4339    }
4340    return 1
4341}
4342
4343# ReplaceRigidBody: replace all the information for rigid body #rbnum
4344# Works the sames as AddRigidBody (see above) except that the rigid body is replaced rather
4345# than added.
4346# Note that count of the # of times the body is used is preserved
4347proc ReplaceRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
4348    set value $rbnum
4349    validint value 2
4350    set key "RGBD${value}"
4351    set line [readexp "$key NBDS"]
4352    foreach key [array names ::exparray "${key}*"] {
4353        #puts $key
4354        delexp $key
4355    }
4356    SetRigidBody $rbnum $multlist $coordlist $varlist $damplist
4357    setexp "$key NBDS" $line 1 68
4358}
4359
4360# Edit the parameters for rigid body #rbnum
4361# (normally called from ReplaceRigidBody or AddRigidBody)
4362proc SetRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
4363    set value $rbnum
4364    validint value 2
4365    set key "RGBD${value}"
4366    # number of atoms
4367    set value [llength [lindex $coordlist 0]]
4368    validint value 5
4369    makeexprec "$key NATR"
4370    setexp "$key NATR" $value 1 5
4371    # number of times used
4372    set value 0
4373    validint value 5
4374    makeexprec "$key NBDS"
4375    setexp "$key NBDS" $value 1 5
4376    # number of coordinate matrices
4377    set value [llength $multlist]
4378    validint value 5
4379    makeexprec "$key NSMP"
4380    setexp "$key NSMP" $value 1 5
4381    set i 0
4382    foreach mult $multlist coords $coordlist {
4383        set var [lindex $varlist $i]
4384        if {$var == ""} {set var 0}
4385        set damp [lindex $damplist $i]
4386        if {$damp == ""} {set damp 0}
4387        incr i
4388        makeexprec "${key}${i}PARM"
4389        setexp "${key}${i}PARM" [format "%10.5f%5d%5d" $mult $var $damp] 1 20
4390        set j 0
4391        foreach item $coords {
4392            #puts $item
4393            incr j
4394            set value $j
4395            validint value 3
4396            makeexprec "${key}${i}SC$value"
4397            if {[llength $item] == 4} {
4398                setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f%10s" $item] 1 40
4399            } elseif {[llength $item] == 3} {
4400                setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f" $item] 1 30
4401            } else {
4402                return -code 3 "Invalid number of coordinates"
4403            }
4404        }
4405    }
4406}
4407
4408# convert a decimal to the GSAS hex encoding with a field $digits long.
4409proc ToHex {num digits} {
4410    return [string toupper [format "%${digits}x" $num]]
4411}
4412
4413# convert a GSAS hex encoding to a decimal integer
4414proc FromHex {hex} {
4415    return [scan $hex "%x"]
4416}
4417
4418# MapRigidBody: define an "instance" of a rigid body: meaning that the coordinates
4419# (and optionally U values) for a set of atoms will be generated from the rigid body
4420# arguments:
4421#   phase: phase number (1-9)
4422#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4423#   firstatom: sequence number of the first atom in phase (note that atoms may
4424#              not be numbered sequentially)
4425#   position: list of three fractional coordinates for the origin of the rigid body coordinates
4426#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the
4427#           cartesian system before the body is translated to position.
4428# returns the instance # (number of times body $bodytyp has been used in phase $phase)
4429proc MapRigidBody {phase bodytyp firstatom position angles} {
4430    # find the first unused body # for this phase & type
4431    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
4432        set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
4433        if {! [existsexp "$key  NDA"]} {break}
4434    }
4435    # did we go too far?
4436    if {$rbnum == 16} {return ""}
4437    # increment number of mapped bodies of this type overall
4438    set value $bodytyp
4439    validint value 2
4440    set key "RGBD${value}"
4441    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
4442    incr used
4443    set value $used
4444    validint value 5
4445    setexp "$key NBDS" $value 1 5
4446    # increment number of mapped bodies of this type in this phase
4447    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
4448    if {[existsexp "$key  NBDS"]} {
4449        set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
4450    } else {
4451        makeexprec "$key  NBDS"
4452        set used 0
4453    }
4454    incr used
4455    set value $used
4456    validint value 5
4457    setexp "$key  NBDS" $value 1 5
4458    # now write the mapping parameters
4459    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
4460    set value $firstatom
4461    validint value 5
4462    makeexprec "$key  NDA"
4463    setexp "$key  NDA" $value 1 5
4464    set l1 {}
4465    set l2 {}
4466    for {set i 0} {$i < 9} {incr i} {
4467        append l1 [format %5d 0]
4468        append l2 [format %1d 0]
4469    }
4470    makeexprec "$key BDFL"
4471    setexp "$key BDFL" $l1$l2 1 54
4472    makeexprec "${key} BDLC"
4473    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
4474    makeexprec "${key} BDOR"
4475    set l1 {}
4476    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
4477        append l1 [format "%8.2f%2d" $val $dir]
4478    }
4479    setexp "${key} BDOR" $l1 1 60
4480    makeexprec "${key} LSTF"
4481    setexp "${key} LSTF" [format "%5d" 0] 1 5
4482    # turn off the X refinement flags for the new body
4483    set st [lsearch $::expmap(atomlist_$phase) $firstatom]
4484    set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodytyp] 1] 0] 3]]
4485    set en [expr {$st+$natoms-1}]
4486    set atomlist [lrange $::expmap(atomlist_$phase) $st $en]
4487    atominfo $phase $atomlist xref set 0
4488    # redo the mapping to capture the newly mapped atoms
4489    mapexp
4490    return $rbnum
4491}
4492
4493# EditRigidBodyMapping: edit parameters that define an "instance" of a rigid body (see MapRigidBody)
4494# arguments:
4495#   phase: phase number (1-9)
4496#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4497#   bodynum: instance number, as returned by MapRigidBody
4498#   position: list of three fractional coordinates for the origin of the rigid body coordinates
4499#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the
4500#           cartesian system before the body is translated to position.
4501#
4502proc EditRigidBodyMapping {phase bodytyp bodynum position angles} {
4503    # number of bodies of this type in this phase
4504    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $bodynum 1]"
4505    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
4506    set l1 {}
4507    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
4508        append l1 [format "%8.2f%2d" $val $dir]
4509    }
4510    setexp "${key} BDOR" $l1 1 60
4511}
4512
4513# UnMapRigidBody: remove a rigid body constraint by removing a RB "instance"
4514# (undoes MapRigidBody)
4515# arguments:
4516#   phase: phase number (1-9)
4517#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
4518#   bodynum: instance number, as returned by MapRigidBody
4519proc UnMapRigidBody {phase bodytyp mapnum} {
4520    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $mapnum] == -1} {
4521        return ""
4522    }
4523    # decrement number of mapped bodies of this type overall
4524    set value $bodytyp
4525    validint value 2
4526    set key "RGBD${value}"
4527    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
4528    incr used -1
4529    set value $used
4530    validint value 5
4531    setexp "$key NBDS" $value 1 5
4532    # decrement number of mapped bodies of this type in this phase
4533    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
4534    if {[existsexp "$key  NBDS"]} {
4535        set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
4536    } else {
4537        set used 0
4538    }
4539    incr used -1
4540    set value $used
4541    validint value 5
4542    if {$used > 0} {
4543        setexp "$key  NBDS" $value 1 5
4544    } else {
4545        delexp "$key  NBDS"
4546    }
4547    # now delete the mapping parameter records
4548    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $mapnum 1]"
4549    foreach key [array names ::exparray "${key}*"] {
4550        delexp $key
4551    }
4552    return $used
4553}
4554
4555# return a list of defined Fourier maps
4556proc listFourier {} {
4557    set l {}
4558    foreach i {1 2 3 4 5 6 7 8 9} {
4559        if {[existsexp "  FOUR CDAT$i"]} {
4560            lappend l $i
4561        }
4562    }
4563    return $l
4564}
4565
4566# read a Fourier map entry
4567# returns five values:
4568#   0: type of map (DELF,FCLC,FOBS,NFDF,PTSN,DPTS)
4569#   1: section (X,Y or Z)
4570#   2: phase (1-9)
4571#   3: DMIN (usually 0.0)
4572#   4: DMAX (usually 999.99)
4573proc readFourier {num} {
4574    set key "  FOUR CDAT$num"
4575    if {![existsexp $key]} {
4576        return {}
4577    }
4578    set vals {}
4579    # 0: type of map (DELF,FCLC,FOBS,NFDF,PTSN,DPTS)
4580    lappend vals [string trim [string range [readexp $key] 2 6]]
4581    # 1: section (X,Y or Z)
4582    lappend vals [string trim [string range [readexp $key] 7 8]]
4583    # 2: phase (1-9)
4584    lappend vals [string trim [string range [readexp $key] 8 13]]
4585    # 3: DMIN (usually 0.0)
4586    lappend vals [string trim [string range [readexp $key] 18 25]]
4587    # 4: DMAX (usually 999.99)
4588    lappend vals [string trim [string range [readexp $key] 30 37]]
4589    return $vals
4590}
4591
4592# add a new Fourier map computation type
4593#   arguments:
4594#      phase: (1-9)
4595#      type: type of map (DELF,FCLC,FOBS,NFDF,PTSN,DPTS) - default DELF
4596#      section: (X,Y or Z) - default Z
4597#   returns the number of the map that is added
4598proc addFourier {phase {type "DELF"} {section "Z"}} {
4599    set num {}
4600    foreach i {1 2 3 4 5 6 7 8 9} {
4601        set key "  FOUR CDAT$i"
4602        if {! [existsexp "  FOUR CDAT$i"]} {
4603            set num $i
4604            break
4605        }
4606    }
4607    if {$num == ""} {return {}}
4608    set key "  FOUR CDAT$num"
4609    makeexprec $key
4610    setexp $key $type 3 4
4611    setexp $key $section 8 1
4612    validint phase 5
4613    setexp $key $phase 9 5
4614    setexp $key "NOPR   0.00      999.99" 15 23
4615    return $num
4616}
4617
4618# read/set a Fourier computation value
4619# use: Fourierinfo num parm
4620#  or: Fourierinfo num parm set value
4621#
4622#  num is the Fourier entry
4623#  parm is one of the following
4624#     type    -- type of map (DELF,FCLC,FOBS,NFDF,PTSN,DPTS)
4625#     section -- last running map direction (X,Y or Z)
4626#     phase   -- phase (1-9)
4627#     dmin    -- d-space for highest order reflection to use (usually 0.0)
4628#     dmax    -- d-space for lowest order reflection to use (usually 999.99)
4629# all parameters may be read or set
4630proc Fourierinfo {num parm "action get" "value {}"} {
4631    set key "  FOUR CDAT$num"
4632    if {![existsexp $key]} {
4633        return {}
4634    }
4635    switch -glob ${parm}-$action {
4636        type-get {
4637            # type of map (DELF,FCLC,FOBS,NFDF,PTSN,DPTS)
4638            return [string trim [string range [readexp $key] 2 6]]
4639        }
4640        type-set {
4641            set found 0
4642            foreach val {DELF FCLC FOBS NFDF PTSN DPTS} {
4643                if {$val == $value} {
4644                    set found 1
4645                    break
4646                }
4647            }
4648            if $found {
4649                setexp $key $value 3 4
4650            }
4651        }
4652        section-get {
4653            # section (X,Y or Z)
4654            return [string range [readexp $key] 7 8]
4655        }
4656        section-set {
4657            set found 0
4658            foreach val {X Y Z} {
4659                if {$val == $value} {
4660                    set found 1
4661                    break
4662                }
4663            }
4664            if $found {
4665                setexp $key $value 8 1
4666            }
4667        }
4668        phase-get {
4669            # phase (1-9)
4670            return [string trim [string range [readexp $key] 8 13]]
4671        }
4672        phase-set {
4673            validint value 5
4674            setexp $key $value 9 5
4675        }
4676        dmin-get {
4677            # DMIN (usually 0.0)
4678            return [string trim [string range [readexp $key] 18 25]]
4679        }
4680        dmin-set {
4681            validreal value 7 2
4682            setexp $key $value 19 7
4683        }
4684        dmax-get {
4685            # DMAX (usually 999.99)
4686            return [string trim [string range [readexp $key] 30 37]]
4687        }
4688        dmax-set {
4689            validreal value 7 2
4690            setexp $key $value 31 7
4691        }
4692        default {
4693            set msg "Unsupported Fourierinfo access: parm=$parm action=$action"
4694            puts $msg
4695            tk_dialog .badexp "Error in readexp" $msg error 0 Exit
4696        }
4697    }
4698}
4699
4700# set histograms used in Fourier computation
4701#  use:
4702#     FourierHists $phase
4703#     FourierHists $phase set {4 3 2 1}
4704# returns a list of histograms to be used to compute that phase's Fourier map
4705# or sets a list of histograms to be used to compute that phase's Fourier map
4706#
4707# Note that the histograms are loaded in the order specified with reflections in
4708# the last histogram overwriting those in earlier ones, where a reflection
4709# occurs in more than one place
4710proc FourierHists {phase "action get" "value {}"} {
4711    # note that in theory one can have more than one CRSm  FMHSTn record
4712    # if more than 22 histograms are used but we will ignore this
4713    set key "CRS$phase  FMHST1"
4714    if {![existsexp $key]} {
4715        makeexprec $key
4716    }
4717    if {$action == "get"} {
4718        return [string trim [readexp $key]]
4719    } else {
4720        set hlist {}
4721        foreach hist $value {
4722            validint hist 3
4723            append hlist $hist
4724        }
4725        setexp $key $hlist 0 67
4726    }
4727}
4728# get the Fourier map computation step and limits
4729# returns 4 lists:
4730#   {stepx stepy stepz} : step size in Angstroms
4731#   {xmin xmax} : min and max x in fractional coordinates
4732#   {ymin ymax} : min and max y in fractional coordinates
4733#   {zmin zmax} : min and max z in fractional coordinates
4734proc getFourierLimits {phase} {
4735    set key "CRS$phase  FMPCTL"
4736    if {![existsexp $key]} {
4737        setFourierLimits $phase
4738    }
4739    set i 0
4740    set line [readexp $key]
4741    foreach v {x y z} cell {a b c} {
4742        set cell_$v [phaseinfo $phase $cell]
4743    }
4744    foreach typ {step min max} {
4745        foreach v {x y z} {
4746            set val [string trim [string range $line $i [expr $i+5]]]
4747            if {$val == ""} {set val 0}
4748            set ${typ}_${v} $val
4749            incr i 5
4750        }           
4751    }
4752    set steps {}
4753    foreach v {x y z} {
4754        set range_$v {}
4755        lappend steps [expr {[set cell_$v] / [set step_$v]}]
4756        lappend range_$v [expr {[set min_$v] * 1. / [set step_$v] }]
4757        lappend range_$v [expr {[set max_$v] * 1. / [set step_$v] }]
4758    }
4759    return [list $steps $range_x $range_y $range_z]
4760}
4761
4762# set the Fourier map computation step and limits
4763#   Asteps contains {stepx stepy stepz} : step size in Angstroms
4764#   range_x contains {xmin xmax} : min and max x in fractional coordinates
4765#   range_y contains {ymin ymax} : min and max y in fractional coordinates
4766#   range_z contains {zmin zmax} : min and max z in fractional coordinates
4767proc setFourierLimits {phase \
4768                           {Asteps {.2 .2 .2}} \
4769                           {range_x {0 1}} \
4770                           {range_y {0 1}} \
4771                           {range_z {0 1}} } {
4772    set key "CRS$phase  FMPCTL"
4773    if {![existsexp $key]} {
4774        makeexprec $key
4775    }
4776    set i 1
4777    # steps across map
4778    foreach v {x y z} cell {a b c} As $Asteps {
4779        set s [expr {1 + int([phaseinfo $phase $cell] / $As)}]
4780        set s [expr {$s + ($s % 2)}]
4781        set step_$v $s
4782        lappend steps [set step_$v]
4783        validint s 5
4784        setexp $key $s $i 5
4785        incr i 5
4786    }
4787    # x,y,z min in steps
4788    foreach v {x y z} {
4789        foreach {min max} [set range_$v] {}
4790        set s [expr {int($min * [set step_$v]-.5)}]
4791        validint s 5
4792        setexp $key $s $i 5
4793        incr i 5
4794    }
4795    # x,y,z max in steps
4796    foreach v {x y z} {
4797        foreach {min max} [set range_$v] {}
4798        set s [expr {int($max * [set step_$v]+.5)}]
4799        validint s 5
4800        setexp $key $s $i 5
4801        incr i 5
4802    }
4803}
Note: See TracBrowser for help on using the repository browser.