Example #1
0
def alias_commands(global_namespace_dict):
    """Alias commands left in global_namespace_dict by previous import from
    diffcalc.

    This is the equivalent of diffcmd/ipython/magic_commands() for use
    when IPython is not available
    """
    gnd = global_namespace_dict
    global GLOBAL_NAMESPACE_DICT
    GLOBAL_NAMESPACE_DICT = gnd
    print "Aliasing commands"

    ### Alias commands in namespace ###
    commands = gnd['hkl_commands_for_help']
    commands += gnd['ub_commands_for_help']
    if not GDA:  # TODO: encapsulation issue: this should be done outside this function!
        commands.append(gnd['pos'])
        commands.append(gnd['scan'])
    aliased_names = []

    for f in commands:
        # Skip section headers like 'Motion'
        if not hasattr(f, '__call__'):
            continue

        alias(f.__name__)
        aliased_names.append(f.__name__)

    print "Aliased commands: " + ' '.join(aliased_names)
Example #2
0
def alias_commands(global_namespace_dict):
    """Alias commands left in global_namespace_dict by previous import from
    diffcalc.

    This is the equivalent of diffcmd/ipython/magic_commands() for use
    when IPython is not available
    """
    gnd = global_namespace_dict
    global GLOBAL_NAMESPACE_DICT
    GLOBAL_NAMESPACE_DICT = gnd
    print "Aliasing commands"
    
    ### Alias commands in namespace ###
    commands = gnd['hkl_commands_for_help']
    commands += gnd['ub_commands_for_help']
    if not GDA:  # TODO: encapsulation issue: this should be done outside this function!
        commands.append(gnd['pos'])
        commands.append(gnd['scan'])       
    aliased_names = []

    for f in commands:
        # Skip section headers like 'Motion'
        if not hasattr(f, '__call__'):
            continue
        
        alias(f.__name__)
        aliased_names.append(f.__name__)

    print "Aliased commands: " + ' '.join(aliased_names) 
Example #3
0
def _try_to_alias(command_name):
    try:
        alias(command_name)
    except:
        pass
    if VERBOSE:
        print "   ", command_name
Example #4
0
from gda.jython.commands.GeneralCommands import run, alias  # @UnusedImport
from gdascripts.pd.time_pds import waittimeClass, showtimeClass, showincrementaltimeClass, actualTimeClass
from gdascripts.scan.installStandardScansWithProcessing import *  # @UnusedWildImport
from gdascripts.watchdogs.watchdogs import enable_watchdogs, disable_watchdogs, list_watchdogs  # @UnusedImport
from gdascripts.malcolm.malcolm import reset_malcolm_after_scan

from i08_shared_utilities import is_live, ls_scannables

# Add config/scripts to import search path (why is this not already set in gda9?).
# Also, this seems to be different to run search path... imh 11/11/2016
scriptDir = LocalProperties.get("gda.config") + "/scripts/"
sys.path.append(os.path.abspath(scriptDir))

print("Initialisation Started")

alias("setTitle")
alias("meta_add")
alias("meta_ll")
alias("meta_ls")
alias("meta_rm")

scan_processor.rootNamespaceDict = globals()  # @UndefinedVariable

waittime = waittimeClass('waittime')
showtime = showtimeClass('showtime')
inctime = showincrementaltimeClass('inctime')
actualTime = actualTimeClass("actualTime")

