Example #1
0
    def __init__(self, repo_dir, inner_size, do_transforms=True, rgb=True,
                 multiview=False, set_name='train', subset_pct=100, shared_objs=None):
        super(ImgServer, self).__init__(repo_dir, inner_size, do_transforms,
                                        rgb, multiview, set_name, subset_pct)
        assert(shared_objs is not None)
        libpath = os.path.dirname(os.path.realpath(__file__))
        try:
            self._i1klib = ct.cdll.LoadLibrary(os.path.join(libpath,
                                                            'imageset_decoder.so'))
        except:
            logger.error("Unable to load imageset_decoder.so.  Ensure that "
                         "this file has been compiled")
        (self.request, self.response) = shared_objs

        self.worker = self._i1klib.create_data_worker(ct.c_int(self.img_size),
                                                      ct.c_int(self.inner_size),
                                                      ct.c_bool(self.center),
                                                      ct.c_bool(self.flip),
                                                      ct.c_bool(self.rgb),
                                                      ct.c_bool(self.multiview),
                                                      ct.c_int(self.minibatch_size),
                                                      ct.c_char_p(self.filename),
                                                      ct.c_int(self.macro_start),
                                                      ct.c_uint(self.ndata))

        def decode_minibatch(bufobj):
            self._i1klib.process_next_minibatch(self.worker, ct.POINTER(ct.c_ubyte)(bufobj))
        self.decode_minibatch = decode_minibatch
Example #2
0
def prepare_MFO_args(
    nAuthMode, szPass1,
    bTimeLimit, tStartTimeW, tEndTimeW,
    bTimesLimit, nTimes, nRight, szKey1,
    szSrcFile1, nFileCount, szExeDstFile1
):
    '''
    Take care of ctypes type for each arguments.
    Call this before make call to MakeFileOut().
    Read the original doc for FileOutDll.dll to see detailed usage.
    '''
    files = ((ctypes.c_wchar * 256) * 250)()
    for i in xrange(len(szSrcFile1)):
        files[i].value = unicode(szSrcFile1[i])
    return (
        ctypes.c_int(nAuthMode),
        ctypes.c_wchar_p(unicode(szPass1)),
        ctypes.c_bool(bTimeLimit),
        ctypes.c_wchar_p(unicode(tStartTimeW)),
        ctypes.c_wchar_p(unicode(tEndTimeW)),
        ctypes.c_bool(bTimesLimit),
        ctypes.c_int(nTimes),
        ctypes.c_int(nRight),
        ctypes.c_wchar_p(szKey1),
        files,
        ctypes.c_int(nFileCount),
        ctypes.c_wchar_p(unicode(szExeDstFile1))
    )
 def __init__(self, rf_freq, rf_dur):
     # Constants corresponding to various NI options, defined with c_types
     vi = c_int(1)
     o1 = c_int(1)
     o2 = c_int(101)
     o3 = c_int(1000000 + 150000 + 219)
     o4 = c_double(0)
     length = len(rf_freq)
     # Loading the driver to call niFgen functions
     try:
         self.nfg = windll.LoadLibrary("niFgen_32.dll")
     except OSError:
         self.nfg = windll.LoadLibrary("niFgen_64.dll")
     # The way to initialize niFgen can be found in NI examples
     # It is copy/past from that, only translated into c_types
     self.nfg.niFgen_init(b'Dev3', c_bool(1), c_bool(1), byref(vi))
     self.nfg.niFgen_ConfigureChannels(vi, b"0")
     self.nfg.niFgen_ConfigureOutputMode(vi, o2)
     # This is the way to convert numpy array into C array
     rff = rf_freq.ctypes.data
     rfd = rf_dur.ctypes.data
     rf = c_int(0)
     self.nfg.niFgen_CreateFreqList(vi, o1, length, rff, rfd, byref(rf))
     self.nfg.niFgen_ConfigureFreqList(vi, b"0", rf, c_double(4), o4,  o4)
     self.nfg.niFgen_ConfigureDigitalEdgeStartTrigger(vi, b"PFI1", o2)
     self.nfg.niFgen_ConfigureTriggerMode(vi, b"0", c_int(2))
     self.nfg.niFgen_ConfigureOutputEnabled(vi, b"0", c_bool(1))
     # These two lines export the internal clock of the niFgen (100 MHz)
     # divided by 400 (250 kHz) on the RTSI1 channel. It's the only way
     # to be sure that all cards are synchronized on the same clock
     self.nfg.niFgen_SetAttributeViInt32(vi, b"", o3, c_long(400))
     self.nfg.niFgen_ExportSignal(vi, o2, b"", b"RTSI1")
     # self.niFgen.niFgen_ExportSignal(vi, c_int(1000 + 4), b"", b"RTSI2")
     self.nfg.niFgen_Commit(vi)
     self.vi = vi
Example #4
0
 def runApp(self):
     self.getter.start()
     getpid=self.getter.pid
     procget=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(getpid))
     kernel.SetPriorityClass(procget, 0x0100)
     self.processer.start()
     procpid=self.processer.pid
     procproc=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(procpid))
     kernel.SetPriorityClass(procproc, 0x0100)
     data_dict=dict({"F3":[], "F4":[], "T7":[], "T8":[]})
     try:
         while self.getter.is_alive():
             data=self.q.recv()
             #print(data)
             for i in data_dict:
                 data_dict[i].append(data[i][0][2])
             if len(data_dict["F3"])==24:
                 for i in data_dict:
                     del data_dict[i][0]
                 jj=self.livedataclass.test_classifiers_ret(data_dict)
                 if jj>=0.85:
                     print("You moved")
                     print(jj)
                 #print(data_dict)
                 
             print(time.time())
             self.system_up_time+=16/128
     except:
         self.getter.terminate()
         self.processer.terminate()
         raise
Example #5
0
def modsub(model, vis, outvis='', datacolumn='corrected', primarybeam='guess', subtract=True, use_cuda=False, field = None):
    import shutil
    import os

    if outvis != '':
        if not os.access(outvis, os.F_OK):
            shutil.copytree(vis, outvis)


# primary beam
    if primarybeam == 'guess':
        primarybeam = stacker.pb.guesspb(vis)
    elif primarybeam in ['constant', 'none'] or primarybeam is None:
        primarybeam = stacker.pb.PrimaryBeamModel()
    pbtype, pbfile, pbnpars, pbpars = primarybeam.cdata()

    if field is not None:
        select_field = True
        field = str(field)
    else:
        select_field = False
        field = ''

    infiletype, infilename, infileoptions = stacker._checkfile(vis, datacolumn)
    outfiletype, outfilename, outfileoptions = stacker._checkfile(outvis, datacolumn)

    flux = c_modsub(infiletype, c_char_p(infilename), infileoptions,
                    outfiletype, c_char_p(outfilename), outfileoptions,
                    c_char_p(model), 
                    pbtype, c_char_p(pbfile), pbpars, pbnpars,
                    c_bool(subtract), c_bool(use_cuda),
                    c_bool(select_field), c_char_p(field))
    return 0
Example #6
0
def QueryColorFilterPosition():
    """determine the current color filter position for slider cameras which support this
    capability. Returns a tuple for the Color and B/W position"""
    FilterIn = ctypes.c_bool()
    FilterOut = ctypes.c_bool()
    _QueryColorFilterPosition(byref(FilterIn), byref(FilterOut))
    return FilterIn.value, FilterOut.value
def togglePhySimIter(lowLevelToggleSeq):
    libMbus = ctypes.cdll.LoadLibrary(libSoName)
    mbusPhy = MbusPhyStruct()
    byteMemSize = 64
    rxByteMem = (ctypes.c_byte * byteMemSize)()
    txByteMem = (ctypes.c_byte * byteMemSize)()
    libMbus.mbus_phy_init(ctypes.byref(mbusPhy),
                          ctypes.byref(rxByteMem),
                          ctypes.c_size_t(byteMemSize),
                          ctypes.byref(txByteMem),
                          ctypes.c_size_t(byteMemSize),
                          )
    libMbus.mbus_phy_rx_enable(ctypes.byref(mbusPhy))
    rxNibList = nibbles.MbusRawNibbleList(mbusTimeFormat="blank")
    driveMbusPinLo = ctypes.c_bool()
    for lowLevelToggle in lowLevelToggleSeq:
        libMbus.mbus_phy_update(ctypes.byref(mbusPhy),
                                ctypes.c_ulong(lowLevelToggle[1]),
                                ctypes.c_bool(lowLevelToggle[0]),
                                ctypes.byref(driveMbusPinLo),
                                )
        if not libMbus.mbus_phy_rx_is_empty(ctypes.byref(mbusPhy)):
            while not libMbus.mbus_phy_rx_is_empty(ctypes.byref(mbusPhy)):
                newNib = libMbus.mbus_phy_rx_pop(ctypes.byref(mbusPhy))
                if newNib == nibbles.MBUS_END_MSG_CODE:
                    # print("{}".format("".join(rxNibList)))
                    # print("{}".format(rxNibList))
                    yield rxNibList
                    rxNibList = nibbles.MbusRawNibbleList(mbusTimeFormat="blank")
                else:
                    rxNibList.append(chr((libMbus.mbus_phy_rxnibble2ascii(newNib))))
    def __init__(self,g_pool,atb_pos=(320,220)):
        super(Marker_Detector, self).__init__()
        self.g_pool = g_pool
        self.order = .2

        # all markers that are detected in the most recent frame
        self.markers = []
        # all registered surfaces

        self.surface_definitions = Persistent_Dict(os.path.join(g_pool.user_dir,'surface_definitions') )
        self.surfaces = [Reference_Surface(saved_definition=d) for d in self.load('realtime_square_marker_surfaces',[]) if isinstance(d,dict)]

        # edit surfaces
        self.surface_edit_mode = c_bool(0)
        self.edit_surfaces = []

        #detector vars
        self.robust_detection = c_bool(1)
        self.aperture = c_int(11)
        self.min_marker_perimeter = 80

        #debug vars
        self.draw_markers = c_bool(0)
        self.show_surface_idx = c_int(0)
        self.recent_pupil_positions = []

        self.img_shape = None

        atb_label = "marker detection"
        self._bar = atb.Bar(name =self.__class__.__name__, label=atb_label,
            help="marker detection parameters", color=(50, 150, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 300))

        self.update_bar_markers()
def main(argv):
	global libX11, display
	state = ctypes.c_bool(False)	
	atom = libX11.XInternAtom(display, "Caps Lock", ctypes.c_bool(False))
	libX11.XkbGetNamedIndicator(display, atom, 0, ctypes.byref(state), 0, 0)
	flag = state.value
	
	signal.signal(signal.SIGINT, sig_hdr)
	signal.signal(signal.SIGTERM, sig_hdr)
	
	if not pynotify.init("caps"):
		sys.exit(1)
	
	uri_on = "file://" + '''your dir''' + "/capslock-on.png"
	uri_off = "file://" + '''your dir''' + "/capslock-off.png"
	caps_notify = pynotify.Notification("CapsLock Notification")
	
# Perhaps libX11 is not compatible with python-daemon. If you know the reason, please tell me. Thanks.
#	with daemon.DaemonContext():
	while True:
		libX11.XkbGetNamedIndicator(display, atom, 0, ctypes.byref(state), 0, 0)
		if flag != state.value:
			if flag:
				caps_notify.update("CapsLock Notification", "CapsLock OFF", uri_off)
				caps_notify.show()
			else:
				caps_notify.update("CapsLock Notification", "CapsLock ON", uri_on)
				caps_notify.show()
			flag = state.value
		time.sleep(0.5)
Example #10
0
    def __init__(self,g_pool,atb_pos=(0,0)):
        Plugin.__init__(self)

        self.window_should_open = False
        self.window_should_close = False
        self._window = None
        self.fullscreen = c_bool(0)
        self.realdata = c_bool(False)
        self.x = c_float(0)
        self.y = c_float(0)
        self.blink_time = c_float(1)
        self.should_blink = False
        self.blink_start = None

        atb_label = "android coordinate plugin"
        # Creating an ATB Bar.
        self._bar = atb.Bar(name =self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_var("real data", self.realdata)
        self._bar.add_var("X", self.x)
        self._bar.define("min=0 max=1 step=0.01", "X")
        self._bar.add_var("Y", self.y)
        self._bar.define("min=0 max=1 step=0.01", "Y")
        self._bar.add_var("blink time", self.blink_time, min=0,max=10,step=0.05,help="Simulated blink time")
        # self._bar.define("min=0 max=10000 step=50", "blink time")
        self._bar.add_button("simulate blink", self.schedule_blink)
Example #11
0
    def test_bool(self):
        self.loopback(True)
        self.loopback(False)

        import ctypes
        self.loopback(ctypes.c_bool(True))
        self.loopback(ctypes.c_bool(False))
 def __init__(self, FollowerForce = ct.c_bool(False), \
              FollowerForceRig = ct.c_bool(True), \
              PrintInfo = ct.c_bool(False), OutInBframe = ct.c_bool(True), \
              OutInaframe = ct.c_bool(False), ElemProj = ct.c_int(0), \
              MaxIterations = ct.c_int(99), NumLoadSteps = ct.c_int(5), \
              NumGauss = ct.c_int(1), Solution = ct.c_int(111), \
              DeltaCurved = ct.c_double(1.0e-5), \
              MinDelta = ct.c_double(1.0e-8), \
              NewmarkDamp = ct.c_double(1.0e-4),
              ImpStart = True, RigidDynamics=False ):
     """@brief Default initialisation is as defined in the original fortran
     derived type."""
     self.FollowerForce = FollowerForce
     self.FollowerForceRig = FollowerForceRig
     self.PrintInfo = PrintInfo
     self.OutInBframe = OutInBframe
     self.OutInaframe = OutInaframe
     self.ElemProj = ElemProj
     self.MaxIterations = MaxIterations
     self.NumLoadSteps = NumLoadSteps
     self.NumGauss = NumGauss
     self.Solution = Solution
     self.DeltaCurved = DeltaCurved
     self.MinDelta = MinDelta
     self.NewmarkDamp = NewmarkDamp
     self.ImpStart=ImpStart
     self.RigidDynamics=RigidDynamics
     
     self._ctypes_links=True  
     self._ctypes_attributes = ['FollowerForce', 'FollowerForceRig', 'PrintInfo',  
              'OutInBframe', 'OutInaframe', 'ElemProj', 'MaxIterations', 'NumLoadSteps',
              'NumGauss', 'Solution', 'DeltaCurved', 'MinDelta', 'NewmarkDamp' ]
     self._ctypes_conversion= [ [ ct.c_int, ct.c_bool, ct.c_double ], 
                                [      int,      bool,       float ] ]
Example #13
0
    def runApp(self):
        self.getter.start()
        getpid=self.getter.pid
        procget=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(getpid))
        kernel.SetPriorityClass(procget, 0x0100)
        self.processer.start()
        procpid=self.processer.pid
        procproc=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(procpid))
        kernel.SetPriorityClass(procproc, 0x0100)
        try:
            while self.getter.is_alive():
                #print("Entered Loop")
                data=self.q.recv()
                
                #if type(data)==str:print(data)
                #print("Got data"+str(len(data)))
                #print("Data"+str(data))
                print(len(data))
                #print(self.processer.is_alive())
                print(time.time())
                #print(data)
                self.system_up_time+=16/128
                #ms=self.checkMarkerStatus()
                #print(self.system_up_time)