# For access to new mscan mapping scan command.
print(
    "Adding mscan mapping scan command. Use help(mscan) to get information on how to use it."
Example #5
0
'''
Created on 16 Apr 2018

@author: fy65
'''
from gda.jython.commands.ScannableCommands import scan
from gda.jython.commands.GeneralCommands import alias

print "-" * 100
print "creating 'snap' command for capturing a snapshot off a detector:"
print "    Usage example: >>>snap pimte 6.0"


def snap(*args):
    newargs = [ds, 1, 1, 1]  # @UndefinedVariable
    for arg in args:
        newargs.append(arg)
    scan([e for e in newargs])


alias("snap")
'''
This requires GDA 'metashop' object to be defined in Spring configuration on the server as:
<bean id="metashop" class="gda.data.metadata.NXMetaDataProvider" />

Created on 20 Mar 2014

@author: fy65
'''
from gda.jython.commands.GeneralCommands import alias

from gdascripts.metadata.metadata_commands import meta_add, meta_ll, meta_ls, meta_rm  # @UnusedImport
from gda.configuration.properties import LocalProperties

alias("meta_add")
alias("meta_ll")
alias("meta_ls")
alias("meta_rm")
from gda.data.scan.datawriter import NexusDataWriter
LocalProperties.set(NexusDataWriter.GDA_NEXUS_METADATAPROVIDER_NAME,"metashop")
Example #7
0
from gda.jython.commands.GeneralCommands import alias
from gda.mscan import MScanSubmitter
from org.eclipse.scanning.command.Services import *

# Set up lambdas that return the AreaScanpath Enum instances that link to the
# Models and assign them to the corresponding names and standard 4 character
# abbreviations so that they can be protected using alias()

grid = (lambda:AreaScanpath.GRID)()
rast = raster = (lambda:AreaScanpath.RASTER)()
spir = spiral = (lambda:AreaScanpath.SPIRAL)()
liss = lissajous = (lambda:AreaScanpath.LISSAJOUS)()

# Register the commands with the Translator
alias('grid')
alias('rast')
alias('raster')
alias('spir')
alias('spiral')
alias('liss')
alias('lissajous')

# Set up functions that return the Roi Enum instances and assign them to
# the corresponding names and standard 4 character abbreviations so that
# they can be protected using alias()

rect = rectangle = (lambda:Roi.RECTANGLE)()
crec = centred_rectangle = (lambda:Roi.CENTRED_RECTANGLE)()
circ = circle = (lambda:Roi.CIRCLE)()
poly = polygon = (lambda:Roi.POLYGON)()
Example #8
0
    '''enable or disable EPICS feedbacks depending on the energy changes requested
    '''
    if motor is ienergy:  # @UndefinedVariable
        if not moveWithinLimits(float(motor.getPosition()),
                                float(new_position), IENERGY_MOVE_LIMIT):
            dcmfrollfeedback.moveTo("Disabled")
            dcmfpitchfeedback.moveTo("Disabled")
            motor.moveTo(new_position)
            dcmfrollfeedback.moveTo("Enabled")
            dcmfpitchfeedback.moveTo("Enabled")
        else:
            motor.moveTo(new_position)
    elif motor is jenergy:  # @UndefinedVariable
        if not moveWithinLimits(float(motor.getPosition()),
                                float(new_position), JENERGY_MOVE_LIMIT):
            sm1fpitchfeedback.moveTo("Disabled")
            motor.moveTo(new_position)
            sm1fpitchfeedback.moveTo("Enabled")
        else:
            motor.moveTo(new_position)
    else:
        motor.moveTo(new_position)
    print "%s moves completed at %f" % (motor.getName(), motor.getPosition())


try:
    from gda.jython.commands.GeneralCommands import alias
    alias("move")
except:
    pass
Example #9
0
        
 
#    raise Exception('need gda class for wrapping scannables. There is one somewhere')
#     import what_is_its_name as XYZ  # @UnresolvedImport
#     delta = XYZ(diode_tth, 'delta')  # or vessel_tth
#     eta = XYZ(sapolar, 'eta')
#     chi = XYZ(satilt, 'chi', 90)  # chi = satilt + 90deg
#     phi = XYZ(saazimuth, 'phi')
#     
#     def usediode():
#         raise Exception('needs implementing')
#    
#     def usevessel():
#         raise Exception('needs implementing')
    from gda.jython.commands.GeneralCommands import alias  # @UnresolvedImport
    alias("usediode")
    alias("usevessel")
    alias("centresample")
    alias("zerosample")
    alias("toolpoint_on")
    alias("toolpoint_off")

else:
    from diffcalc.gdasupport.minigda.scannable import ScannableAdapter
    from IPython.core.magic import register_line_magic  # @UnresolvedImport
    from diffcmd.ipython import parse_line
#     delta = ScannableAdapter(diodetth, 'delta')  # or vessel_tth
#     eta = ScannableAdapter(sapolar, 'eta')
#     chi = ScannableAdapter(satilt, 'chi', 90)  # chi = satilt + 90deg
#     phi = ScannableAdapter(saazimuth, 'phi')
    
Example #10
0
        synapseHigh = whichSynapseTerminal(args[0])
        synapseHigh.rawAsynchronousMoveTo("Source high")
        synapseLow = whichSynapseTerminal(args[1])
        synapseLow.rawAsynchronousMoveTo("Source low")
        sleep(1)  #ensure above finished before statement below

        generateCurrentPulseFromKeithley(args[2], args[3], args[4] / 2,
                                         args[5])

        synapse_setall.rawAsynchronousMoveTo("STV")
        print "Pulse sweep completed."
    else:
        raise Exception("Number of parameters is wrong, require 6 arguments.")


alias('pulse2')


def pulse4(*args):
    ''' send pulse sweep generated by Keithley 2461 to the sample using 4 contact points via Synapse Switch Box.
    This command takes only 8 input parameters:
        The first 4 parameters defines the contact points in the Synapse Switch Box;
        The last 4 parameters defines pulse sweep to be generated by the Keithley 2461.
    Command syntax:
        pulse source_1_high  source_2_high source_1_low source_2_low current width timeDelay  numberOfPulses
    '''
    if len(args) == 8:
        if len(args[:4]) != len(set(args[:4])):
            raise Exception(
                "Cannot use the same Synapse terminal more than once in this command."
            )
Example #11
0
    objects = {}
    objects['diffcalcdemo'] = DiffcalcDemo(demoCommands)
    _try_to_alias('diffcalcdemo')
    print "=" * 80
    print "Try the following:"
    for line in demoCommands:
        print line
    print
    print ("Or type 'diffcalcdemo' to run this script. "
           "(Caution, will move the diffractometer!)")
    return objects

def override_gda_help_command(global_dict):
    print "Overriding gda's standard help command"
    _gdahelp_orig = global_dict['_gdahelp']  # @UndefinedVariable
    
    def _gdahelp(o=None):
        if o is None:
            _gdahelp_orig(o)
        else:
            try:
                print o.__doc__
            except:
                _gdahelp_orig(o)
    global_dict['_gdahelp'] = _gdahelp

try:
    alias("help")
except NameError:
    pass  # alias command available in the gda Jython environment
    
    def isDetectorAtPosition(self, pixium_z):
        #TODO: need motor Tolerance data here
        return pixium_z is not None and float(pixium_arm_z.getPosition()==float(pixium_z))  # @UndefinedVariable
                
    def getName(self):
        return self.name
    def setName(self, name):
        self.name=name
        
stagedatacollection=StageDataCollection("MS1")
collectDiffractionData=stagedatacollection.processSamples()
moveToSafePosition=stagedatacollection.moveToSafePosition

from gda.jython.commands.GeneralCommands import alias 
alias("collectDiffractionData")
alias("moveToSafePosition")

def createSampleDict(name, cellID, visitID, calibrant='Si', calibrant_x=0, calibrant_y=0, calibrant_exposure=1.0, sample_x_start=None, sample_x_stop=None, sample_x_step=None, sample_y_start=None, sample_y_stop=None, sample_y_step=None, sample_exposure=1.0, pixium_x=None, pixium_y=None, pixium_z=None ):
    sample={}
    sample["name"]=name
    sample["cell_ID"]=cellID
    sample["visit_ID"]=visitID
    sample["calibrant"]=calibrant
    sample["calibrant_x"]=calibrant_x
    sample["calibrant_y"]=calibrant_y
    sample["calibrant_exposure"]=calibrant_exposure
    sample["sample_x_start"]=sample_x_start
    sample["sample_x_stop"]=sample_x_stop
    sample["sample_x_step"]=sample_x_step
    sample["sample_y_start"]=sample_y_start
from gdascripts.scan import specscans
from gdascripts.scan import gdascans

from gda.jython.commands.GeneralCommands import alias
from gda.jython import InterfaceProvider
from gda.scan import ScanDataPointCache

print "Setting up scan data point cache"
scanDataPointCache = ScanDataPointCache()
# Attach to JSF
InterfaceProvider.getScanDataPointProvider().addIScanDataPointObserver(scanDataPointCache)

print "Setting up scan data processor, scan_processor"
scan_processor = ScanDataProcessor([MaxPositionAndValue(), MinPositionAndValue(), CentreOfMass(), GaussianPeakAndBackground() ], globals(), scanDataPointCache=scanDataPointCache)
go = scan_processor.go
alias("go")

print "Creating spec-like commands:"
ascan  = specscans.Ascan([scan_processor])
a2scan = specscans.A2scan([scan_processor])
a3scan = specscans.A3scan([scan_processor])
mesh   = specscans.Mesh([scan_processor])
dscan  = specscans.Dscan([scan_processor])
d2scan = specscans.D2scan([scan_processor])
d3scan = specscans.D3scan([scan_processor])
alias('ascan');print ascan.__doc__.split('\n')[3]
alias('a2scan');print a2scan.__doc__.split('\n')[3]
alias('a3scan');print a3scan.__doc__.split('\n')[3]
alias('mesh');print mesh.__doc__.split('\n')[3]
alias('dscan');print dscan.__doc__.split('\n')[3]
alias('d2scan');print d2scan.__doc__.split('\n')[3]
print "   >>>nwf - return the full path of the next working data file"
print "   >>>nfn - return the next data file number to be collected"
print "   >>>setSubdirectory('test') - change data directory to a sub-directory named 'test', created first if not exist"
print "   >>>getSubdirectory() - return the current sub-directory setting if exist"
print "Please note: users can only create sub-directory within their permitted visit data directory via GDA, not themselves."
print "To create another sub-directory 'child-test' inside a sub-directory 'test', you must specify the full path as 'test/child-test' "
# set up a nice method for getting the latest file path
i11JNumTracker = NumTracker("i11-1");

# function to find the working directory
def pwd():
    '''return the working directory'''
    cwd = PathConstructor.createFromDefaultProperty()
    return cwd
    
alias("pwd")

# function to find the last working file path
def lwf():
    '''return the last working file path root'''
    cwd = PathConstructor.createFromDefaultProperty()
    filenumber = i11JNumTracker.getCurrentFileNumber();
    return os.path.join(cwd,str(filenumber))
    
alias("lwf")

# function to find the next working file path
def nwf():
    '''query the next working file path root'''
    cwd = PathConstructor.createFromDefaultProperty()
    filenumber = i11JNumTracker.getCurrentFileNumber();
# To use this module (from LocalStation.py for example):
# >>> from gdascripts.scannable.installStandardScannableMetadataCollection import * #@UnusedWildImport
# >>> meta.rootNamespaceDict=globals()
# >>> note.rootNamespaceDict=globals()

__all__ = ["meta", "setmeta", "lsmeta", "addmeta", "rmmeta", "note"]

from gdascripts.scannable.metadata import MetadataOneOffNote, MetadataCollector
from gda.jython.commands.GeneralCommands import alias

print """Creating metadata scannable 'meta' and commands 'setmeta', 'lsmeta',
'addmeta','rmmeta'"""
meta = MetadataCollector('meta')
setmeta = meta.set
lsmeta = meta.ls
addmeta = meta.add
rmmeta = meta.rm

alias('note')
alias('setmeta')
alias('lsmeta')
alias('addmeta')
alias('rmmeta')

print "Creating 'note' command"
note = MetadataOneOffNote()
from gdascripts.scan import specscans
from gda.jython.commands.GeneralCommands import alias

ascan  = specscans.Ascan()
a2scan = specscans.A2scan()
a3scan = specscans.A3scan()
mesh   = specscans.Mesh()
dscan  = specscans.Dscan()
d2scan = specscans.D2scan()
d3scan = specscans.D3scan()

alias('ascan');    print ascan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('a2scan');print a2scan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('a3scan');print a3scan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('mesh');print mesh.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('dscan');print dscan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('d2scan');print d2scan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('d3scan');print d3scan.__doc__.split('\nUSAGE:\n\t\n  ')[1]

Example #17
0
			raise
		newparams=(scandim+2)*[0]						#list of zeros of correct length
		steps=[]
		span=self.mult(0,paramlist[0][0])						#scalar or list of zeros of same size as original parameter 
		for i in range(0,2*(scandim-1)+1,2):
#			print 'plist0', paramlist[0][i]
			steps+=[paramlist[0][i]]						#add step vector to list		
			span=self.add(span,self.mult(paramlist[0][i],paramlist[0][i+1]-1))		#add step*n to span of scan

		start=self.add(self.startpos,self.mult(span,-0.5))
		end=self.add(self.startpos,self.mult(span,0.5))
		newparams=2*[0]								#new list with two zeros, to be replaced with...
		newparams[0]=start
		newparams[1]=end
		newparams+=steps
#		print 'steps', steps
#		print 'nerparams', newparams
		paramlist[0]=newparams
		return [devlist, paramlist]

from gda.jython.commands.GeneralCommands import alias
lup=dscan=ScanWrapperDscanReturnToStartClass()
go=dscan.go
alias("go")
ascan=ScanWrapperAscanClass()
scancn=ScanWrapperCscanReturnToStartClass()
alias("dscan")
alias("lup")
alias("ascan")
alias("scancn")
Example #18
0
            ['ca61sr', 'ca62sr', 'ca63sr', 'ca64sr', 'ca65sr', 'ca66sr'])

        beamlineutil.stopArchiving()
        fastEnergy.cvscan(startEnergy, endEnergy, scanTime, pointTime)
        beamlineutil.registerFileForArchiving(beamlineutil.getLastScanFile())
        beamlineutil.restoreArchiving()

        uuu.restoreDefaults()

    except:
        errortype, exception, traceback = sys.exc_info()
        logger.fullLog(None, "Error in zacscan", errortype, exception,
                       traceback, False)


alias("zacscan")


def zacstop():
    try:
        fastEnergy.stop()
        beamlineutil.restoreArchiving()
        InterfaceProvider.getCommandAborter().abortCommands()
    except:
        errortype, exception, traceback = sys.exc_info()
        logger.fullLog(None, "Error in stopping the zacscan ", errortype,
                       exception, traceback, False)


##		if (this.commandserver.getScanStatus() == Jython.RUNNING || this.commandserver.getScanStatus() == Jython.PAUSED) {
##			this.commandserver.haltCurrentScan();
def sumScanRawData(numberofscan, beamenergy=energy, detector=mythen): #@UndefinedVariable
    filenames = []
    for i in range(numberofscan):
        filenames.append(str(detector.getDataDirectory()) + str(os.sep) + str(detector.buildRawFilename(i+1)))
    
    now = datetime.datetime.now()
    photonenergy = int(round(float(beamenergy.getPosition())))
    sum_flat_field_file = PSD_FLATFIELD_DIR + str(os.sep) + "Sum_Flat_Field_E" + str(photonenergy) + "keV_T" + str(photonenergy*1000/2) + "eV_" + now.strftime("%Y%m%d") + ".raw"
    summedfile = open(sum_flat_field_file, "w")
    data = map(read_raw_data, filenames)
    for channel in range(len(data[0])):
        values = [data[i][channel][1] for i in range(len(data))]
        summedfile.write("%d %d\n" % (channel, sum(values)))
    
    summedfile.flush()
    summedfile.close()
    print "Summation completed: Flat Field Calibration file is " + sum_flat_field_file
    return sum_flat_field_file