##                for i in data:
##                    i.append(ms)
##                self.writelines(data) 
        except:
            self.getter.terminate()
            self.processer.terminate()
            self.closedump()
            raise
Example #14
0
    def __init__(self, name, g_pool, bar_defs):
        super(Bar, self).__init__(name, **bar_defs)
        self.fps = c_float(0.0)
        self.timestamp = time()
        self.dt = c_float(0.0)
        self.sleep = c_float(0.0)
        self.display = c_int(1)
        self.draw_pupil = c_bool(1)
        self.draw_roi = c_int(0)
        self.bin_thresh = c_int(60)
        self.blur = c_int(3)
        self.pupil_ratio = c_float(1.0)
        self.pupil_angle = c_float(0.0)
        self.pupil_size = c_float(80.0)
        self.pupil_size_tolerance = c_float(40.0)
        self.canny_aperture = c_int(5)
        self.canny_thresh = c_int(200)
        self.canny_ratio = c_int(2)
        self.record_eye = c_bool(0)

        # add class field here and it will become session persistant
        self.session_save = {
            "display": self.display,
            "draw_pupil": self.draw_pupil,
            "bin_thresh": self.bin_thresh,
            "pupil_ratio": self.pupil_ratio,
            "pupil_size": self.pupil_size,
            "mean_blur": self.blur,
            "canny_aperture": self.canny_aperture,
            "canny_thresh": self.canny_thresh,
            "canny_ratio": self.canny_ratio,
        }

        self.load()
        dispay_mode_enum = atb.enum(
            "Mode", {"Camera Image": 0, "Region of Interest": 1, "Egdes": 2, "Corse Pupil Region": 3}
        )
        self.add_var("Display/FPS", self.fps, step=1.0, readonly=True)
        self.add_var("Display/SlowDown", self.sleep, step=0.01, min=0.0)
        self.add_var("Display/Mode", self.display, vtype=dispay_mode_enum, help="select the view-mode")
        self.add_var("Display/Show_Pupil_Point", self.draw_pupil)
        self.add_button("Draw_ROI", self.roi, help="drag on screen to select a region of interest", Group="Display")
        self.add_var("Pupil/Shade", self.bin_thresh, readonly=True)
        self.add_var("Pupil/Ratio", self.pupil_ratio, readonly=True)
        self.add_var("Pupil/Angle", self.pupil_angle, step=0.1, readonly=True)
        self.add_var("Pupil/Size", self.pupil_size, readonly=True)
        self.add_var("Pupil/Size_Tolerance", self.pupil_size_tolerance, step=1, min=0)
        self.add_var("Canny/MeanBlur", self.blur, step=2, max=7, min=1)
        self.add_var("Canny/Aperture", self.canny_aperture, step=2, max=7, min=3)
        self.add_var("Canny/Lower_Threshold", self.canny_thresh, step=1, min=1)
        self.add_var(
            "Canny/LowerUpperRatio",
            self.canny_ratio,
            step=1,
            min=0,
            help="Canny recommended a ratio between 3/1 and 2/1",
        )
        self.add_var("record_eye_video", self.record_eye, help="when recording also save the eye video stream")
        self.add_var("SaveSettings&Exit", g_pool.quit)
Example #15
0
def hklUni(cell, spaceGroup, sMin, sMax, code, numRef, maxRef):
    fn = lib.__cfml_reflections_utilities_MOD_hkl_uni_reflect
    c_ReflectionArray = Reflection*max(maxRef,1)
    reflections = c_ReflectionArray()
    fn.argtypes = [POINTER(CrystalCell), POINTER(SpaceGroup), POINTER(c_bool),
                   POINTER(c_float), POINTER(c_float), c_char_p,
                   POINTER(c_int), POINTER(DV), POINTER(c_bool)]
    fn.restype = None
    fn(cell, spaceGroup, c_bool(True), c_float(sMin), c_float(sMax),
       code, numRef, build_struct_dv(reflections), c_bool(False))
    return reflections
Example #16
0
def sort(x, reverse=False):
    if x.dtype == 'int32':
        __lib.sort_int(__getPointer(x), __getLen(x), ct.c_bool(reverse))
    elif x.dtype == 'float64':
        __lib.sort_double(__getPointer(x), __getLen(x), ct.c_bool(reverse))
    elif x.dtype == 'int64':
        __lib.sort_longint(__getPointer(x), __getLen(x), ct.c_bool(reverse))
    else:
        #SortError
        raise RuntimeError('[sort] Datatype %s not supported' % x.dtype)
    return x
Example #17
0
    def __init__(self,g_pool,atb_pos=(0,0)):
        super(Marker_Detector, self).__init__()


        # all markers that are detected in the most recent frame
        self.markers = []
        # all registered surfaces
        self.surface_definitions = shelve.open(os.path.join(g_pool.user_dir,'surface_definitions'),protocol=2)
        self.surfaces = [Reference_Surface(saved_definition=d) for d in self.load('square_marker_surfaces',[]) if isinstance(d,dict)]

        # edit surfaces
        self.surface_edit_mode = c_bool(0)
        self.edit_surfaces = []

        #detector vars
        self.robust_detection = c_bool(1)
        self.aperture = c_int(11)
        self.min_marker_perimeter = 80

        #debug vars
        self.draw_markers = c_bool(0)
        self.show_surface_idx = c_int(0)
        self.recent_pupil_positions = []

        self.img_shape = None

        #multi monitor setup
        self.window_should_open = False
        self.window_should_close = False
        self._window = None
        self.fullscreen = c_bool(0)
        self.monitor_idx = c_int(0)
        self.monitor_handles = glfwGetMonitors()
        self.monitor_names = [glfwGetMonitorName(m) for m in self.monitor_handles]
        monitor_enum = atb.enum("Monitor",dict(((key,val) for val,key in enumerate(self.monitor_names))))
        #primary_monitor = glfwGetPrimaryMonitor()

        atb_label = "marker detection"
        self._bar = atb.Bar(name =self.__class__.__name__, label=atb_label,
            help="marker detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_var("monitor",self.monitor_idx, vtype=monitor_enum,group="Window",)
        self._bar.add_var("fullscreen", self.fullscreen,group="Window")
        self._bar.add_button("  open Window   ", self.do_open, key='m',group="Window")
        self._bar.add_var("surface to show",self.show_surface_idx, step=1,min=0,group="Window")
        self._bar.add_var('robust_detection',self.robust_detection,group="Detector")
        self._bar.add_var("draw markers",self.draw_markers,group="Detector")

        atb_pos = atb_pos[0],atb_pos[1]+110
        self._bar_markers = atb.Bar(name =self.__class__.__name__+'markers', label='registered surfaces',
            help="list of registered ref surfaces", color=(50, 100, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 120))
        self.update_bar_markers()
Example #18
0
    def start(self):
        """
        Launch background threads for loading the data.
        """
        DataBufferPair = (ct.POINTER(ct.c_ubyte)) * 2
        LabelBufferPair = (ct.POINTER(ct.c_int)) * 2

        class DeviceParams(ct.Structure):
            _fields_ = [("type", ct.c_int), ("id", ct.c_int), ("data", DataBufferPair), ("labels", LabelBufferPair)]

        if self.be.device_type == 0:  # CPU
            data_buffers = DataBufferPair(
                self.buffers[0]._tensor.ctypes.data_as(ct.POINTER(ct.c_ubyte)),
                self.buffers[1]._tensor.ctypes.data_as(ct.POINTER(ct.c_ubyte)),
            )
            label_buffers = LabelBufferPair(
                self.labels[0]._tensor.ctypes.data_as(ct.POINTER(ct.c_int)),
                self.labels[1]._tensor.ctypes.data_as(ct.POINTER(ct.c_int)),
            )
        else:  # GPU
            data_buffers = DataBufferPair(
                ct.cast(int(self.buffers[0].gpudata), ct.POINTER(ct.c_ubyte)),
                ct.cast(int(self.buffers[1].gpudata), ct.POINTER(ct.c_ubyte)),
            )
            label_buffers = LabelBufferPair(
                ct.cast(int(self.labels[0].gpudata), ct.POINTER(ct.c_int)),
                ct.cast(int(self.labels[1].gpudata), ct.POINTER(ct.c_int)),
            )
        params = DeviceParams(self.be.device_type, self.be.device_id, data_buffers, label_buffers)
        self.loader = self.loaderlib.start(
            ct.c_int(self.inner_size),
            ct.c_bool(self.center),
            ct.c_bool(self.flip),
            ct.c_bool(self.rgb),
            ct.c_int(self.scale_range[0]),
            ct.c_int(self.scale_range[1]),
            ct.c_int(self.contrast_range[0]),
            ct.c_int(self.contrast_range[1]),
            ct.c_int(0),
            ct.c_int(0),  # ignored rotation params
            ct.c_int(self.aspect_ratio),
            ct.c_int(self.minibatch_size),
            ct.c_char_p(self.filename),
            ct.c_int(self.macro_start),
            ct.c_uint(self.ndata),
            ct.c_int(self.nlabels),
            ct.c_bool(self.macro),
            ct.c_bool(self.shuffle),
            ct.c_int(self.item_max_size),
            ct.c_int(self.label_size),
            ct.POINTER(DeviceParams)(params),
        )
        assert self.start_idx % self.bsz == 0
Example #19
0
 def runApp(self):
    self.getter.start()
    getpid=self.getter.pid
    procget=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(getpid))
    kernel.SetPriorityClass(procget, 0x0100)
    self.processer.start()
    procpid=self.processer.pid
    procproc=kernel.OpenProcess(ctypes.c_uint(0x0200|0x0400), ctypes.c_bool(False), ctypes.c_uint(procpid))
    kernel.SetPriorityClass(procproc, 0x0100)
    data_dict=dict()
    for i in self.events:
        data_dict[i]={"F3":[], "F4":[], "T7":[], "T8":[]}
    
    for tp in data_dict:
        
        print(tp)
        #time.sleep(1)
        first=bool(True)
        
        try:
            while self.getter.is_alive():
                #print(data_dict)
                #print(data_dict[tp])
                data=self.q.recv()
                if first:
                    
                    #print(tp)
                    #time.sleep(1)
                    data=self.q.recv()
                    first=False
                for i in data_dict[tp]:
                    data_dict[tp][i].append(data[i][0][2])
                if len(data_dict[tp]["F3"])==64:
                    for i in data_dict[tp]:
                        del data_dict[tp][i][0]
                    #print(self.livedataclass.test_classifiers_ret(data_dict))
                    raise KeyboardInterrupt
                
                    
                print(time.asctime())
             #a#   self.system_up_time+=16/128
        except:
            for i in range(32):
                 self.q.recv()
            print("Train Done")
            
           # raise
    self.getter.terminate()
    self.processer.terminate()
    fileobj=open("C:/Users/Gaurav/Desktop/KineticEEGProgamFiles/Trainingdata.dat", "wb")
    fileobj.write(pickle.dumps(data_dict))
    fileobj.close()
Example #20
0
 def __init__(self, M, N, ImageMethod = False, Mstar = 1, Steady = True,\
              KJMeth = True, NewAIC = True, DelTime = 0.0, Rollup = False,\
              NumCores = 1):
     self.M = ct.c_uint(M)
     self.N = ct.c_uint(N)
     self.ImageMethod = ct.c_bool(ImageMethod)
     self.Mstar = ct.c_int(Mstar)
     self.Steady = ct.c_bool(Steady)
     self.KJMeth = ct.c_bool(KJMeth)
     self.NewAIC = ct.c_bool(NewAIC)
     self.DelTime = ct.c_double(DelTime)
     self.Rollup = ct.c_bool(Rollup)
     self.NumCores = ct.c_uint(NumCores)
Example #21
0
    def get_phase(self, jds, eclipseMode=True, getOrbits=False):
        """
        Convert MJD2000 to accurate orbit number and orbit phase (eclipse-based or pole-based).

        Parameters
        ----------

        jds : numpy array, float64
            julian dates or a float64 scalar
        eclipseMode : bool, optional
            flag to indicate eclipse mode or polar mode
        getOrbits : bool, optional
            also return orbit numbers

        Returns
        -------

        numpy array of array phases (same size as 'jds')

        or

        the phases and an array or absolute orbit numbers
         
        """
        if not isinstance(jds, np.ndarray):
            jds = np.array(jds)

        n_records = jds.size
        saa_flag = False;
        dummy_orbit = 0
        # prepare orbit phase output array for c
        phases = np.zeros(n_records) # TODO: directly specify dtype=float64 or so?
        phases = phases.astype(np.float32)
        phases_c = phases.ctypes.data_as(ct.POINTER(ct.c_float))
        # prepare julianday input array for c
        jds = jds.astype(np.float64)
        jds_c = jds.ctypes.data_as(ct.POINTER(ct.c_double))

        # orbits = np.empty(n_records)
        # orbits_c = orbits.ctypes.data_as(ct.POINTER(ct.c_long))
        orbits = np.empty(n_records) # TODO: directly specify dtype=float64 or so?
        orbits = orbits.astype(np.int32)
        orbits_c = orbits.ctypes.data_as(ct.POINTER(ct.c_long))

        if getOrbits:
            self.phaselib._GET_SCIA_ROE_ORBITPHASE_ORBIT(ct.c_bool(eclipseMode), ct.c_bool(saa_flag), ct.c_long(n_records), orbits_c, phases_c, jds_c) 
            return np.float64(phases), orbits
        else:
            self.phaselib._GET_SCIA_ROE_ORBITPHASE(ct.c_bool(eclipseMode), ct.c_bool(saa_flag), ct.c_long(n_records), ct.c_long(dummy_orbit), phases_c, jds_c) 
            return phases