flatfield=FlatFieldCalibration("flatfield")
alias("faltfield")



    
    
    
    
    
Example #20
0
metadatalist = metadatalist + iddlist + idulist + pgmlist
try:
    #SRS file metadata only works when run in localStation.py - see globals()
    print "-" * 50
    print "SRS or ASCII file metadata command:"
    from gdascripts.scannable.installStandardScannableMetadataCollection import *  # @UnusedWildImport
    meta.rootNamespaceDict = globals()
    note.rootNamespaceDict = globals()

    def stdmeta():
        setmeta_ret = setmeta(*metadatalist)
        print "Standard metadata scannables: " + setmeta_ret

    stdmeta()
    print "    Use 'stdmeta' to reset to standard scannables"
    alias('stdmeta')
    meta.quiet = True
except:
    localStation_exception(sys.exc_info(),
                           "creating SRS file metadata objects")

#Nexus file
print "-" * 50
print "Nexus file metadata commands:"
print "    'meta_add' - add a scannable or scannables to the scan metadata"
print "    'meta_ll'  - list the items and their values to be put into the scan metadata"
print "    'meta_ls'  - list only the items to be put into the scan metadata"
print "    'meta_rm'  - remove a scannable or scannables from the scan metadata"

from metadata.metashop import *  # @UnusedWildImport
meta_add(*metadatalist)
Example #21
0
from cameras.useCameras import camerac1, camerac2
prf = PeemRefocusingClass('PeemRefocusing', camerac1, None, None, u4m,
                          camerac2, u1m, u2m, u3m)
# @UndefinedVariable - Spring beans


def calibration(d_yag=2):
    result = prf.calibration(d_yag)
    sleep(5)
    #centre()
    print("Type prf.save_parameters() to save the parameters.")
    print("Type prf.load_parameters() to load the parameters.")
    return result


def findbeam():
    return prf.tracking()


def centre():
    return prf.centre_cam2()


alias("calibration")
alias("findbeam")
alias("centre")

print("-> Find peak calibration parameters loaded. ")
print("-> Activate camerac1 and type findbeam.")
prf.loadParameters()
Example #22
0
    peemline.setSubDir("")


def getVisit():
    return peemline.getVisit()


def getvisit():
    return peemline.getVisit()


def setDir(newSubDir):
    peemline.setSubDir(newSubDir)


def setdir(newSubDir):
    peemline.setSubDir(newSubDir)


alias("lastscan")
alias("getTitle")
alias("gettitle")
alias("setTitle")
alias("settitle")
alias("getVisit")
alias("getvisit")
alias("setVisit")
alias("setvisit")
alias("setDir")
alias("setdir")
Example #23
0
    andorGV12 = SwitchableHardwareTriggerableProcessingDetectorWrapper(
        'andorGV12',
        andor1GV12det,
        None,
        andor1GV12det_for_snaps, [],
        panel_name=None,
        panel_name_rcp='Plot 1',
        toreplace=None,
        replacement=None,
        iFileLoader=TIFFImageLoader,
        fileLoadTimout=15,
        returnPathAsImageNumberOnly=True)

    def andorGV12openDelay(t_seconds=None):
        """Get or set the shutter close delay (in seconds) for the andor"""
        if t_seconds == None:
            return andor1GV12det.getCollectionStrategy().getShutterOpenDelay()
        andor1GV12det.getCollectionStrategy().setShutterOpenDelay(t_seconds)

    def andorGV12closeDelay(t_seconds=None):
        """Get or set the shutter close delay (in seconds) for the andor"""
        if t_seconds == None:
            return andor1GV12det.getCollectionStrategy().getShutterCloseDelay()
        andor1GV12det.getCollectionStrategy().setShutterCloseDelay(t_seconds)

    alias('andorGV12openDelay')
    alias('andorGV12closeDelay')

except:
    localStation_exception(sys.exc_info(),
                           "creating andor & andorGV12 objects")
Example #24
0
@author: fy65
'''
from gda.configuration.properties import LocalProperties
from gda.jython.commands.GeneralCommands import alias

print "-" * 100
print "Create data file format commands:"
print "    1. 'nexusformat' - switch to write Nexus data file. This is GDA default data file format."
print "    2. 'asciiformat' - switch to write ASCII data file. This format is being deprecated!"
print "    3. 'whichformat' - query which data file format is set in GDA currently."


def nexusformat():
    LocalProperties.set(LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT,
                        "NexusDataWriter")


def asciiformat():
    LocalProperties.set(LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT,
                        "SrsDataFile")


def whichformat():
    return LocalProperties.get(
        LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT)


alias("nexusformat")
alias("asciiformat")
alias("whichformat")
Example #25
0
'''
This requires GDA 'metashop' object to be defined in Spring configuration on the server as:
<bean id="metashop" class="gda.data.metadata.NXMetaDataProvider" />

Created on 25 Feb 2021