Example #22
0
def __aiMetadataGetBool( nodeEntry, paramName, name, defaultValue = None ) :

	value = ctypes.c_bool()
	if arnold.AiMetaDataGetBool( nodeEntry, paramName, name, value ) :
		return bool( value )

	return defaultValue
    def __init__(self, g_pool,atb_pos=(0,0)):
        Plugin.__init__(self)
        self.active = False
        self.detected = False
        self.g_pool = g_pool
        self.pos = None
        self.smooth_pos = 0.,0.
        self.smooth_vel = 0.
        self.sample_site = (-2,-2)
        self.counter = 0
        self.counter_max = 30
        self.candidate_ellipses = []
        self.show_edges = c_bool(0)
        self.aperture = 7
        self.dist_threshold = c_int(10)
        self.area_threshold = c_int(30)
        self.world_size = None

        self.stop_marker_found = False
        self.auto_stop = 0
        self.auto_stop_max = 30
        atb_label = "calibrate using handheld marker"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name = self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_button("start/stop", self.start_stop, key='c')
        self._bar.add_var("show edges",self.show_edges, group="Advanced")
Example #24
0
    def do_get_data_lost(self): #OK!
        """
        Check for data loss.

        Timestamps of events detected by the device can get lost if their rate 
        is too high for the USB interface or if the PC is unable to receive 
        the data in time. The TDC recognizes this situation and signals it to 
        the PC (with high priority).

        The function checks if a data loss situation is currently detected or
        if it has been latched since the last call. If you are only interested 
        in the current situation, call the function twice; 
        the first call will delete the latch.

        Output:

        Current and latched data loss state.
        """
        lost = ctypes.c_bool()

        ans = self.qutools_dll.TDC_getDataLost(ctypes.byref(lost))
        #print ans
        
        if ans != 0:
            return self.err_dict[ans]
        else:
            return lost.value
    def initServer(self):
        '''Initialize the Lab Brick Attenuator Server.'''
        yield self.getRegistryKeys()
        try:
            self.VNXdll = yield ctypes.CDLL(self.DLL_path)
        except Exception:
            raise Exception('Could not find Lab Brick Attenuator DLL')

        # Disable attenuator DLL test mode.
        self.VNXdll.fnLDA_SetTestMode(ctypes.c_bool(False)) 
        
        # Number of the currently connected devices.
        self._num_devs = 0

        # Create a dictionary that maps serial numbers to device IDs.
        self.SerialNumberDict = dict()
        # Create a dictionary that keeps track of last set attenuation.
        self.LastAttenuation = dict()   
        # Dictionary to keep track of min/max attenuations.
        self.MinMaxAttenuation = dict()

        # Create a context for the server.
        self._pseudo_context = {}
        if self.autoRefresh:
            callLater(0.1, self.startRefreshing)
        else:
            yield self.refreshAttenuators()
Example #26
0
	def setFrom(self, val, name=None):
		"""Create an argument using a value as input.
		
		Arguments:
		Value -- an OpenSCAD value
		string -- the name of the value
		"""
		if name:
			self.name = ctypes.c_char_p(name)
		else:
			self.name = ctypes.c_char_p(0)
			
		if isinstance(val, bool):
			self.type = 'b'
			self.boolValue = ctypes.c_bool(val)
		elif isinstance(val, int) or isinstance(val, float):
			self.type = 'd'
			self.dblValue = ctypes.c_double(val)
		elif isinstance(val, str):
			self.type = 's'
			self.strValue = ctypes.c_char_p(val)
		elif isinstance(val, list) or isinstance(val, tuple):
			self.type = 'v'
			self.vecLen = ctypes.c_int(len(val))
			arr = (ctypes.c_double * len(val))()
			for i, v in enumerate(val):
				arr[i] = ctypes.c_double(v)
			self.vecValue = arr
Example #27
0
 def __init__(self, library_location=DEFAULT_UUIRTDRV_LIBRARY_LOCATION):
     """Accepts a path to uuirtdrv.so - probably has to be changed a little for windows"""
     uuirtlib = ctypes.cdll.LoadLibrary(library_location)
     self.__UUIRTOpen = uuirtlib.UUIRTOpen
     self.__UUIRTOpenEx = uuirtlib.UUIRTOpenEx
     self.__UUIRTClose = uuirtlib.UUIRTClose
     self.__UUIRTGetDrvInfo = uuirtlib.UUIRTGetDrvInfo
     self.__UUIRTGetDrvVersion = uuirtlib.UUIRTGetDrvVersion
     self.__UUIRTGetUUIRTInfo = uuirtlib.UUIRTGetUUIRTInfo
     self.__UUIRTGetUUIRTConfig = uuirtlib.UUIRTGetUUIRTConfig
     self.__UUIRTSetUUIRTConfig = uuirtlib.UUIRTSetUUIRTConfig
     self.__UUIRTTransmitIR = uuirtlib.UUIRTTransmitIR
     self.__UUIRTLearnIR = uuirtlib.UUIRTLearnIR
     self.__UUIRTSetReceiveCallback = uuirtlib.UUIRTSetReceiveCallback
     self.__UUIRTGetUUIRTGPIOCfg = uuirtlib.UUIRTGetUUIRTGPIOCfg
     self.__UUIRTSetUUIRTGPIOCfg = uuirtlib.UUIRTSetUUIRTGPIOCfg
     self.__dev_handle = ctypes.c_void_p()
     self.__opened = False
     self.__receiveCallback = None
     self.__learnCallback = None
     self.__receiveUserData = None
     self.__receiveUserDataType = None
     self.__learnUserData = None
     self.__learnUserDataType = None
     
     # Python 2.6 and later - not sure what to wrap this with on earlier versions
     self.__abort = ctypes.c_bool(False)
Example #28
0
def is_process_64_from_handle(hProcess):
    """ Take a process handle. return True if process is 64 bits, and False otherwise. """
    iswow64 = c_bool(False)
    if not hasattr(windll.kernel32,'IsWow64Process'):
        return False
    windll.kernel32.IsWow64Process(hProcess, byref(iswow64))
    return not iswow64.value
Example #29
0
 def learnIR(self, codeformat, callback, userdata, abort, param1):
     """Wraps UUIRTLearnIR, returns a list of int().
         codeformat is an int(), 
         callback is a Python ctypes function usbuirt.PLEARNCALLBACKPROC(), 
         userdata is any python object and will be sent to the callback function,
         abort is a boolean, and should be set to false - and theoretically setting it to true will interrupt the learning process
         param1 should be 0 unless there's a good reason according to the docs
         Note that changing this callback will override self.learnCallback and self._learnCallback."""
     # ircode create_string_buffer
     if not self.__opened:
         raise Exception
     buff = ctypes.create_string_buffer(4096)
     if callback:
         self.__learnCallback = PLEARNCALLBACKPROC(callback)
     
     # Python 2.6 and later.
     self.__abort = ctypes.c_bool(abort)
     self.__learnUserData = userdata
     # the type needs a reference count retained to reconstruct
     self.__learnUserDataType = ctypes.py_object(self.__learnUserData)
     rv = self.__UUIRTLearnIR(self.__dev_handle,
                              ctypes.c_int(codeformat),
                              ctypes.byref(buff),
                              self.__learnCallback,
                              ctypes.cast(ctypes.addressof(self.__learnUserDataType), ctypes.c_void_p),
                              ctypes.byref(self.__abort),
                              param1, None, None)
     if rv == 0:
         raise Exception
     #vals = [int(x, 16) for x in buff.value.split(' ')]
     #return vals
     #returning pronto format code
     return buff.value
Example #30
0
    def initServer(self):

        # load wavemeter dll file for use of API functions self.d and self.l
        # are dummy c_types for unused wavemeter functions

        dll_path = "C:\Windows\System32\wlmData.dll"
        self.wmdll = ctypes.windll.LoadLibrary(dll_path)
        self.d = ctypes.c_double(0)
        self.l = ctypes.c_long(0)
        self.b = ctypes.c_bool(0)

        self.set_pid_variables()

        # Getting the amplitude in the GetAmplitudeNum function can
        # return the max, min, and average of the interference pattern
        self.AmplitudeMin = ctypes.c_long(0)
        self.AmplitudeMax = ctypes.c_long(2)
        self.AmplitudeAvg = ctypes.c_long(4)

        self.set_dll_variables()
        self.WavemeterVersion = self.wmdll.GetWLMVersion(ctypes.c_long(1))

        self.measureChan()

        self.listeners = set()
def Solve_Py(XBINPUT,XBOPTS,VMOPTS,VMINPUT,AELAOPTS,**kwords):
    """@brief Nonlinear dynamic solver using Python to solve aeroelastic
    equation.
    @details Assembly of structural matrices is carried out with 
    Fortran subroutines. Aerodynamics solved using PyAero\.UVLM.
    @param XBINPUT Beam inputs (for initialization in Python).
    @param XBOPTS Beam solver options (for Fortran).
    @param VMOPTS UVLM solver options (for C/C++).
    @param VMINPUT UVLM solver inputs (for initialization in Python).
    @param VMUNST Unsteady input information for aero solver.
    @param AELAOPTS Options relevant to coupled aeroelastic simulations.
    @param writeDict OrderedDict of 'name':tuple of outputs to write.
    """
        
    # Check correct solution code.
    assert XBOPTS.Solution.value == 912, ('NonlinearFlightDynamic requested' +
                                          ' with wrong solution code')
    # Initialise static beam data.
    XBINPUT, XBOPTS, NumNodes_tot, XBELEM, PosIni, PsiIni, XBNODE, NumDof \
                = BeamInit.Static(XBINPUT,XBOPTS)
                
    # Calculate initial displacements.
    if AELAOPTS.ImpStart == False:
        XBOPTS.Solution.value = 112 # Modify options.
        VMOPTS.Steady = ct.c_bool(True)
        Rollup = VMOPTS.Rollup.value
        VMOPTS.Rollup.value = False
        # Solve Static Aeroelastic.
        PosDefor, PsiDefor, Zeta, ZetaStar, Gamma, GammaStar, Force = \
                    Static.Solve_Py(XBINPUT, XBOPTS, VMOPTS, VMINPUT, AELAOPTS)
        XBOPTS.Solution.value = 912 # Reset options.
        VMOPTS.Steady = ct.c_bool(False)
        VMOPTS.Rollup.value = Rollup
    elif AELAOPTS.ImpStart == True:
        PosDefor = PosIni.copy(order='F')
        PsiDefor = PsiIni.copy(order='F')
        Force = np.zeros((XBINPUT.NumNodesTot,6),ct.c_double,'F')
        
    # Write deformed configuration to file. TODO: tidy this away inside function.
    ofile = Settings.OutputDir + Settings.OutputFileRoot + '_SOL912_def.dat'
    if XBOPTS.PrintInfo==True:
        sys.stdout.write('Writing file %s ... ' %(ofile))
    fp = open(ofile,'w')
    fp.write('TITLE="Non-linear static solution: deformed geometry"\n')
    fp.write('VARIABLES="iElem" "iNode" "Px" "Py" "Pz" "Rx" "Ry" "Rz"\n')
    fp.close()
    if XBOPTS.PrintInfo==True:
        sys.stdout.write('done\n')
    WriteMode = 'a'
    # Write
    BeamIO.OutputElems(XBINPUT.NumElems, NumNodes_tot.value, XBELEM,
                       PosDefor, PsiDefor, ofile, WriteMode)
    
    # Initialise structural variables for dynamic analysis.
    Time, NumSteps, ForceTime, Vrel, VrelDot,\
    PosDotDef, PsiDotDef,\
    OutGrids, PosPsiTime, VelocTime, DynOut\
        = BeamInit.Dynamic(XBINPUT,XBOPTS)
    # Delete unused variables.
    del OutGrids, VelocTime
    
    if XBOPTS.PrintInfo.value==True:
        sys.stdout.write('Solve nonlinear dynamic case in Python ... \n')
    
    
    #Initialise structural system tensors
    MssFull = np.zeros((NumDof.value,NumDof.value), ct.c_double, 'F')
    CssFull = np.zeros((NumDof.value,NumDof.value), ct.c_double, 'F') 
    KssFull = np.zeros((NumDof.value,NumDof.value), ct.c_double, 'F') 
    FstrucFull = np.zeros((NumDof.value,NumDof.value), ct.c_double, 'F')
    
    ms = ct.c_int()
    cs = ct.c_int()
    ks = ct.c_int()
    fs = ct.c_int()
    
    Msr = np.zeros((NumDof.value,6), ct.c_double, 'F')
    Csr = np.zeros((NumDof.value,6), ct.c_double, 'F')
    
    X     = np.zeros(NumDof.value, ct.c_double, 'F')
    dXdt  = np.zeros(NumDof.value, ct.c_double, 'F')
    Force_Dof = np.zeros(NumDof.value, ct.c_double, 'F')
    
    Qstruc = np.zeros(NumDof.value, ct.c_double, 'F')
    
    #Initialise rigid-body system tensors
    MrsFull = np.zeros((6,NumDof.value), ct.c_double, 'F')
    CrsFull = np.zeros((6,NumDof.value), ct.c_double, 'F') 
    KrsFull = np.zeros((6,NumDof.value), ct.c_double, 'F') 
    FrigidFull = np.zeros((6,NumDof.value+6), ct.c_double, 'F')
    
    mr = ct.c_int()
    cr = ct.c_int()
    kr = ct.c_int()
    fr = ct.c_int()
    
    Mrr = np.zeros((6,6), ct.c_double, 'F')
    Crr = np.zeros((6,6), ct.c_double, 'F')
        
    Qrigid = np.zeros(6, ct.c_double, 'F')
    
    #Initialise full system tensors
    Q     = np.zeros(NumDof.value+6+4, ct.c_double, 'F')
    DQ    = np.zeros(NumDof.value+6+4, ct.c_double, 'F')
    dQdt  = np.zeros(NumDof.value+6+4, ct.c_double, 'F')
    dQddt = np.zeros(NumDof.value+6+4, ct.c_double, 'F')
    Force_All = np.zeros(NumDof.value+6, ct.c_double, 'F')

    Msys = np.zeros((NumDof.value+6+4,NumDof.value+6+4), ct.c_double, 'F')
    Csys = np.zeros((NumDof.value+6+4,NumDof.value+6+4), ct.c_double, 'F') 
    Ksys = np.zeros((NumDof.value+6+4,NumDof.value+6+4), ct.c_double, 'F') 
    Asys = np.zeros((NumDof.value+6+4,NumDof.value+6+4), ct.c_double, 'F')
    
    Qsys = np.zeros(NumDof.value+6+4, ct.c_double, 'F')
    
    #Initialise rotation operators. TODO: include initial AOA here
    currVrel=Vrel[0,:].copy('F')
    AOA  = np.arctan(currVrel[2]/-currVrel[1])
    Quat = xbl.Euler2Quat(AOA,0,0)
    Cao  = xbl.Rot(Quat)
    ACoa = np.zeros((6,6), ct.c_double, 'F')
    ACoa[:3,:3] = np.transpose(Cao)
    ACoa[3:,3:] = np.transpose(Cao)
    Cqr = np.zeros((4,6), ct.c_double, 'F')
    Cqq = np.zeros((4,4), ct.c_double, 'F')
        
    Unit4 = np.zeros((4,4), ct.c_double, 'F')
    for i in range(4):
        Unit4[i,i] = 1.0
    
    # Extract initial displacements and velocities.
    BeamLib.Cbeam_Solv_Disp2State(NumNodes_tot, NumDof, XBINPUT, XBNODE,
                                  PosDefor, PsiDefor, PosDotDef, PsiDotDef,
                                  X, dXdt)
    
    # Approximate initial accelerations.
    PosDotDotDef = np.zeros((NumNodes_tot.value,3),ct.c_double,'F')
    PsiDotDotDef = np.zeros((XBINPUT.NumElems,Settings.MaxElNod,3),
                             ct.c_double, 'F')
    
    #Populate state vector
    Q[:NumDof.value]=X.copy('F')
    dQdt[:NumDof.value]=dXdt.copy('F')
    dQdt[NumDof.value:NumDof.value+6] = Vrel[0,:].copy('F')
    dQdt[NumDof.value+6:]= Quat.copy('F')
    
    #Force at the first time-step
    Force += (XBINPUT.ForceDyn*ForceTime[0]).copy('F')
    

    #Assemble matrices and loads for structural dynamic analysis
    currVrel=Vrel[0,:].copy('F')
    tmpQuat=Quat.copy('F')
    BeamLib.Cbeam3_Asbly_Dynamic(XBINPUT, NumNodes_tot, XBELEM, XBNODE,\
                         PosIni, PsiIni, PosDefor, PsiDefor,\
                         PosDotDef, PsiDotDef, PosDotDotDef, PsiDotDotDef,\
                         Force, currVrel, 0*currVrel,\
                         NumDof, Settings.DimMat,\
                         ms, MssFull, Msr,\
                         cs, CssFull, Csr,\
                         ks, KssFull, fs, FstrucFull,\
                         Qstruc, XBOPTS, Cao)
       
    BeamLib.f_fem_m2v(ct.byref(NumNodes_tot),\
                              ct.byref(ct.c_int(6)),\
                              Force.ctypes.data_as(ct.POINTER(ct.c_double)),\
                              ct.byref(NumDof),\
                              Force_Dof.ctypes.data_as(ct.POINTER(ct.c_double)),\
                              XBNODE.Vdof.ctypes.data_as(ct.POINTER(ct.c_int)) )

    Qstruc -= np.dot(FstrucFull, Force_Dof)
    
    
    #Assemble matrices for rigid-body dynamic analysis
    BeamLib.Xbeam_Asbly_Dynamic(XBINPUT, NumNodes_tot, XBELEM, XBNODE,\
                         PosIni, PsiIni, PosDefor, PsiDefor,\
                         PosDotDef, PsiDotDef, PosDotDotDef, PsiDotDotDef,\
                         currVrel, 0*currVrel, tmpQuat,\
                         NumDof, Settings.DimMat,\
                         mr, MrsFull, Mrr,\
                         cr, CrsFull, Crr, Cqr, Cqq,\
                         kr, KrsFull, fr, FrigidFull,\
                         Qrigid, XBOPTS, Cao)
    
    BeamLib.f_fem_m2v_nofilter(ct.byref(NumNodes_tot),\
                               ct.byref(ct.c_int(6)),\
                               Force.ctypes.data_as(ct.POINTER(ct.c_double)),\
                               ct.byref(ct.c_int(NumDof.value+6)),\
                               Force_All.ctypes.data_as(ct.POINTER(ct.c_double)) )

    Qrigid -= np.dot(FrigidFull, Force_All)
        
          
#     #Separate assembly of follower and dead loads   
#     tmpForceTime=ForceTime[0].copy('F') 
#     tmpQforces,Dummy,tmpQrigid = xbl.LoadAssembly(XBINPUT, XBELEM, XBNODE, XBOPTS, NumDof, \
#                                     PosIni, PsiIni, PosDefor, PsiDefor, \
#                                     (XBINPUT.ForceStatic_foll + XBINPUT.ForceDyn_foll*tmpForceTime), \
#                                     (XBINPUT.ForceStatic_dead + XBINPUT.ForceDyn_dead*tmpForceTime), \
#                                     Cao,1)
#                            
#     Qstruc -= tmpQforces      
#     Qrigid -= tmpQrigid
    
    
    #Assemble system matrices
    Msys[:NumDof.value,:NumDof.value] = MssFull.copy('F')
    Msys[:NumDof.value,NumDof.value:NumDof.value+6] = Msr.copy('F')
    Msys[NumDof.value:NumDof.value+6,:NumDof.value] = MrsFull.copy('F')
    Msys[NumDof.value:NumDof.value+6,NumDof.value:NumDof.value+6] = Mrr.copy('F')
    Msys[NumDof.value+6:,NumDof.value+6:] = Unit4.copy('F')
       
    Qsys[:NumDof.value] = Qstruc
    Qsys[NumDof.value:NumDof.value+6] = Qrigid
    Qsys[NumDof.value+6:] = np.dot(Cqq,dQdt[NumDof.value+6:])
       

    # Initial Accel.
    dQddt[:] = np.dot(np.linalg.inv(Msys), -Qsys)
    
    
    #Record position of all grid points in global FoR at initial time step
    DynOut[0:NumNodes_tot.value,:] = PosDefor
    
    #Position/rotation of the selected node in initial deformed configuration
    PosPsiTime[0,:3] = PosDefor[-1,:]
    PosPsiTime[0,3:] = PsiDefor[-1,XBELEM.NumNodes[-1]-1,:]
    
    
    #Get gamma and beta for Newmark scheme
    gamma = 0.5 + XBOPTS.NewmarkDamp.value
    beta = 0.25*(gamma + 0.5)**2
    
    
    # Initialise Aero       
    Section = InitSection(VMOPTS,VMINPUT,AELAOPTS.ElasticAxis)
    
    # Declare memory for Aero variables.
    ZetaDot = np.zeros((Section.shape[0],PosDefor.shape[0],3),ct.c_double,'C')
    K = VMOPTS.M.value*VMOPTS.N.value
    AIC = np.zeros((K,K),ct.c_double,'C')
    BIC = np.zeros((K,K),ct.c_double,'C')
    AeroForces = np.zeros((VMOPTS.M.value+1,VMOPTS.N.value+1,3),ct.c_double,'C')
    
    # Initialise A-frame location and orientation to be zero.
    OriginA_G = np.zeros(3,ct.c_double,'C')
    PsiA_G = xbl.quat2psi(Quat) # CRV at iStep
    
    # Init external velocities.  
    Ufree = InitSteadyExternalVels(VMOPTS,VMINPUT)
    if AELAOPTS.ImpStart == True:
        Zeta = np.zeros((Section.shape[0],PosDefor.shape[0],3),ct.c_double,'C')             
        Gamma = np.zeros((VMOPTS.M.value,VMOPTS.N.value),ct.c_double,'C')
        # Generate surface, wake and gamma matrices.
        CoincidentGrid(PosDefor, PsiDefor, Section, currVrel[:3], 
                       currVrel[3:], PosDotDef, PsiDotDef, XBINPUT,
                       Zeta, ZetaDot, OriginA_G, PsiA_G,
                       VMINPUT.ctrlSurf)
        # init wake grid and gamma matrix.
        ZetaStar, GammaStar = InitSteadyWake(VMOPTS,VMINPUT,Zeta,currVrel[:3])
          
    # Define tecplot stuff
    if Settings.PlotTec==True:
        FileName = Settings.OutputDir + Settings.OutputFileRoot + 'AeroGrid.dat'
        Variables = ['X', 'Y', 'Z','Gamma']        
        FileObject = PostProcess.WriteAeroTecHeader(FileName, 
                                                    'Default',
                                                    Variables)
        # Plot results of static analysis
        PostProcess.WriteUVLMtoTec(FileObject,
                                   Zeta,
                                   ZetaStar,
                                   Gamma,
                                   GammaStar,
                                   TimeStep = 0,
                                   NumTimeSteps = XBOPTS.NumLoadSteps.value,
                                   Time = 0.0,
                                   Text = True)
    
    # Open output file for writing
    if 'writeDict' in kwords and Settings.WriteOut == True:
        writeDict = kwords['writeDict']
        ofile = Settings.OutputDir + \
                Settings.OutputFileRoot + \
                '_SOL912_out.dat'
        fp = open(ofile,'w')
        fp.write("{:<14}".format("Time"))
        for output in writeDict.keys():
            fp.write("{:<14}".format(output))
        fp.write("\n")
        fp.flush()
        
    # Write initial outputs to file.
    if 'writeDict' in kwords and Settings.WriteOut == True:
        locForces = None # Stops recalculation of forces
        fp.write("{:<14,e}".format(Time[0]))
        for myStr in writeDict.keys():
            if re.search(r'^R_.',myStr):
                if re.search(r'^R_._.', myStr):
                    index = int(myStr[4])
                elif re.search(r'root', myStr):
                    index = 0
                elif re.search(r'tip', myStr):
                    index = -1
                else:
                    raise IOError("Node index not recognised.")
                
                if myStr[2] == 'x':
                    component = 0
                elif myStr[2] == 'y':
                    component = 1
                elif myStr[2] == 'z':
                    component = 2
                else:
                    raise IOError("Displacement component not recognised.")
                
                fp.write("{:<14,e}".format(PosDefor[index,component]))
                
            elif re.search(r'^M_.',myStr):
                if re.search(r'^M_._.', myStr):
                    index = int(myStr[4])
                elif re.search(r'root', myStr):
                    index = 0
                elif re.search(r'tip', myStr):
                    index = -1
                else:
                    raise IOError("Node index not recognised.")
                
                if myStr[2] == 'x':
                    component = 0
                elif myStr[2] == 'y':
                    component = 1
                elif myStr[2] == 'z':
                    component = 2
                else:
                    raise IOError("Moment component not recognised.")
                
                if locForces == None:
                    locForces = BeamIO.localElasticForces(PosDefor,
                                                          PsiDefor,
                                                          PosIni,
                                                          PsiIni,
                                                          XBELEM,
                                                          [index])
                
                fp.write("{:<14,e}".format(locForces[0,3+component]))
            else:
                raise IOError("writeDict key not recognised.")
        # END for myStr
        fp.write("\n")
        fp.flush()
    # END if write

    # Time loop.
    for iStep in range(NumSteps.value):
        
        if XBOPTS.PrintInfo.value==True:
            sys.stdout.write('Time: %-10.4e\n' %(Time[iStep+1]))
            sys.stdout.write('   SubIter DeltaF     DeltaX     ResLog10\n')
        
        #calculate dt
        dt = Time[iStep+1] - Time[iStep]
        
        # Set dt for aero force calcs.
        VMOPTS.DelTime = ct.c_double(dt)
        
        #Predictor step
        Q       += dt*dQdt + (0.5-beta)*dQddt*np.power(dt,2.0)
        dQdt    += (1.0-gamma)*dQddt*dt
        dQddt[:] = 0.0
        
        # Quaternion update for orientation.
        Quat = dQdt[NumDof.value+6:].copy('F')
        Quat = Quat/np.linalg.norm(Quat)
        Cao  = xbl.Rot(Quat)
        
        #nodal diplacements and velocities from state vector
        X=Q[:NumDof.value].copy('F') 
        dXdt=dQdt[:NumDof.value].copy('F'); 
        BeamLib.Cbeam3_Solv_State2Disp(XBINPUT,NumNodes_tot,XBELEM,XBNODE,
                                       PosIni,PsiIni,NumDof,X,dXdt,
                                       PosDefor,PsiDefor,PosDotDef,PsiDotDef)
            
        # Force at current time-step. TODO: Check communication flow. 
        if iStep > 0 and AELAOPTS.Tight == False:
            
            # zero aero forces.
            AeroForces[:,:,:] = 0.0
            
            # Update CRV.
            PsiA_G = xbl.quat2psi(Quat) # CRV at iStep
            
            # Update origin.
            currVrel=Vrel[iStep-1,:].copy('F')
            OriginA_G[:] = OriginA_G[:] + currVrel[:3]*dt
            
            # Update control surface deflection.
            if VMINPUT.ctrlSurf != None:
                VMINPUT.ctrlSurf.update(Time[iStep])
            
            # Generate surface grid.
            currVrel=Vrel[iStep,:].copy('F')
            CoincidentGrid(PosDefor, PsiDefor, Section, currVrel[:3], 
                           currVrel[3:], PosDotDef, PsiDotDef, XBINPUT,
                           Zeta, ZetaDot, OriginA_G, PsiA_G,
                           VMINPUT.ctrlSurf)
            
            # Update wake geom       
            #'roll' data.
            ZetaStar = np.roll(ZetaStar,1,axis = 0)
            GammaStar = np.roll(GammaStar,1,axis = 0)
            #overwrite grid points with TE.
            ZetaStar[0,:] = Zeta[VMOPTS.M.value,:]
            # overwrite Gamma with TE value from previous timestep.
            GammaStar[0,:] = Gamma[VMOPTS.M.value-1,:]
            
            # Apply gust velocity.
            if VMINPUT.gust != None:
                Utot = Ufree + VMINPUT.gust.Vels(Zeta)
            else:
                Utot = Ufree
            
            # Solve for AeroForces
            UVLMLib.Cpp_Solver_VLM(Zeta, ZetaDot, Utot, ZetaStar, VMOPTS, 
                           AeroForces, Gamma, GammaStar, AIC, BIC)
            
            # Apply density scaling
            AeroForces[:,:,:] = AELAOPTS.AirDensity*AeroForces[:,:,:]
            
            if Settings.PlotTec==True:
                PostProcess.WriteUVLMtoTec(FileObject,
                                           Zeta,
                                           ZetaStar,
                                           Gamma,
                                           GammaStar,
                                           TimeStep = iStep,
                                           NumTimeSteps = XBOPTS.NumLoadSteps.value,
                                           Time = Time[iStep],
                                           Text = True)

            # map AeroForces to beam.
            CoincidentGridForce(XBINPUT, PsiDefor, Section, AeroForces,
                                Force)
            
            # Add gravity loads.
            AddGravityLoads(Force, XBINPUT, XBELEM, AELAOPTS,
                            PsiDefor, VMINPUT.c)
            
            # Add thrust and other point loads
            Force += (XBINPUT.ForceStatic + 
                      XBINPUT.ForceDyn*ForceTime[iStep+1]).copy('F')
        #END if iStep > 0
            
            
        #Reset convergence parameters
        Iter = 0
        ResLog10 = 1.0
        
        
        #Newton-Raphson loop      
        while ( (ResLog10 > XBOPTS.MinDelta.value) \
                & (Iter < XBOPTS.MaxIterations.value) ):
                                    
            #set tensors to zero 
            MssFull[:,:] = 0.0; CssFull[:,:] = 0.0
            KssFull[:,:] = 0.0; FstrucFull[:,:] = 0.0
            Msr[:,:] = 0.0; Csr[:,:] = 0.0
            Qstruc[:] = 0.0
            
            MrsFull[:,:] = 0.0; CrsFull[:,:] = 0.0
            KrsFull[:,:] = 0.0; FrigidFull[:,:] = 0.0
            Mrr[:,:] = 0.0; Crr[:,:] = 0.0
            Qrigid[:] = 0.0
    
            Msys[:,:] = 0.0; Csys[:,:] = 0.0
            Ksys[:,:] = 0.0; Asys[:,:] = 0.0;
            Qsys[:] = 0.0
            
            # Update counter.
            Iter += 1
            
            if XBOPTS.PrintInfo.value==True:
                sys.stdout.write('   %-7d ' %(Iter))
                        
            #nodal diplacements and velocities from state vector
            X=Q[:NumDof.value].copy('F') 
            dXdt=dQdt[:NumDof.value].copy('F'); 
            BeamLib.Cbeam3_Solv_State2Disp(XBINPUT,
                                           NumNodes_tot,
                                           XBELEM,
                                           XBNODE,
                                           PosIni,
                                           PsiIni,
                                           NumDof,
                                           X,
                                           dXdt,
                                           PosDefor,
                                           PsiDefor,
                                           PosDotDef,
                                           PsiDotDef)


            #rigid-body velocities and orientation from state vector
            Vrel[iStep+1,:]    = dQdt[NumDof.value:NumDof.value+6].copy('F')
            VrelDot[iStep+1,:] = dQddt[NumDof.value:NumDof.value+6].copy('F')
            Quat = dQdt[NumDof.value+6:].copy('F')
            Quat = Quat/np.linalg.norm(Quat)
            Cao  = xbl.Rot(Quat)


            #Update matrices and loads for structural dynamic analysis
            tmpVrel=Vrel[iStep+1,:].copy('F')
            tmpQuat=Quat.copy('F')
            BeamLib.Cbeam3_Asbly_Dynamic(XBINPUT, NumNodes_tot, XBELEM, XBNODE,\
                                 PosIni, PsiIni, PosDefor, PsiDefor,\
                                 PosDotDef, PsiDotDef, PosDotDotDef, PsiDotDotDef,\
                                 Force, tmpVrel, 0*tmpVrel,\
                                 NumDof, Settings.DimMat,\
                                 ms, MssFull, Msr,\
                                 cs, CssFull, Csr,\
                                 ks, KssFull, fs, FstrucFull,\
                                 Qstruc, XBOPTS, Cao)
            
            BeamLib.f_fem_m2v(ct.byref(NumNodes_tot),\
                              ct.byref(ct.c_int(6)),\
                              Force.ctypes.data_as(ct.POINTER(ct.c_double)),\
                              ct.byref(NumDof),\
                              Force_Dof.ctypes.data_as(ct.POINTER(ct.c_double)),\
                              XBNODE.Vdof.ctypes.data_as(ct.POINTER(ct.c_int)) )
                    
            
            #Update matrices for rigid-body dynamic analysis
            BeamLib.Xbeam_Asbly_Dynamic(XBINPUT, NumNodes_tot, XBELEM, XBNODE,\
                                 PosIni, PsiIni, PosDefor, PsiDefor,\
                                 PosDotDef, PsiDotDef, PosDotDotDef, PsiDotDotDef,\
                                 tmpVrel, 0*tmpVrel, tmpQuat,\
                                 NumDof, Settings.DimMat,\
                                 mr, MrsFull, Mrr,\
                                 cr, CrsFull, Crr, Cqr, Cqq,\
                                 kr, KrsFull, fs, FrigidFull,\
                                 Qrigid, XBOPTS, Cao)
    
            BeamLib.f_fem_m2v_nofilter(ct.byref(NumNodes_tot),\
                                       ct.byref(ct.c_int(6)),\
                                       Force.ctypes.data_as(ct.POINTER(ct.c_double)),\
                                       ct.byref(ct.c_int(NumDof.value+6)),\
                                       Force_All.ctypes.data_as(ct.POINTER(ct.c_double)) )
        
        
            #Residual at first iteration
            if(Iter == 1):
                Res0_Qglobal = max(max(abs(Qsys)),1)
                Res0_DeltaX  = max(max(abs(DQ)),1)
              
            
            #Assemble discrete system matrices with linearised quaternion equations          
            Msys[:NumDof.value,:NumDof.value] = MssFull.copy('F')
            Msys[:NumDof.value,NumDof.value:NumDof.value+6] = Msr.copy('F')
            Msys[NumDof.value:NumDof.value+6,:NumDof.value] = MrsFull.copy('F')
            Msys[NumDof.value:NumDof.value+6,NumDof.value:NumDof.value+6] = Mrr.copy('F')
            Msys[NumDof.value+6:,NumDof.value+6:] = Unit4.copy('F')
            
            Csys[:NumDof.value,:NumDof.value] = CssFull.copy('F')
            Csys[:NumDof.value,NumDof.value:NumDof.value+6] = Csr.copy('F')
            Csys[NumDof.value:NumDof.value+6,:NumDof.value] = CrsFull.copy('F')
            Csys[NumDof.value:NumDof.value+6,NumDof.value:NumDof.value+6] = Crr.copy('F')
            
            Csys[NumDof.value+6:,NumDof.value:NumDof.value+6] = Cqr.copy('F')
            Csys[NumDof.value+6:,NumDof.value+6:] = Cqq.copy('F')
            
            Ksys[:NumDof.value,:NumDof.value] = KssFull.copy('F')
            Ksys[NumDof.value:NumDof.value+6,:NumDof.value] = KrsFull.copy('F')
            
          