@author: svz41317
'''
from gda.jython.commands.GeneralCommands import alias

from gdascripts.metadata.metadata_commands import meta_add, meta_ll, meta_ls, meta_rm, meta_clear_alldynamical  # @UnusedImport
from gda.configuration.properties import LocalProperties

alias("meta_add")
alias("meta_ll")
alias("meta_ls")
alias("meta_rm")
from gda.data.scan.datawriter import NexusDataWriter
LocalProperties.set(NexusDataWriter.GDA_NEXUS_METADATAPROVIDER_NAME,
                    "metashop")
Example #26
0
            #check if there is enough time for the cvscan before topup
            scanTime = abs((stop - start) / step * dwell[0])
            topup_checker = beam_checker.getDelegate().getGroupMember(
                "checktopup_time_cv")
            topup_checker.minimumThreshold = scanTime + 5
            #         print "topup_checker.minimumThreshold = %r" % (topup_checker.minimumThreshold)
            newargs.append(beam_checker)

        trajectory_controller_helper.energy = c_energy
        trajectory_controller_helper.wfs = wfs
        cvscan_traj([e for e in newargs])
    except:
        localStation_exception(sys.exc_info(), "cvscan exits with Error.")


alias('cvscan')

print "Creating I10 GDA 'cvscan2' commands: - ensure dwell time is applied all waveform scannables individually!"


def cvscan2(c_energy, start, stop, step, *args):
    ''' cvscan that applies dwell time to all instances of WaveformChannelScannable.
        This will make sure all the waveform channel scannable data are polled at the same rate.
    '''
    wfs = []
    dwell = []
    others = []
    beam_checker = None
    newargs = [c_energy, start, stop, step]
    try:
        for arg in args:
Example #27
0
            motor.asynchronousMoveTo(new_position)
            print "%s starts to move" % (motor.getName())
    elif motor is delta:  #@UndefinedVariable
        if abs(float(tth.getPosition()) - MAC_SAFE_POSITION
               ) > MAC_SAFE_POSITION_TOLERANCE:  #@UndefinedVariable
            raise UnsafeOperationException(
                float(tth.getPosition()), MAC_SAFE_POSITION,
                "Cannot proceed as MAC detector is not at safe position."
            )  #@UndefinedVariable
        else:
            motor.asynchronousMoveTo(new_position)
            print "%s starts to move" % (motor.getName())


from gda.jython.commands.GeneralCommands import alias
alias("move")
alias("asynmove")


#
class UnsafeOperation(Exception):
    ''' Raised when an operation attempts to move a motor to positions that's not allowed.

    Attributes:
        prev -- position at the beginning of motion
        next -- attempted new position
        msg  -- explanation of why the specific transition is not allowed
    '''
    def __init__(self, prev, next, msg):
        self.prev = prev
        self.next = next
Example #28
0
        if not isinstance(rp, tuple):
            result = False
        else:
            for stp in rp:
                if not isinstance(stp, list):
                    result = False
                    break
                elif len(stp) != 3:
                    result = False
                    break

        return result


def isScannable(obj):
    return isinstance(obj, (ScannableMotionBase, ScannableBase, Scannable))


#Usage
myscan = MyScanClass()
alias('myscan')

#The following three ways to run the scan command:
#myscan(*[testMotor1 0 10 1 dummyCounter1 0.1])
#myscan(testMotor1, 0, 10, 1, dummyCounter1, 0.1)
#myscan testMotor1 0 10 1 dummyCounter1 0.1

#myscan testMotor1 0 10 1 dummyCounter1 0.1

#myscan testMotor1 ([0, 5, 1], [6,10,0.1], [10,15,1]) dummyCounter1 0.1
Example #29
0
    collectionNumber = 0
    try:
        for t1 in frange(starttime, stoptime, gatewidth):
            # print t1
            voltage.resetCounter()
            voltage.setCollectionNumber(collectionNumber)
            electrometer.resetCounter()
            electrometer.setCollectionNumber(collectionNumber)
            print "move event receiver to delay=%s width=%s" % (t1 - starttime, gatewidth)
            evr.moveTo([t1 - starttime, gatewidth])
            mythen.gated(nf, ng, scanNumber, mythen.getDataDirectory(), collectionNumber)
            collectionNumber += 1
            # print "end loop"
            interruptable()
    except:
        raise
    finally:
        print "end loop"
        voltage.removeMonitor()
        electrometer.removeMonitor()
    # clearup
    # voltage.removeMonitor()
    # electrometer.removeMonitor()
    # stop ramp output
    fg.setOutput(0)
    print "scan completed."


# to support syntax: pescan 20 50 0.1 mythen ng nf
alias("pescan")
Example #30
0
from gda.jython.commands.GeneralCommands import alias

from Diamond.Scans.RegionalScan import RegionalScanClass
"""
from Diamond.Scans.CentroidScan import CentroidScanClass
"""

#Usage:
print "-"*100
print "Use mrscan motor (R1, R2, ... R3) for multiple-region scan"
print "where Rx is defined by a [start, stop, step] list"
print "For example:"
print "    mrscan testMotor1 ([0, 5, 1], [6,10,0.1], [10,15,1]) dummyCounter1 0.1"
print "Note that if there is only one region, a comma at the end of tuple is necessary:"
print "For example:"
print "    mrscan testMotor1 ([0, 5, 1],) dummyCounter1 0.1"

#Usage
mrscan=RegionalScanClass()
alias('mrscan');
"""
del cscan
cscan=CentroidScanClass()
alias('cscan');
#Usage:
#print "Use cscan motor centre width step for centroid scan"
"""
Example #31
0
from gda.jython.commands.GeneralCommands import alias
from gda.mscan import MScanSubmitter
from org.eclipse.scanning.command.Services import *

# Set up lambdas that return the AreaScanpath Enum instances that link to the
# Models and assign them to the corresponding names and standard 4 character
# abbreviations so that they can be protected using alias()

grid = (lambda: AreaScanpath.GRID)()
rast = raster = (lambda: AreaScanpath.RASTER)()
spir = spiral = (lambda: AreaScanpath.SPIRAL)()
liss = lissajous = (lambda: AreaScanpath.LISSAJOUS)()

# Register the commands with the Translator
alias('grid')
alias('rast')
alias('raster')
alias('spir')
alias('spiral')
alias('liss')
alias('lissajous')

# Set up functions that return the Roi Enum instances and assign them to
# the corresponding names and standard 4 character abbreviations so that
# they can be protected using alias()

rect = rectangle = (lambda: Roi.RECTANGLE)()
crec = centred_rectangle = (lambda: Roi.CENTRED_RECTANGLE)()
circ = circle = (lambda: Roi.CIRCLE)()
poly = polygon = (lambda: Roi.POLYGON)()
Example #32
0
        return self.center(self.cam2, self.cam2x, self.cam2y, pixelSize)

        
prf=PeemRefocusingClass('PeemRefocusing', campeem, yagx, yagy, camc2, c2x, c2y);

#prf.calibration();
#prf.saveParameters();
#prf.loadParameters();
#prf.tracking();

def cali(dYag):
    result = prf.calibration(dYag);
    sleep(5)
    #centre()
    print "Type prf.saveParameters() to save the parameters."
    print "Type prf.loadParameters() to load the parameters."
    return result;


def beam():
    return prf.tracking();

def centre():
    return prf.centreCam2();

alias("cali")
alias("beam")
alias("centre")


Example #33
0
'''
Created on 1 Mar 2018