#             #Separate assembly of follower and dead loads   
#             tmpForceTime=ForceTime[iStep+1].copy('F') 
#             tmpQforces,Dummy,tmpQrigid = xbl.LoadAssembly(XBINPUT, XBELEM, XBNODE, XBOPTS, NumDof, \
#                                             PosIni, PsiIni, PosDefor, PsiDefor, \
#                                             (XBINPUT.ForceStatic_foll + XBINPUT.ForceDyn_foll*tmpForceTime), \
#                                             (XBINPUT.ForceStatic_dead + XBINPUT.ForceDyn_dead*tmpForceTime), \
#                                             Cao,1)
#                                    
#             Qstruc -= tmpQforces      
#             Qrigid -= tmpQrigid
    
            
            #Compute residual to solve update vector
            Qstruc += -np.dot(FstrucFull, Force_Dof)
            Qrigid += -np.dot(FrigidFull, Force_All)
            
            Qsys[:NumDof.value] = Qstruc
            Qsys[NumDof.value:NumDof.value+6] = Qrigid
            Qsys[NumDof.value+6:] = np.dot(Cqq,dQdt[NumDof.value+6:])
            
            Qsys += np.dot(Msys,dQddt)

                
            #Calculate system matrix for update calculation
            Asys = Ksys + \
                      Csys*gamma/(beta*dt) + \
                      Msys/(beta*dt**2)
                      
            
            #Compute correction
            DQ[:] = np.dot(np.linalg.inv(Asys), -Qsys)

            Q += DQ
            dQdt += DQ*gamma/(beta*dt)
            dQddt += DQ/(beta*dt**2)
            
            
            #Update convergence criteria
            if XBOPTS.PrintInfo.value==True:                 
                sys.stdout.write('%-10.4e ' %(max(abs(Qsys))))
            
            Res_Qglobal = max(abs(Qsys))
            Res_DeltaX  = max(abs(DQ))
            
            ResLog10 = max(Res_Qglobal/Res0_Qglobal,Res_DeltaX/Res0_DeltaX)
            
            if XBOPTS.PrintInfo.value==True:
                sys.stdout.write('%-10.4e %8.4f\n' %(max(abs(DQ)),ResLog10))

        # END Netwon-Raphson.
                
                
        #update to converged nodal displacements and velocities
        X=Q[:NumDof.value].copy('F') 
        dXdt=dQdt[:NumDof.value].copy('F'); 
        BeamLib.Cbeam3_Solv_State2Disp(XBINPUT, NumNodes_tot, XBELEM, XBNODE,
                           PosIni, PsiIni, NumDof, X, dXdt,\
                           PosDefor, PsiDefor, PosDotDef, PsiDotDef)
        
        PosPsiTime[iStep+1,:3] = PosDefor[-1,:]
        PosPsiTime[iStep+1,3:] = PsiDefor[-1,XBELEM.NumNodes[-1]-1,:]
        
        #Position of all grid points in global FoR
        i1 = (iStep+1)*NumNodes_tot.value
        i2 = (iStep+2)*NumNodes_tot.value
        DynOut[i1:i2,:] = PosDefor
        
        #Export rigid-body velocities/accelerations
        if XBOPTS.OutInaframe.value==True:
            Vrel[iStep,:] = dQdt[NumDof.value:NumDof.value+6].copy('F')
            VrelDot[iStep,:] = dQddt[NumDof.value:NumDof.value+6].copy('F')
        else:
            Quat = dQdt[NumDof.value+6:].copy('F')
            Quat = Quat/np.linalg.norm(Quat)
            Cao  = xbl.Rot(Quat)
            ACoa[:3,:3] = np.transpose(Cao)
            ACoa[3:,3:] = np.transpose(Cao)
            
            Vrel[iStep,:] = np.dot(ACoa,dQdt[NumDof.value:NumDof.value+6].copy('F'))
            VrelDot[iStep,:] = np.dot(ACoa,dQddt[NumDof.value:NumDof.value+6].copy('F'))
            
        # Write selected outputs
        # tidy this away using function.
        if 'writeDict' in kwords and Settings.WriteOut == True:
            locForces = None # Stops recalculation of forces
            fp.write("{:<14,e}".format(Time[iStep+1]))
            for myStr in writeDict.keys():
                if re.search(r'^R_.',myStr):
                    if re.search(r'^R_._.', myStr):
                        index = int(myStr[4])
                    elif re.search(r'root', myStr):
                        index = 0
                    elif re.search(r'tip', myStr):
                        index = -1
                    else:
                        raise IOError("Node index not recognised.")
                    
                    if myStr[2] == 'x':
                        component = 0
                    elif myStr[2] == 'y':
                        component = 1
                    elif myStr[2] == 'z':
                        component = 2
                    else:
                        raise IOError("Displacement component not recognised.")
                    
                    fp.write("{:<14,e}".format(PosDefor[index,component]))
                    
                elif re.search(r'^M_.',myStr):
                    if re.search(r'^M_._.', myStr):
                        index = int(myStr[4])
                    elif re.search(r'root', myStr):
                        index = 0
                    elif re.search(r'tip', myStr):
                        index = -1
                    else:
                        raise IOError("Node index not recognised.")
                    
                    if myStr[2] == 'x':
                        component = 0
                    elif myStr[2] == 'y':
                        component = 1
                    elif myStr[2] == 'z':
                        component = 2
                    else:
                        raise IOError("Moment component not recognised.")
                    
                    if locForces == None:
                        locForces = BeamIO.localElasticForces(PosDefor,
                                                              PsiDefor,
                                                              PosIni,
                                                              PsiIni,
                                                              XBELEM,
                                                              [index])
                    
                    fp.write("{:<14,e}".format(locForces[0,3+component]))
                else:
                    raise IOError("writeDict key not recognised.")
            # END for myStr
            fp.write("\n")
            fp.flush()
                    
        # 'Rollup' due to external velocities. TODO: Must add gusts here!
        ZetaStar[:,:] = ZetaStar[:,:] + VMINPUT.U_infty*dt
    
    # END Time loop
    
    # Write _dyn file.
    ofile = Settings.OutputDir + Settings.OutputFileRoot + '_SOL912_dyn.dat'
    fp = open(ofile,'w')
    BeamIO.Write_dyn_File(fp, Time, PosPsiTime)
    fp.close()
    
    #Write _shape file
    ofile = Settings.OutputDir + Settings.OutputFileRoot + '_SOL912_shape.dat'
    fp = open(ofile,'w')
    BeamIO.Write_shape_File(fp, len(Time), NumNodes_tot.value, Time, DynOut)
    fp.close()
    
    #Write rigid-body velocities
    ofile = Settings.OutputDir + Settings.OutputFileRoot + '_SOL912_rigid.dat'
    fp = open(ofile,'w')
    BeamIO.Write_rigid_File(fp, Time, Vrel, VrelDot)
    fp.close()
    
    # Close output file if it exists.
    if 'writeDict' in kwords and Settings.WriteOut == True:
        fp.close()
    
    # Close Tecplot ascii FileObject.
    if Settings.PlotTec==True:
        PostProcess.CloseAeroTecFile(FileObject)
    
    if XBOPTS.PrintInfo.value==True:
        sys.stdout.write(' ... done\n')
        
    # For interactive analysis at end of simulation set breakpoint.
    pass
    based on a frequency of interest.
    @param freq Frequency of interest.
    @param c chord of wing.
    @param Umag mean reltive free-stream velocity magnitude.
    @returns M Number of chordwise panels for wing.
    @returns DelTime Suggested timestep [seconds.]
    """
    k = freq*c/(2*Umag) #get expected reduced freq
    M = int(50.0*k/np.pi) #get adequate panelling
    DelTime = c/(Umag*M) #get resulting DelTime
    return M, DelTime


if __name__ == '__main__':
    # Beam options.
    XBOPTS = DerivedTypes.Xbopts(FollowerForce = ct.c_bool(False),
                                 MaxIterations = ct.c_int(50),
                                 PrintInfo = ct.c_bool(True),
                                 OutInaframe = ct.c_bool(True),
                                 NumLoadSteps = ct.c_int(1),
                                 Solution = ct.c_int(912),
                                 MinDelta = ct.c_double(1e-5),
                                 NewmarkDamp = ct.c_double(5e-3))
    # beam inputs.
    XBINPUT = DerivedTypes.Xbinput(2,4)
    XBINPUT.BeamLength = 6.096
    XBINPUT.BeamStiffness[0,0] = 1.0e+09
    XBINPUT.BeamStiffness[1,1] = 1.0e+09
    XBINPUT.BeamStiffness[2,2] = 1.0e+09
    XBINPUT.BeamStiffness[3,3] = 0.99e+06
    XBINPUT.BeamStiffness[4,4] = 9.77e+06
Example #33
0
 def disableNorm(self):
     """Disable instance-wise normalization"""
     key = 'norm'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(False)))
Example #34
0
 def request_stop_computations(self):
     """Called when user wants to terminate the current computation"""
     rch.set_flag_stop_all(ct.c_bool(True))
     super().request_stop_computations()
 def setInternalPulseMod(self, dOntime, dReptime, bOn=False):
     status = fnLMS_SetFastPulsedOutput(self.device_id, c_float(dOntime), c_float(dReptime), c_bool(bOn))
     self.check_error(status)
Example #36
0
import ctypes as c
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import time
import datetime
import astropy.io.fits as pf

lib = c.cdll.LoadLibrary('libatik.so')
lib.debug(c.c_bool(True))


def timenow():
    return int((datetime.datetime.now().timestamp() * 1e3))


class AtikCaps(c.Structure):
    _fields_ = [("lineCount", c.c_uint), ("pixelCountX", c.c_uint),
                ("pixelCountY", c.c_uint), ("pixelSizeX", c.c_double),
                ("pixelSizeY", c.c_double), ("maxBinX", c.c_uint),
                ("maxBinY", c.c_uint), ("tempSensorCount", c.c_uint),
                ("offsetX", c.c_int), ("offsetY", c.c_int),
                ("supportsLongExposure", c.c_bool),
                ("minShortExposure", c.c_double),
                ("maxShortExposure", c.c_double)]


class AtikCam:
    def __init__(self):
        count = 0
        while count < 1:
Example #37
0
 def _00E0(self):
     """
     CLS: Clear the display
     """
     self.display = [ [c_bool(False) for x in range(64)] for y in range(32) ]
Example #38
0
 def setSigmoid(self):
     """Convert output by using sigmoid"""
     key = 'sigmoid'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(True)))
Example #39
0
 def setSign(self):
     """Convert output to 0 and 1"""
     key = 'sign'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(True)))
Example #40
0
    def __init__(self, g_pool, atb_pos=(320, 220)):
        super(Marker_Detector, self).__init__()
        self.g_pool = g_pool
        self.order = .2

        # all markers that are detected in the most recent frame
        self.markers = []
        # all registered surfaces

        if g_pool.app == 'capture':
            self.surface_definitions = shelve.open(os.path.join(
                g_pool.user_dir, 'surface_definitions'),
                                                   protocol=2)
            self.surfaces = [
                Reference_Surface(saved_definition=d)
                for d in self.load('realtime_square_marker_surfaces', [])
                if isinstance(d, dict)
            ]
        elif g_pool.app == 'player':
            #in player we load from the rec_dir: but we have a couple options:
            self.surface_definitions = shelve.open(os.path.join(
                g_pool.rec_dir, 'surface_definitions'),
                                                   protocol=2)
            if self.load('offline_square_marker_surfaces', []) != []:
                logger.debug(
                    "Found ref surfaces defined or copied in previous session."
                )
                self.surfaces = [
                    Reference_Surface(saved_definition=d)
                    for d in self.load('offline_square_marker_surfaces', [])
                    if isinstance(d, dict)
                ]
            elif self.load('offline_square_marker_surfaces', []) != []:
                logger.debug(
                    "Did not find ref surfaces def created or used by the user in player from earlier session. Loading surfaces defined during capture."
                )
                self.surfaces = [
                    Reference_Surface(saved_definition=d)
                    for d in self.load('realtime_square_marker_surfaces', [])
                    if isinstance(d, dict)
                ]
            else:
                logger.debug("No surface defs found. Please define using GUI.")
                self.surfaces = []
        # edit surfaces
        self.surface_edit_mode = c_bool(0)
        self.edit_surfaces = []

        #detector vars
        self.robust_detection = c_bool(1)
        self.aperture = c_int(11)
        self.min_marker_perimeter = 80

        #debug vars
        self.draw_markers = c_bool(0)
        self.show_surface_idx = c_int(0)
        self.recent_pupil_positions = []

        self.img_shape = None

        #multi monitor setup
        self.window_should_open = False
        self.window_should_close = False
        self._window = None
        self.fullscreen = c_bool(0)
        self.monitor_idx = c_int(0)
        monitor_handles = glfwGetMonitors()
        self.monitor_names = [glfwGetMonitorName(m) for m in monitor_handles]
        monitor_enum = atb.enum(
            "Monitor",
            dict(((key, val) for val, key in enumerate(self.monitor_names))))
        #primary_monitor = glfwGetPrimaryMonitor()

        atb_label = "marker detection"
        self._bar = atb.Bar(name=self.__class__.__name__,
                            label=atb_label,
                            help="marker detection parameters",
                            color=(50, 50, 50),
                            alpha=100,
                            text='light',
                            position=atb_pos,
                            refresh=.3,
                            size=(300, 100))
        self._bar.add_var(
            "monitor",
            self.monitor_idx,
            vtype=monitor_enum,
            group="Window",
        )
        self._bar.add_var("fullscreen", self.fullscreen, group="Window")
        self._bar.add_button("  open Window   ",
                             self.do_open,
                             key='m',
                             group="Window")
        self._bar.add_var("surface to show",
                          self.show_surface_idx,
                          step=1,
                          min=0,
                          group="Window")
        self._bar.add_var('robust_detection',
                          self.robust_detection,
                          group="Detector")
        self._bar.add_var("draw markers", self.draw_markers, group="Detector")
        self._bar.add_button('close', self.unset_alive)

        atb_pos = atb_pos[0], atb_pos[1] + 110
        self._bar_markers = atb.Bar(name=self.__class__.__name__ + 'markers',
                                    label='registered surfaces',
                                    help="list of registered ref surfaces",
                                    color=(50, 100, 50),
                                    alpha=100,
                                    text='light',
                                    position=atb_pos,
                                    refresh=.3,
                                    size=(300, 120))
        self.update_bar_markers()
Example #41
0
 def disableLockFree(self):
     """Disable lock free training"""
     key = 'lock_free'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(False)))
Example #42
0
    def has_block(self, block_id):
        result = ctypes.c_bool()

        _libexec('chain_controller_has_block', self.pointer,
                 ctypes.c_char_p(block_id.encode()), ctypes.byref(result))
        return result.value
Example #43
0
def fastPD(
    unary,
    pairs,
    binary,
    wpairs=None,
    niters=100,
    debug=False,
):
    ''' MRF solve
    
        with N nodes, L labels, P pairs
    
    args:   
        unary: N x L array (unary potentials)
        pairs: P x 2 array (vertex indices for each pair)
        binary: L x L array (potential for each pair of labels)
        wpairs: P x 1 array (potential for each pair. All set to 1. if None)
        niters: (number of iterations. default is 100)
        
    returns:
        results: N x 1 array (computed label for each None)
        energy: (energy value of solution)
    
    '''

    unary_ = np.array(unary, dtype=np.float32)
    pairs_ = np.asarray(pairs, dtype=np.int32)
    binary_ = np.asarray(binary, dtype=np.float32)

    if wpairs is None:
        wedges_ = np.ones(len(pairs_)).astype(np.float32)
    else:
        wedges_ = wpairs.astype(np.float32)

    nnodes = unary_.shape[0]
    nlabels = unary_.shape[1]
    npairs = pairs_.shape[0]

    results = np.zeros(nnodes, dtype=np.int32)

    max_iter = niters

    energy = _libFastPD.fastPD(
        ctypes.c_int32(nnodes),
        ctypes.c_int32(nlabels),
        unary_.flatten(),
        ctypes.c_int32(npairs),
        pairs_.flatten(),
        binary_.flatten(),
        wedges_,
        results,
        ctypes.c_int32(max_iter),
        ctypes.c_bool(debug),
    )
    '''
    int nnodes,           // number of nodes
    int nlabels,          // number of labels
    T const* unary,       // unary potentials
    int npairs,           // number of pairs
    int const * pairs,    // pairs (ith pair = pairs[2*i], pairs[2*i+1])
    T const * binary,     // binary potentials
    T const * wedges,     // edge weighting
    int* results,         // return array
    int max_iter,         // max number of iterations
    bool debug            // print debug info
    '''

    del unary_, pairs_, binary_, wedges_

    return results, energy
Example #44
0
    def connect(self, host="localhost", port=27017, username=None,
                password=None, database=None, p_file=None,
                pem_pwd=None, ca_file=None, ca_dir=None, c_file=None,
                weak_cert_validation=False, options=None):
        """Connects to the given host and port.

           :param host: either host name (or IP) to connect to, or full URI
           :param port: port number of running MongoDB service on host
           :param username: An optional username for authentication.
           :param password: An optional password for authentication.
           :param database: The database to authenticate to if the URI
           specifies a username and password. If this is not specified but
           credentials exist, this defaults to the "admin" database. See
           mongoc_uri(7).
           :param p_file: SSL certificate and key file
           :param pem_pwd: Passphrase for encrypted key file
           :param ca_file: Certificate authority file
           :param ca_dir: Directory for certificate authority files
           :param c_file: Certificate revocation list file
           :param weak_cert_validation: bypass validation
           :param options: Connection-specific options as a dict.

           :returns: True if successful; false otherwise.
           :rtype: bool
        """
        if self._connection is not None:
            self.close()

        if host.startswith("mongodb://"):
            uri = host
        else:
            # Build up the URI string.
            uri = ["mongodb://"]
            if username is not None:
                if password is None:
                    uri.append("%s@" % username)
                else:
                    uri.append("%s:%s@" % (username, password))
            elif password is not None:
                raise ValueError("You cannot have a password with no"
                                 " username.")

            uri.append("%s:%d" % (host, port))

            if database is not None:
                uri.append("/%s" % database)
            if options is not None:
                uri.append("?%s" % urlencode(options))
            uri = "".join(uri)

        if sys.version >= "3":
            p_file = bytes(p_file, "ascii") if p_file is not None else None
            pem_pwd = bytes(pem_pwd, "ascii") if pem_pwd is not None else None
            ca_file = bytes(ca_file, "ascii") if ca_file is not None else None
            ca_dir = bytes(ca_dir, "ascii") if ca_dir is not None else None
            c_file = bytes(c_file, "ascii") if c_file is not None else None

        # Attempt the connection.
        err = get_empty_bson_error()
        self._connection = cmonary.monary_connect(
            uri.encode('ascii'),
            ctypes.c_char_p(p_file),
            ctypes.c_char_p(pem_pwd),
            ctypes.c_char_p(ca_file),
            ctypes.c_char_p(ca_dir),
            ctypes.c_char_p(c_file),
            ctypes.c_bool(weak_cert_validation),
            ctypes.byref(err))
        if self._connection is None:
            raise MonaryError(err.message)
 def __init__(self, bTestMode=False):
     """The init case defines a session ID, used to identify the instrument"""
     fnLMS_SetTestMode(c_bool(bTestMode))
     self.device_id = None
Example #46
0
pythonapi.PyCObject_AsVoidPtr.restype = c_void_p
pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object]

prototype = WINFUNCTYPE(c_int, c_int, POINTER(MARGINS))
params = (1, "hWnd", 0), (1, "pMarInset", MARGINS(-1, -1, -1, -1))
_DwmExtendFrameIntoClientArea = prototype(
    ("DwmExtendFrameIntoClientArea", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, c_int, POINTER(DWM_BLURBEHIND))
params = (1, "hWnd", 0), (1, "pBlurBehind", 0)
_DwmEnableBlurBehindWindow = prototype(
    ("DwmEnableBlurBehindWindow", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, POINTER(DWORD), POINTER(c_bool))
params = (2, "pcrColorization", DWORD(0)), (1, "pfOpaqueBlend", c_bool(False))
_DwmGetColorizationColor = prototype(
    ("DwmGetColorizationColor", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, POINTER(c_bool))
params = (2, "pfEnabled", c_bool(False)),
_DwmIsCompositionEnabled = prototype(
    ("DwmIsCompositionEnabled", windll.dwmapi), params)

# Before we get started, see if we have the DWM functions.
has_dwm = hasattr(windll, 'dwmapi') and \
          hasattr(windll.dwmapi, 'DwmIsCompositionEnabled')


def DWM_is_composition_enabled():
    """
 def setExternalPulseMod(self, bOn=False):
     status = fnLMS_SetUseExternalPulseMod(self.device_id, c_bool(bOn))
     self.check_error(status)