@author: fy65
'''
from gda.configuration.properties import LocalProperties
from gda.jython.commands.GeneralCommands import alias

def nexusformat():
    LocalProperties.set(LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT, "NexusDataWriter")
    
def acsiiformat():
    LocalProperties.set(LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT, "SrsDataFile")

def whichformat():
    return LocalProperties.get(LocalProperties.GDA_DATA_SCAN_DATAWRITER_DATAFORMAT)

alias("nexusformat")
alias("acsiiformat")
alias("whichformat")
Example #34
0
from gdascripts.analysis.datasetprocessor.oned.GaussianPeakAndBackground import GaussianPeakAndBackground
from gdascripts.scan.process.ScanDataProcessor import ScanDataProcessor
from gdascripts.scan.process.ScanDataProcessorResult import go
from gdascripts.scan import specscans
from gdascripts.scan import gdascans

from gda.jython.commands.GeneralCommands import alias

print "Setting up scan data processor, scan_processor"
scan_processor = ScanDataProcessor([
    MaxPositionAndValue(),
    MinPositionAndValue(),
    CentreOfMass(),
    GaussianPeakAndBackground()
], globals())
alias("go")

print "Creating scan commands:"
ascan = specscans.Ascan([scan_processor])
a2scan = specscans.A2scan([scan_processor])
a3scan = specscans.A3scan([scan_processor])
mesh = specscans.Mesh([scan_processor])
dscan = specscans.Dscan([scan_processor])
d2scan = specscans.D2scan([scan_processor])
d3scan = specscans.D3scan([scan_processor])
scan = gdascans.Scan([scan_processor])
rscan = gdascans.Rscan([scan_processor])
alias('ascan')
print ascan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
alias('a2scan')
print a2scan.__doc__.split('\nUSAGE:\n\t\n  ')[1]
Example #35
0
                    if type(args[i]) == IntType and (
                            type(args[i + 1]) == IntType
                            or type(args[i + 1]) == FloatType):
                        #support the miscan command - first input after detector is number of images per data point
                        decoratee.setNumberOfImagesPerCollection(args[i])
                    elif type(args[i]) == FloatType and (
                            type(args[i + 1]) == IntType
                            or type(args[i + 1]) == FloatType):
                        raise TypeError, "Number of images to collect per scan data point must be Int type."
                    elif type(args[i]) == FloatType and not (
                            type(args[i + 1]) == IntType
                            or type(args[i + 1]) == FloatType):
                        decoratee.setNumberOfImagesPerCollection(1)
                elif i == len(
                        args
                ) - 1:  #followed by only one argument - must be exposure time
                    decoratee.setNumberOfImagesPerCollection(1)

            else:  #exposure time is the last one in the scan command
                newargs.append(args[i])  #single image per data point
            i = i + 1
    scan([e for e in newargs])

    if PRINTTIME:
        print("=== Scan ended: " + time.ctime() +
              ". Elapsed time: %.0f seconds" % (time.time() - starttime))


from gda.jython.commands.GeneralCommands import alias
alias("miscan")
Example #36
0
            [0])  #scalar or list of zeros of same size as original parameter
        for i in range(0, 2 * (scandim - 1) + 1, 2):
            #			print 'plist0', paramlist[0][i]
            steps += [paramlist[0][i]]  #add step vector to list
            span = self.add(span,
                            self.mult(paramlist[0][i], paramlist[0][i + 1] -
                                      1))  #add step*n to span of scan

        start = self.add(self.startpos, self.mult(span, -0.5))
        end = self.add(self.startpos, self.mult(span, 0.5))
        newparams = 2 * [0]  #new list with two zeros, to be replaced with...
        newparams[0] = start
        newparams[1] = end
        newparams += steps
        #		print 'steps', steps
        #		print 'nerparams', newparams
        paramlist[0] = newparams
        return [devlist, paramlist]


from gda.jython.commands.GeneralCommands import alias
lup = dscan = ScanWrapperDscanReturnToStartClass()
go = dscan.go
alias("go")
ascan = ScanWrapperAscanClass()
scancn = ScanWrapperCscanReturnToStartClass()
alias("dscan")
alias("lup")
alias("ascan")
alias("scancn")
def asynmove(motor, new_position):
    if motor is tth: #@UndefinedVariable
        if abs(float(delta.getPosition()) - PSD_SAFE_POSITION) > PSD_SAFE_POSITION_TOLERANCE: #@UndefinedVariable
            raise UnsafeOperationException(float(delta.getPosition()), PSD_SAFE_POSITION, "Cannot proceed as PSD detector is not at safe position.") #@UndefinedVariable
        else:
            motor.asynchronousMoveTo(new_position)
            print "%s starts to move" % (motor.getName())
    elif motor is delta: #@UndefinedVariable
        if abs(float(tth.getPosition()) - MAC_SAFE_POSITION) > MAC_SAFE_POSITION_TOLERANCE: #@UndefinedVariable
            raise UnsafeOperationException(float(tth.getPosition()),MAC_SAFE_POSITION, "Cannot proceed as MAC detector is not at safe position.") #@UndefinedVariable
        else:
            motor.asynchronousMoveTo(new_position)
            print "%s starts to move" % (motor.getName())

from gda.jython.commands.GeneralCommands import alias         
alias("move")
alias("asynmove")
#
class UnsafeOperation(Exception):
    ''' Raised when an operation attempts to move a motor to positions that's not allowed.
    
    Attributes:
        prev -- position at the beginning of motion
        next -- attempted new position
        msg  -- explanation of why the specific transition is not allowed
    '''
    def __init__(self, prev, next, msg):
        self.prev = prev
        self.next = next
        self.msg = msg
        
print "   >>>nwf - return the full path of the next working data file"
print "   >>>nfn - return the next data file number to be collected"
print "   >>>setSubdirectory('test') - change data directory to a sub-directory named 'test', created first if not exist"
print "   >>>getSubdirectory() - return the current sub-directory setting if exist"
print "Please note: users can only create sub-directory within their permitted visit data directory via GDA, not themselves."
print "To create another sub-directory 'child-test' inside a sub-directory 'test', you must specify the full path as 'test/child-test' "
# set up a nice method for getting the latest file path
i11NumTracker = NumTracker("i11");

# function to find the working directory
def pwd():
    '''return the working directory'''
    cwd = PathConstructor.createFromDefaultProperty()
    return cwd
    
alias("pwd")

# function to find the last working file path
def lwf():
    '''return the last working file path root'''
    cwd = PathConstructor.createFromDefaultProperty()
    filenumber = i11NumTracker.getCurrentFileNumber();
    return os.path.join(cwd,str(filenumber))
    
alias("lwf")

# function to find the next working file path
def nwf():
    '''query the next working file path root'''
    cwd = PathConstructor.createFromDefaultProperty()
    filenumber = i11NumTracker.getCurrentFileNumber();
Example #39
0
                #print t1
                peobject.reset()                             # reset the gate counter
                print "move event receiver to delay=%s width=%s" % (t1-starttime, gatewidth)
                evr.moveTo([t1-starttime,gatewidth])
                print "start mythen %d" % time()
                pos fastshutter "OPEN"
                mythen.gated(nf, ng, scanNumber, collectionNumber)  # block until all frames and gates are collected
                pos fastshutter "CLOSE"
                collectionNumber += 1
                peobject.save(collectionNumber)
                interruptable()                                     # allow "StopAll" to work
    except:
        raise
    finally:
        print "collection completed at %d" % time()
        peobject.removeMonitor()        # ensure monitor removed
        pestop()
 
    #stop ramp output
    fg2.setOutput(0)
    fg1.setOutput(0)
    
def pestop():
    #stop ramp output
    fg2.setOutput(0)
    fg1.setOutput(0)
   
# to support syntax: pescan 20 50 0.1 mythen ng nf
alias("pescan")
alias("peloop")
Example #40
0
    '''
    plotdata(filename, datatype, panelname, False)

def plotover(datatype, filename, panelname="DataPlot"):
    ''' Plot collected data on top of existing lines in the Graph.
        command syntax:
            plotover datatype filename [panelname]
        function syntax:
            plotover(datatype, filename, [panelname])
        where:
            datatype can be MAC or PSD (in capitals)
            filename must be file name string in quote or absolute file path or URL to the data file (must be quoted)
    '''
    plotdata(filename, datatype, panelname, True)

alias("plot")   
alias("plotover")   

def plotdata(filename, dataType=MAC, plotPane="DataPlot", Overlay=True):
    '''Plot existing data on "MAC, PSD", or "SRS" (if any) Panel, the default is MAC data on DataPlot panel and overlay is True.
       
       syntax:
               plotdata(filename,[MAC|SRS|PSD],["MAC"|"Mythen"|"DataPlot"],[True|False])
       
               where:
                    filename: the filename string in quote. 
                
                    dataType: the input data types or formats available
		                MAC - plot MAC data on MAC panel
		                PSD - plot PSD data on Mythen panel
		                SRS - plot SRS data on SRS panel
Example #41
0
###############################################################################

print "-----------------------------------------------------------------------------------------------------------------"
print "create directory operation commands: "
i09NumTracker = NumTracker("i09")
print "    pwd : present working directory;"


# function to find the working directory
def pwd():
    '''return the current working directory'''
    curdir = InterfaceProvider.getPathConstructor().createFromDefaultProperty()
    return curdir


alias("pwd")
print "    lwf : last working file path;"


# function to find the last working file path
def lwf():
    '''return the absolute path of the last working file'''
    curdir = InterfaceProvider.getPathConstructor().createFromDefaultProperty()
    filenumber = i09NumTracker.getCurrentFileNumber()
    return os.path.join(curdir, str(filenumber))


alias("lwf")
print "    nwf : next working file path;"

Example #42
0
        print self.exposuretime
        pathPositions=tuple(self.path)
        print pathPositions
        scan([self.sg, pathPositions, self.detector, exposureTime])
            
    def setName(self, name):
        self.name=name
        
    def getName(self):
        return self.name

scanPath=PathScan("pathscan", detectorToUse=edxd) #@UndefinedVariable
    
def pathscan(startpoint, stoppoint, pathfile, detector, exposureTime):
    ''' Scan following a defined path in a specified file from start point to end point, collect data at each point for the specified time.'''
    scanPath.read_scan_path(pathfile)
    if startpoint<scanPath.getStartPoint() or startpoint > scanPath.getStopPoint():
        raise ValueError("start point ID is out of the range specified in the path file: " + pathfile)
    scanPath.setStartPoint(startpoint)
    if stoppoint>scanPath.getStopPoint() or startpoint < scanPath.getStartPoint():
        raise ValueError("Stop point ID is out of the range specified in the path file: " + pathfile)
    scanPath.setStopPoint(stoppoint)
    scanPath.setDetector(detector)
    pathSelected=scanPath.getPath()[startpoint:stoppoint+1]
    scanPath.setPath(pathSelected)
    pointsSelected=scanPath.getPointIDs()[startpoint:stoppoint+1]
    scanPath.setPointIDs(pointsSelected)
    scanPath.startScan(pathfile, exposureTime)
    
alias("pathscan")
Example #43
0
        __main__.en=Dummy("en")
        print "Set energy to 12398.425 eV in simulation mode!"
        __main__.en(12398.425) #1 Angstrom wavelength @UndefinedVariable
        print "Switch to simulation motors"
        swithMotors(simtth,simalpha,simth,simchi,phi)
        setLimitsAndCuts(simtth,simalpha,simth,simchi,phi)
        
    def realdc():
        ''' switch to use real motors in diffcalc
        '''
        print "Stop simulation motors"
        stopMotors(simtth,simalpha,simth,simchi,phi)
        
        global SIM_MODE
        SIM_MODE=False
        import __main__
        print "Set energy to current beamline energy in real mode!"
        __main__.en=pgm_energy
        print "Switch to real motors"
        swithMotors(tth,th,chi,phi)
        setLimitsAndCuts(tth,th,chi,phi)
     
    from gda.jython.commands.GeneralCommands import alias  # @UnresolvedImport
    print "Created commands: 'simdc' and 'realdc' to switch between real and simulated motors."
    alias("simdc")
    alias("realdc")

### Demo ###
if not GDA:
    demo = demo = startup._demo.Demo(globals(), 'fourc')
Example #44
0
## ncdgridscan=gridscan.Grid("Camera View", "Mapping Grid", mfgige, gridxy, ncddetectors)
## ncdgridscan.snap()
from ncdutils import DetectorMeta, DetectorMetaString
waxs_distance = DetectorMeta("waxs_distance", ncddetectors, "WAXS", "distance",
                             "m")
saxs_distance = DetectorMeta("saxs_distance", ncddetectors, "SAXS", "distance",
                             "m")
saxs_centre_x = DetectorMeta("saxs_centre_x", ncddetectors, "SAXS",
                             "beam_center_x")
saxs_centre_y = DetectorMeta("saxs_centre_y", ncddetectors, "SAXS",
                             "beam_center_y")
saxs_mask = DetectorMetaString('saxs_mask', ncddetectors, 'SAXS', 'maskFile')

import metadatatweaks
getTitle = metadatatweaks.getTitle
alias("getTitle")
setTitle = metadatatweaks.setTitle
alias("setTitle")
getSubdirectory = metadatatweaks.getSubdirectory
alias("getSubdirectory")
setSubdirectory = metadatatweaks.setSubdirectory
alias("setSubdirectory")
getVisit = metadatatweaks.getVisit
alias("getVisit")
setVisit = metadatatweaks.setVisit
alias("setVisit")

import uk.ac.gda.server.ncd.config.DeviceLister
import gda.util.ElogEntry
device_list_html = uk.ac.gda.server.ncd.config.DeviceLister.generateDeviceListHTML(
)
Example #45
0
#                 newargs.append( PositionReader(arg) ) # to read the actual position
                i = i + 4
        else:
            newargs.append(arg)
            i = i + 1
            if isinstance(arg, Detector):
                if i < len(args) and (type(args[i]) == IntType
                                      or type(args[i]) == FloatType):
                    #detector has exposure time set so need to adjust motor speed to match number of of points
                    totalTime = float(args[i]) * numberSteps
                    motorSpeed = math.fabs(
                        (float(stoppos - startpos)) / float(totalTime))
                    maxSpeed = flyscannablewraper.getScannableMaxSpeed()
                    if motorSpeed > 0 and motorSpeed <= maxSpeed:
                        #when exposure time is too large, change motor speed to roughly match
                        flyscannablewraper.setSpeed(motorSpeed)
                    elif motorSpeed > maxSpeed:
                        #when exposure time is small enough use maximum speed of the motor
                        flyscannablewraper.setSpeed(maxSpeed)

    gda.jython.commands.ScannableCommands.scan([e for e in newargs])


def flyscannable(scannable, timeout_secs=1.):
    return FlyScannable(scannable, timeout_secs)


from gda.jython.commands.GeneralCommands import alias

alias('flyscan')
Example #46
0
    filenumber = numTracker.getCurrentFileNumber()
    return filenumber + 1


# the subdirectory parts
def setSubdirectory(dirname):
    '''create a new sub-directory under current data directory for data collection that follows'''
    if os.sep not in dirname:
        subdirectory = getSubdirectory()
        if subdirectory:
            dirname = str(subdirectory) + os.sep + str(dirname)
    Finder.find("GDAMetadata").setMetadataValue("subdirectory", dirname)
    try:
        os.mkdir(pwd())
    except:
        exceptionType, exception = sys.exc_info()[:2]
        print "Error Type: ", exceptionType
        print "Error value: ", exception


def getSubdirectory():
    return Finder.find("GDAMetadata").getMetadataValue("subdirectory")


alias("pwd")
alias("lwf")
alias("nwf")
alias("nfn")
alias("setSubdirectory")
alias("getSubdirectory")
from gdascripts.scan.process.ScanDataProcessor import ScanDataProcessor
from gdascripts.scan import specscans
from gdascripts.scan import gdascans

from gda.jython.commands.GeneralCommands import alias

print "Setting up scan data processor, scan_processor"
ge=GaussianEdge()
ge.smoothwidth=5
ge.plotPanel = "Edge Fit Plot"

gpab = GaussianPeakAndBackground()
gpab.plotPanel = "Peak Fit Plot"
scan_processor = ScanDataProcessor( [MaxPositionAndValue(),MinPositionAndValue(),CentreOfMass(), gpab, ge ], globals() )
go = scan_processor.go
alias("go")

print "Creating spec-like commands:"
ascan  = specscans.Ascan([scan_processor])
#a2scan = specscans.A2scan([scan_processor])
#a3scan = specscans.A3scan([scan_processor])
#mesh   = specscans.Mesh([scan_processor])
#dscan  = specscans.Dscan([scan_processor])
#d2scan = specscans.D2scan([scan_processor])
#d3scan = specscans.D3scan([scan_processor])
alias('ascan');print ascan.__doc__.split('\n')[3]
#alias('a2scan');print a2scan.__doc__.split('\n')[3]
#alias('a3scan');print a3scan.__doc__.split('\n')[3]
#alias('mesh');print mesh.__doc__.split('\n')[3]
#alias('dscan');print dscan.__doc__.split('\n')[3]
#alias('d2scan');print d2scan.__doc__.split('\n')[3]