Example #48
0
 def setQuiet(self):
     """Set xlearn to quiet model"""
     key = 'quiet'
     _check_call(
         _LIB.XLearnSetBool(self.handle, c_str(key), ctypes.c_bool(True)))
Example #49
0
    def Calc(self, f=None):
        """Calculate the theory"""

        # get parameters
        tau = self.parameters["tau"].value
        beta = self.parameters["beta"].value
        lambda_ = self.parameters["lambda"].value
        sigma = self.parameters["sigma"].value
        numtomake = np.round(self.parameters["num_to_make"].value)
        monmass = self.parameters["mon_mass"].value
        Me = self.parameters["Me"].value
        nbins = int(np.round(self.parameters["nbin"].value))
        rch.set_do_prio_senio(ct.c_bool(self.do_priority_seniority))
        rch.set_flag_stop_all(ct.c_bool(False))

        c_ndist = ct.c_int()

        # resize theory datatable
        ft = f.data_table
        ft = f.data_table
        tt = self.tables[f.file_name_short]
        tt.num_columns = ft.num_columns
        tt.num_rows = 1
        tt.data = np.zeros((tt.num_rows, tt.num_columns))

        if not self.dist_exists:
            success = rch.request_dist(ct.byref(c_ndist))
            self.ndist = c_ndist.value
            if not success:
                # launch dialog asking for more dist
                self.signal_request_dist.emit(
                    self
                )  # use signal to open QDialog in the main GUI window
                return
            else:
                self.dist_exists = True
        ndist = self.ndist
        # rch.react_dist[ndist].contents.name = self.reactname #TODO: set the dist name in the C library
        rch.react_dist[ndist].contents.M_e = Me
        rch.react_dist[ndist].contents.monmass = monmass
        rch.react_dist[ndist].contents.nummwdbins = nbins
        rch.react_dist[ndist].contents.polysaved = False
        rch.react_dist[ndist].contents.nsaved_arch = 0
        rch.react_dist[ndist].contents.arch_minwt = self.xmin
        rch.react_dist[ndist].contents.arch_maxwt = self.xmax
        rch.init_bin_prio_vs_senio(ndist)

        if self.simexists:
            rch.return_dist_polys(ct.c_int(ndist))

        # initialise tobita batch
        rch.tobCSTRstart(
            ct.c_double(tau),
            ct.c_double(beta),
            ct.c_double(sigma),
            ct.c_double(lambda_),
            ct.c_int(ndist),
        )
        rch.react_dist[ndist].contents.npoly = 0

        c_m = ct.c_int()

        # make numtomake polymers
        i = 0
        rate_print = np.trunc(numtomake / 20)
        self.Qprint("Making polymers:")
        self.Qprint("0% ", end="")
        while i < numtomake:
            if self.stop_theory_flag:
                self.Qprint(
                    "<br><big><font color=red><b>Polymer creation stopped by user</b></font></big>"
                )
                break
            # get a polymer
            success = rch.request_poly(ct.byref(c_m))
            m = c_m.value
            if success:  # check availability of polymers
                # put it in list
                if (
                    rch.react_dist[ndist].contents.npoly == 0
                ):  # case of first polymer made
                    rch.react_dist[ndist].contents.first_poly = m
                    rch.set_br_poly_nextpoly(
                        ct.c_int(m), ct.c_int(0)
                    )  # br_poly[m].contents.nextpoly = 0
                else:  # next polymer, put to top of list
                    rch.set_br_poly_nextpoly(
                        ct.c_int(m), ct.c_int(rch.react_dist[ndist].contents.first_poly)
                    )  # br_poly[m].contents.nextpoly = rch.react_dist[ndist].contents.first_poly
                    rch.react_dist[ndist].contents.first_poly = m

                # make a polymer
                if rch.tobCSTR(
                    ct.c_int(m), ct.c_int(ndist)
                ):  # routine returns false if arms ran out
                    rch.react_dist[ndist].contents.npoly += 1
                    i += 1
                    # check for error
                    if rch.tCSTR_global.tobitaCSTRerrorflag:
                        self.Qprint(
                            "<br><big><font color=red><b>Polymers too large: gelation occurs for these parameters</b></font></big>"
                        )
                        i = numtomake
                else:  # error message if we ran out of arms
                    self.success_increase_memory = None
                    self.signal_request_arm.emit(self)
                    while (
                        self.success_increase_memory is None
                    ):  # wait for the end of QDialog
                        time.sleep(
                            0.5
                        )  # TODO: find a better way to wait for the dialog thread to finish
                    if self.success_increase_memory:
                        continue  # back to the start of while loop
                    else:
                        i = numtomake
                        rch.tCSTR_global.tobitaCSTRerrorflag = True

                # update on number made
                if i % rate_print == 0:
                    self.Qprint("-", end="")
                    # needed to use Qprint if in single-thread
                    QApplication.processEvents()

            else:  # polymer wasn't available
                self.success_increase_memory = None
                self.signal_request_polymer.emit(self)
                while self.success_increase_memory is None:
                    time.sleep(
                        0.5
                    )  # TODO: find a better way to wait for the dialog thread to finish
                if self.success_increase_memory:
                    continue
                else:
                    i = numtomake
        # end make polymers loop
        if not rch.tCSTR_global.tobitaCSTRerrorflag:
            self.Qprint("&nbsp;100%")

        calc = 0
        # do analysis of polymers made
        if (rch.react_dist[ndist].contents.npoly >= 100) and (
            not rch.tCSTR_global.tobitaCSTRerrorflag
        ):
            rch.molbin(ndist)
            ft = f.data_table

            # resize theory data table
            ft = f.data_table
            tt = self.tables[f.file_name_short]
            tt.num_columns = ft.num_columns + 2
            tt.num_rows = rch.react_dist[ndist].contents.nummwdbins
            tt.data = np.zeros((tt.num_rows, tt.num_columns))

            for i in range(1, rch.react_dist[ndist].contents.nummwdbins + 1):
                tt.data[i - 1, 0] = np.power(
                    10, rch.react_dist[ndist].contents.lgmid[i]
                )
                tt.data[i - 1, 1] = rch.react_dist[ndist].contents.wt[i]
                tt.data[i - 1, 2] = rch.react_dist[ndist].contents.avg[i]
                tt.data[i - 1, 3] = rch.react_dist[ndist].contents.avbr[i]
            rch.end_print(self, ndist, self.do_priority_seniority)
            rch.prio_and_senio(self, f, ndist, self.do_priority_seniority)

            calc = rch.react_dist[ndist].contents.nummwdbins - 1
            rch.react_dist[ndist].contents.polysaved = True

        self.simexists = True
        # self.Qprint('%d arm records left in memory' % rch.pb_global.arms_left)
        # rch.print_arch_stats(ct.c_int(ndist))
        return calc
Example #50
0
def sign_file_with_certificate(input_file, output_file, founded_certs_list):
    signer_num = 0
    # Creating array of CMSG_SIGNER_ENCODE_INFO for all founded certs
    signer_infos = (crypto_support.CMSG_SIGNER_ENCODE_INFO *
                    len(founded_certs_list))()
    SignInfo = crypto_support.CMSG_SIGNED_ENCODE_INFO()
    SignInfo.cSigners = len(founded_certs_list)
    SignInfo.rgSigners = ctypes.cast(
        signer_infos, ctypes.POINTER(crypto_support.CMSG_SIGNER_ENCODE_INFO))
    SignInfo.cbSize = ctypes.sizeof(crypto_support.CMSG_SIGNED_ENCODE_INFO)
    for cert in founded_certs_list:
        # acquire private key
        SignerInfo = crypto_support.CMSG_SIGNER_ENCODE_INFO()
        SignerInfo.cbSize = ctypes.sizeof(
            crypto_support.CMSG_SIGNER_ENCODE_INFO)
        acquire_flags = crypto_support.CRYPT_ACQUIRE_COMPARE_KEY_FLAG | \
                        crypto_support.CRYPT_ACQUIRE_CACHE_FLAG
        privkey_keyprov = ctypes.c_ulong()
        privkey_keyspec = ctypes.c_ulong()
        privkey_needsfree = ctypes.c_bool(crypto_support.FALSE)
        if not crypto_support.fCryptAcquireCertificatePrivateKey(
                cert, acquire_flags, 0, ctypes.pointer(privkey_keyprov),
                ctypes.pointer(privkey_keyspec),
                ctypes.pointer(privkey_needsfree)):
            raise ctypes.WinError()
        SignerInfo.hCryptProv = privkey_keyprov
        SignerInfo.dwKeySpec = privkey_keyspec
        # TODO: install pin
        # fill in CMSG_SIGNER_ENCODE_INFO
        SignerInfo.HashAlgorithm.Parameters.cbData = crypto_support.DWORD(0)
        SignerInfo.pCertInfo = cert.contents.pCertInfo
        SignerInfo.cAuthAttr = crypto_support.DWORD(0)
        SignerInfo.rgAuthAttr = None
        SignerInfo.cUnauthAttr = crypto_support.DWORD(0)
        SignerInfo.rgUnauthAttr = None
        # fill in hash oid
        pubKeyOID = cert.contents.pCertInfo.contents.SubjectPublicKeyInfo.Algorithm.pszObjId
        SignerInfo.HashAlgorithm.pszObjId = crypto_support.LPSTR(
            GetDefaultOIDfromPubKeyOID(pubKeyOID.decode()).encode('utf-8'))
        # fill in CMSG_SIGNED_ENCODE_INFO
        SignInfo.rgSigners[signer_num] = SignerInfo
        signer_num += 1
        # TODO: add certificate
        # TODO: add CRL
    encoding_type = crypto_support.X509_ASN_ENCODING | crypto_support.PKCS_7_ASN_ENCODING
    # open input file
    input_file_handle = open(input_file, 'rb')
    input_file_data = input_file_handle.read()
    # cast file date into BYTE*
    file_data_pointer = ctypes.pointer(
        (ctypes.c_ubyte *
         len(input_file_data)).from_buffer_copy(input_file_data))
    file_data_pointer = ctypes.cast(file_data_pointer,
                                    ctypes.POINTER(crypto_support.BYTE))
    # calculated resulting length
    encoded_len = crypto_support.fCryptMsgCalculateEncodedLength(
        encoding_type, 0, crypto_support.CMSG_SIGNED,
        ctypes.c_void_p(ctypes.addressof(SignInfo)), None,
        crypto_support.DWORD(len(input_file_data)))
    # open message to encode with sign info
    message_handle = crypto_support.fCryptMsgOpenToEncode(
        encoding_type, 0, crypto_support.CMSG_SIGNED,
        ctypes.c_void_p(ctypes.addressof(SignInfo)), None, None)
    if not message_handle:
        raise ctypes.WinError()
    # update message with input data
    if not crypto_support.fCryptMsgUpdate(message_handle, file_data_pointer,
                                          len(input_file_data),
                                          crypto_support.TRUE):
        raise ctypes.WinError()
    # save signed data to file
    # Allocating buffer for CMSG_CONTENT_PARAM
    message_buffer = (ctypes.c_ubyte * encoded_len)()
    message_buffer_pointer = ctypes.cast(message_buffer,
                                         ctypes.POINTER(crypto_support.BYTE))
    # Get message content
    if not crypto_support.fCryptMsgGetParam(
            message_handle, crypto_support.CMSG_CONTENT_PARAM, 0,
            message_buffer_pointer,
            ctypes.byref(crypto_support.DWORD(encoded_len))):
        return ctypes.WinError()
    # cast string into data to save into signature file
    signed_data = ctypes.string_at(message_buffer_pointer, encoded_len)
    # open output signature file
    output_file_handle = open(output_file, 'wb')
    #output_file_handle.write(signed_data[:encoded_len])
    output_file_handle.write(signed_data)
    output_file_handle.close()
    if not crypto_support.fCryptMsgClose(message_handle):
        raise ctypes.WinError()
    print('Successfully signed!')
Example #51
0
def is_process32(hProcess):
    """检查目标进程是否32位"""
    # https://docs.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process?redirectedfrom=MSDN
    ret = ctypes.c_bool()
    ctypes.windll.kernel32.IsWow64Process(hProcess, ctypes.byref(ret))
    return not ret.value
Example #52
0
 def setOnDisk(self):
     """Set xlearn to use on-disk training"""
     key = 'on_disk'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(True)))
Example #53
0
def SetProtection():
 windll.ntdll.RtlAdjustPrivilege(20, 1, 0, byref(c_bool()))
 windll.ntdll.RtlSetProcessIsCritical(1, 0, 0) == 0
Example #54
0
def init(target_dtype='float16', target_precision_ops=None,
         conditional_fp32_ops=None, fp32_ops=None, layout_optimization=False):
    """Initialize AMP (automatic mixed precision).

    This needs to be done before model creation.

    Parameters
    ----------
    target_dtype : {'float16', 'bfloat16'}
        Target low precision type for AMP. Currently only float16 and bfloat16 are supported.
    target_precision_ops : list of string
        Override the list of functions casted to target_dtype. Entries in this list
        are names of the functions casted to target_dtype.
    conditional_fp32_ops : list of (string, string, list of string)
        Override the list of functions conditionally casted to FP32. The format
        of the list is (name of the function, name of the parameter, list of
        values of the parameter that make the function be casted to FP32).
    fp32_ops : list of string
        Override the list of functions casted to FP32. Entries in this list
        are names of the functions casted to FP32.
    """
    global _amp_initialized
    global _loss_scaler
    if not _amp_initialized:
        assert target_dtype in ['float16', np.float16, 'bfloat16', bfloat16], \
               "AMP currently supports only float16 or bfloat16 as a target_dtype"
        _amp_initialized = True
        log_msg = "Using AMP"
        if layout_optimization:
            log_msg += "\n - layout optimization: enabled"
            check_call(_LIB.MXSetOptimizeLayout(ctypes.c_bool(True)))
        logging.info(log_msg)
        if target_dtype == "bfloat16":
            target_dtype = bfloat16
        else:
            target_dtype = np.dtype(target_dtype)

        warn_if_model_exists()

        ops = get_all_registered_operators_grouped()
        get_aliases_nd = lambda l: [a for op in l for a in ops[op] if not base._is_np_op(a)]
        get_aliases_np = lambda l: [a for op in l for a in ops[op] if base._is_np_op(a)]
        get_aliases_np_pub = lambda l: [a for op in l for a in ops[op]
                                        if a.startswith(('_np_', '_npx_'))]
        get_cond_aliases_nd = lambda l: [(a, *rest) for op, *rest in l for a in ops[op]
                                         if not base._is_np_op(a)]
        get_cond_aliases_np = lambda l: [(a, *rest) for op, *rest in l for a in ops[op]
                                         if base._is_np_op(a)]
        get_cond_aliases_np_pub = lambda l: [(a, *rest) for op, *rest in l for a in ops[op]
                                             if a.startswith(('_np_', '_npx_'))]
        sy_submodules = {p:getattr(symbol, p[1:-1]) for p in base._OP_NAME_PREFIX_LIST}
        get_sy_fun = lambda fun, mod: _get_nd_fun_to_wrap(fun, mod, sy_submodules)
        nd_submodules = {p:getattr(ndarray, p[1:-1]) for p in base._OP_NAME_PREFIX_LIST}
        get_nd_fun = lambda fun, mod: _get_nd_fun_to_wrap(fun, mod, nd_submodules)
        get_np_sy_fun = lambda fun, mod: _get_np_fun_to_wrap(fun, "mxnet.symbol")
        get_np_nd_fun = lambda fun, mod: _get_np_fun_to_wrap(fun, "mxnet.ndarray")
        get_np_fun = lambda fun, mode: _get_np_fun_to_wrap(fun, "mxnet")
        todo = [
            (symbol, False, get_aliases_nd, get_cond_aliases_nd, get_sy_fun),
            (ndarray, False, get_aliases_nd, get_cond_aliases_nd, get_nd_fun),
            (symbol.numpy, True, get_aliases_np, get_cond_aliases_np, get_np_sy_fun),
            (ndarray.numpy, True, get_aliases_np, get_cond_aliases_np, get_np_nd_fun),
            (numpy, True, get_aliases_np_pub, get_cond_aliases_np_pub, get_np_fun),
        ]
        _loss_scaler = LossScaler()
        for module, is_numpy, get_aliases, get_cond_aliases, get_fun in todo:
            _wrap_module_functions(module, is_numpy, target_dtype, get_aliases, get_cond_aliases,
                                   get_fun, target_precision_ops, conditional_fp32_ops, fp32_ops)
            _wrap_loss_output_functions(module, _loss_scaler, target_dtype)
Example #55
0
    def __init__(self,
                 testing_sdk=None,
                 testing_zi_sdk=None,
                 sdk_version=None):

        if sdk_version == 64:
            self.sdk_location = os.path.join(os.path.dirname(__file__),
                                             'SidekickSDKx64.dll')
        elif sdk_version == 86:
            self.sdk_location = os.path.join(os.path.dirname(__file__),
                                             'SidekickSDKx86.dll')
        elif platform.machine().endswith('64'):
            self.sdk_location = os.path.join(os.path.dirname(__file__),
                                             'SidekickSDKx64.dll')
        else:
            self.sdk_location = os.path.join(os.path.dirname(__file__),
                                             'SidekickSDKx86.dll')

        ## @name Timing_Variables
        # Variables for timing of setting parameters. Names indicate function.
        # @{

        ## Time allowed for QCL paramters to be set.
        self.qcl_set_params_timeout = 5
        ## Time allowed for the laser to be armed.
        self.arm_laser_timeout = 20
        ## Time allowed to attempt to cool the TECs to desired temperature.
        self.cool_tecs_timeout = 60
        ## Additional time allowed for cooling of the TECs.
        self.cool_tecs_additional = 10
        ## Time allowed to turn on the laser itself.
        self.turn_on_laser_timeout = 30
        ## Number of attempts allowed for trying to turn on the laser.
        self.laser_on_attempts = 3
        ## Time to wait after the laser has been turned on for normalization of operation.
        self.laser_on_wait = 5
        # @}

        ## @name Laser_State
        # State of all variable laser parameters. Initialized to default, safe
        # experiment values.
        # @{

        ## Whether or not the laser is on.
        self.laser_on = False
        ## Current from the QCL in MilliAmps.
        self.qcl_current_ma = 1500
        ## Pulse rate of the laser in Hertz according to the QCL.
        self.qcl_pulse_rate_hz = 15000
        ## Pulse width of the laser in nanoseconds according to the QCL.
        self.qcl_pulse_width_ns = 500
        ## Laser wavelength in the units specified by the next parameter.
        self.wavelength = 1020
        ## Wavelength units, defaults to 2, which cooresponds to wavenumber.
        self.qcl_wvlen_units = 2
        ## QCL temperature, kept constant. In Degrees Celsius.
        self.qcl_temp = 17

        #@}

        ## @name Lockin_Parameters
        # All necessary communication information for the Lock In.
        #@{

        ## IP of the device
        self.lockin_ip = '192.168.48.102'
        ## Port to use for communication
        self.lockin_port = 8004
        ## Amplitude modulation factor.
        self.lockin_amplitude = 1.0
        ## Poll sample length for the lock in.
        self.lockin_poll_length = 30
        ## Demod channel, for paths on the device.
        self.lockin_demod_c = '0'
        ## Signal input channel
        self.lockin_in_c = '0'
        ## Oscillator variable.
        self.lockin_osc_c = '0'
        ## Oscillation frequency, 30e5 #[Hz] this matches the laser controller
        self.lockin_osc_freq = 100000
        ## Time constant, set to 3e-3 # 0.0075 # 0.001  [s]
        self.lockin_time_constant = 1e-2  #
        ## Demod index for the channel.
        self.demod_idx = float(self.lockin_demod_c) + 1
        ## Time allowed to poll data in ms
        self.poll_timeout = 500
        ## Demod rate of 80 # 300 [samples / s]
        self.demod_rate = 2e3

        #@}

        ## @name Sidekick_SDK_Variables
        # Variables required for and set by Sidekick SDK setup.
        #@{

        ## Used to see if the SDK is indeed retrieved.
        self.sidekick_sdk_ret_success = 0
        ## SDK object used to access all laser operation functions.
        self.sdk = CDLL(
            self.sdk_location) if testing_sdk is None else testing_sdk
        ## Zurich Instrumentes SDK for lockin actions.
        self.zi_sdk = zhinst if testing_zi_sdk is None else testing_zi_sdk

        self.__call_sdk_bool(self.sdk.SidekickSDK_Initialize,
                             'SDK initialization successful',
                             'Unable to initialize SDK')
        ## Daylight SDK Object pointer to pass to laser functions.
        self.handle = None
        ## ZI sdk object pointer for lock-in function.
        self.device = None
        ## DAQ object for lockin setup.
        self.daq = None

        #@}

        ## @name Parameter_Bounds
        #  Stores safe operating constraints for all manipulated parameters.
        #@{

        ## Maximum safe current in mA for operation of this laser.
        self.max_current = 1600
        ## Minimum safe current in mA for operation of this laser.
        self.min_current = 1200
        ## Maximum wavelength (in wavenumbers) able to be reached by this laser.
        self.max_wavelength = 1250
        ## Minimum wavelength (in wavenumbers) able to be reached by this laser.
        self.min_wavelength = 950
        ## Maximum pulse rate in Hz that this laser can safely operate at.
        self.max_pulse_rate = 15000
        ## Minimum pulse rate in Hz that this laser can safely operate at.
        self.min_pulse_rate = 5000
        ## Maximum pulse width in ns for safe operation of the laser.
        self.max_pulse_width = 2500
        ## Minimum pulse width in ns for safe operation of the laser.
        self.min_pulse_width = 500

        #@}

        ## @name Set_Parameter_Constants
        # Constants required for setting laser parameters.
        #@{

        ## Reading requires passing false to readwrite functions.
        self.qcl_read = c_bool(False)
        ## Writing requires passing true to readwrite functions.
        self.qcl_write = c_bool(True)
        ## Sets up SIDEKICK_SDK_SCAN_START_STEP_MEASURE as operation.
        self.scan_operation = c_uint8(7)
        ## Does not permit bidirectional scans.
        self.bidirectional_scans = c_uint8(0)
        ## Performs just a single scan per call.
        self.scan_count = c_uint16(1)
        ## Maintains laser emission between steps.
        self.keep_on = c_uint8(1)
        ## Dummy parameter for function which is meant for non SideKick Projects.
        self.pref_qcl = c_uint8(0)

        #@}

        ## Thread object for collecting data when the laser is in operation.
        self.poll_thread = None

        ## Array into which data observed from the sensor is written.
        self.data = []

        ## Array into which time data corresponding to observation data is stored.
        self.time_axis = []

        self.__startup()
Example #56
0
 def GetPeerOs(self):
     b = c_bool()
     os = scl.GetPeerOs(self.Handle, byref(b))
     return os, b.value
Example #57
0
    def __init__(self, config, **kwargs):
        """
        Parameters
        ----------
        config: str or Config Object
            if config is a string, then it is a name of builtin config,
                builtin config are stored in python/magent/builtin/config
                kwargs are the arguments to the config
            if config is a Config Object, then parameters are stored in that object
        """
        Environment.__init__(self)

        # if is str, load built in configuration
        if isinstance(config, str):
            # built-in config are stored in python/magent/builtin/config
            try:
                demo_game = importlib.import_module('magent.builtin.config.' +
                                                    config)
                config = getattr(demo_game, 'get_config')(**kwargs)
            except AttributeError:
                raise BaseException('unknown built-in game "' + config + '"')

        # create new game
        game = ctypes.c_void_p()
        _LIB.env_new_game(ctypes.byref(game), b"GridWorld")
        self.game = game

        # set global configuration
        config_value_type = {
            'map_width': int,
            'map_height': int,
            'food_mode': bool,
            'turn_mode': bool,
            'minimap_mode': bool,
            'revive_mode': bool,
            'goal_mode': bool,
            'embedding_size': int,
            'render_dir': str,
        }

        for key in config.config_dict:
            value_type = config_value_type[key]
            if value_type is int:
                _LIB.env_config_game(
                    self.game, key.encode("ascii"),
                    ctypes.byref(ctypes.c_int(config.config_dict[key])))
            elif value_type is bool:
                _LIB.env_config_game(
                    self.game, key.encode("ascii"),
                    ctypes.byref(ctypes.c_bool(config.config_dict[key])))
            elif value_type is float:
                _LIB.env_config_game(
                    self.game, key.encode("ascii"),
                    ctypes.byref(ctypes.c_float(config.config_dict[key])))
            elif value_type is str:
                _LIB.env_config_game(self.game, key.encode("ascii"),
                                     ctypes.c_char_p(config.config_dict[key]))

        # register agent types
        for name in config.agent_type_dict:
            type_args = config.agent_type_dict[name]

            # special pre-process for view range and attack range
            for key in [x for x in type_args.keys()]:
                if key == "view_range":
                    val = type_args[key]
                    del type_args[key]
                    type_args["view_radius"] = val.radius
                    type_args["view_angle"] = val.angle
                elif key == "attack_range":
                    val = type_args[key]
                    del type_args[key]
                    type_args["attack_radius"] = val.radius
                    type_args["attack_angle"] = val.angle

            length = len(type_args)
            keys = (ctypes.c_char_p *
                    length)(*[key.encode("ascii") for key in type_args.keys()])
            values = (ctypes.c_float * length)(*type_args.values())

            _LIB.gridworld_register_agent_type(self.game, name.encode("ascii"),
                                               length, keys, values)

        # serialize event expression, send to C++ engine
        self._serialize_event_exp(config)

        # init group handles
        self.group_handles = []
        for item in config.groups:
            handle = ctypes.c_int32()
            _LIB.gridworld_new_group(self.game, item.encode("ascii"),
                                     ctypes.byref(handle))
            self.group_handles.append(handle)

        # init observation buffer (for acceleration)
        self._init_obs_buf()

        # init view space, feature space, action space
        self.view_space = {}
        self.feature_space = {}
        self.action_space = {}
        buf = np.empty((3, ), dtype=np.int32)
        for handle in self.group_handles:
            _LIB.env_get_info(
                self.game, handle, b"view_space",
                buf.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)))
            self.view_space[handle.value] = (buf[0], buf[1], buf[2])
            _LIB.env_get_info(
                self.game, handle, b"feature_space",
                buf.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)))
            self.feature_space[handle.value] = (buf[0], )
            _LIB.env_get_info(
                self.game, handle, b"action_space",
                buf.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)))
            self.action_space[handle.value] = (buf[0], )
Example #58
0
 def setbool(self, strcommand, value):
     """Set command with Bool value parameter.
     """
     command = ct.c_wchar_p(strcommand)
     value = ct.c_bool(value)
     self.lib.AT_SetBool(self.AT_H, command, value)
Example #59
0
 def disableEarlyStop(self):
     """Disable early-stopping"""
     key = 'early_stop'
     _check_call(
         _LIB.XLearnSetBool(ctypes.byref(self.handle), c_str(key),
                            ctypes.c_bool(False)))
Example #60
0
 def cbool(cls, value: bool = False) -> 'CRef':
     """Alternative constructor. Creates a reference to boolean."""
     return cls(ctypes.c_bool(value))