示例#1
0
    def __init__(self, mol_name):
        """
        :param mol_name: (file) name of molecules
        :type mol_name: string
        :raises: SetupError
        """

        self.mol_name = mol_name
        self.mol_file = ''
        self.mol_fmt = ''

        self.sander_rst = ''
        self.sander_crd = ''
        self.ssbond_file = ''
        self.namd_prefix = ''

        self.min_no = 0  # number of current minimisation step
        self.md_no = 0  # number of current MD step

        self.charge = 0.0
        self.box_dims = []
        self.volume = 0.0
        self.density = 0.0

        self.amber_top = ''  # only set in _amber_top_common
        self.amber_crd = ''  # only set in _amber_top_common
        self.amber_pdb = ''

        self._parm_overwrite = None
        self.mdengine = None

        self.leap = Leap(self.force_fields, self.solvent_load)
示例#2
0
    def __init__(self, model, optimizer_cls, meta_optimizer_cls,
                 optimizer_kwargs, meta_optimizer_kwargs, meta_kwargs,
                 criterion):
        super(LeapWrapper, self).__init__(criterion, model, optimizer_cls,
                                          optimizer_kwargs)
        self.meta = Leap(model, **meta_kwargs)

        self.meta_optimizer_cls = \
            optim.SGD if meta_optimizer_cls.lower() == 'sgd' else optim.Adam
        self.meta_optimizer = self.meta_optimizer_cls(self.meta.parameters(),
                                                      **meta_optimizer_kwargs)
示例#3
0
def main(short_moves):

    print "----------------------------------ShortMotion----------------------------------"

    print "Get an actor for lauching commands."
    actor = Actor(short_moves)

    print "Get a hands listener and bind it with the actor."
    listener = Hands_Listener(
        actor)  #Get listener which herits from Leap.Listener

    print "Get a Leap controller."
    controller = Leap.Controller()  #Get a Leap controller

    print "Binding the Listener to the controller."
    controller.add_listener(listener)  #Attach the listener

    print "----------------------------------Short Moves-----------------------------------"
    print ""
    actor.print_short_moves()
    print ""

    #Keep this process running until Enter is pressed
    print "Press Enter to quit..."
    sys.stdin.readline()

    #Remove the sample listener when done
    controller.remove_listener(listener)
示例#4
0
def main(osc_setup, watched_params_in_hand):

    print "----------------------------------Initializing ----------------------------------"
    print


    #print "Get an actor for sending OSC messages."
    actor = Sender(osc_setup)

    #print "Get a hands listener and bind it with the actor."
    listener = Hands_Listener(actor,watched_params_in_hand) #Get listener which herits from Leap.Listener

    #print "Get a Leap controller."
    controller = Leap.Controller()  #Get a Leap controller

    #print "Binding the Listener to the controller."

    controller.add_listener(listener)  #Attach the listener
    

    #Keep this process running until Enter is pressed
    
    
    print "Press Enter to quit..."
    print
    print "---------------------------------- Running ----------------------------------"
    
    sys.stdin.readline()
    
    #Remove the sample listener when done
    controller.remove_listener(listener)
示例#5
0
    def watch_params_in_gesture(self, gesture):
        if len(gesture.hands) > 0:  #FIX hands ?
            gesture_params = {}
            if gesture.type == 1:
                gesture = Leap.SwipeGesture(gesture)

                gesture.direction_name = self.get_direction_name(
                    gesture.direction)

                gesture.current_position_name = self.get_position_name(
                    gesture.hands[0].palm_position)
                gesture.start_position_name = self.get_position_name(
                    gesture.start_position)

                watched_params = GLOBALS['WATCHED_PARAMS_IN_SWIPE']
            if gesture.type == 4:
                gesture = Leap.CircleGesture(gesture)
                if gesture.pointable.direction.angle_to(
                        gesture.normal) <= Leap.PI / 2:
                    gesture.clockwiseness = "clockwise"
                else:
                    gesture.clockwiseness = "counterclockwise"

                gesture.position_name = self.get_position_name(gesture.center)

                watched_params = GLOBALS['WATCHED_PARAMS_IN_CIRCLE']
            if gesture.type == 5:
                gesture.activated = True
                watched_params = GLOBALS['WATCHED_PARAMS_IN_SCREEN_TAP']
            if gesture.type == 6:
                gesture.activated = True
                watched_params = GLOBALS['WATCHED_PARAMS_IN_KEY_TAP']

            for path, api in watched_params.items():
                try:
                    gesture_params[path] = eval('gesture.' + api)
                except:
                    print "%s\t%s not found. Valid api ?" % (path, api)

            if gesture.type == 1:
                self.actor.on_swipe(gesture_params)
            if gesture.type == 4:
                self.actor.on_circle(gesture_params)
            if gesture.type == 5:
                self.actor.on_screen_tap(gesture_params)
            if gesture.type == 6:
                self.actor.on_key_tap(gesture_params)
示例#6
0
 def do_gesture_recognition(self, gesture_hand, mouse_hand):
     if len(gesture_hand.fingers.extended()
            ) == 5:  #Five open fingers on gesture hand (swipe mode)
         self.gesture_debouncer.signal(
             5)  #Tell the debouncer we've seen this gesture
     elif len(
             gesture_hand.fingers.extended()
     ) == 4 and self.gesture_debouncer.state != 7:  #Three open fingers on gesture hand (scroll mode)
         self.gesture_debouncer.signal(4)
     elif len(gesture_hand.fingers.extended()
              ) == 3:  #Three open fingers on gesture hand (scroll mode)
         self.gesture_debouncer.signal(3)
     elif len(
             gesture_hand.fingers.extended()
     ) == 2 and self.gesture_debouncer.state != 6:  #Two open fingers on gesture hand (right click)
         self.gesture_debouncer.signal(2)
     elif len(gesture_hand.fingers.extended()
              ) == 1:  #One open finger on gesture hand (click down)
         self.gesture_debouncer.signal(1)
     elif len(gesture_hand.fingers.extended()
              ) == 0:  #No open fingers (click up/no action)
         self.gesture_debouncer.signal(0)
     #Now that we've told the debouncer what we *think* the current gesture is, we must act
     #On what the debouncer thinks the gesture is^%{DOWN}
     if self.gesture_debouncer.state == 5:  #Swipe mode
         for gesture in frame.gestures():
             if gesture.type is Leap.Gesture.TYPE_SWIPE:
                 swipe = Leap.SwipeGesture(gesture)
                 if swipe.start_position.x < swipe.position.x:
                     SendKeys.SendKeys("^${RIGHT}")
                 else:
                     SendKeys.SendKeys("^${LEFT}")
     elif self.gesture_debouncer.state == 4:  #Right click
         SendKeys.SendKeys("%{TABS}")
         self.gesture_debouncer.signal(
             7)  #Dummy class so it doesn't right click again
     elif self.gesture_debouncer.state == 3:  #Scroll mode
         y_scroll_amount = self.velocity_to_scroll_amount(
             mouse_hand.palm_velocity.y)  #Mouse hand controls scroll amount
         x_scroll_amount = self.velocity_to_scroll_amount(
             mouse_hand.palm_velocity.x)
         self.cursor.scroll(x_scroll_amount, y_scroll_amount)
     elif self.gesture_debouncer.state == 2:  #Right click
         if self.cursor.left_button_pressed:
             self.cursor.click_up(
             )  #You can't left and right click at the same time
         self.cursor.rightClick()  #Right click
         self.gesture_debouncer.signal(
             6)  #Dummy class so it doesn't right click again
     elif self.gesture_debouncer.state == 1:  #Click/drag mode
         if not self.cursor.left_button_pressed:
             self.cursor.click_down()  #Click down (if needed)
         self.do_mouse_stuff(mouse_hand)  #We may want to click and drag
     elif self.gesture_debouncer.state == 0:  #Move cursor mode
         if self.cursor.left_button_pressed:
             self.cursor.click_up()  #Click up (if needed)
         self.do_mouse_stuff(mouse_hand)
示例#7
0
def main():
    if "-h" in sys.argv or "--help" in sys.argv:
        show_help()
        return

    print "----------------------------------PyLeapMouse----------------------------------"
    print "Use --finger (or blank) for pointer finger control, and --palm for palm control."
    print "Use -h or --help for more info.\n"

    #Default
    finger_mode = True
    palm_mode = False
    motion_mode = False
    smooth_aggressiveness = 8
    smooth_falloff = 1.3

    for i in range(0, len(sys.argv)):
        arg = sys.argv[i].lower()
        if "--palm" in arg:
            finger_mode = False
            palm_mode = True
            motion_mode = False
        if "--motion" in arg:
            finger_mode = False
            palm_mode = False
            motion_mode = True
        if "--smooth-falloff" in arg:
            smooth_falloff = float(sys.argv[i + 1])
        if "--smooth-aggressiveness" in arg:
            smooth_aggressiveness = int(sys.argv[i + 1])

    listener = None
    #I'm tired and can't think of a way to organize this segment nicely

    #Create a custom listener object which controls the mouse
    if finger_mode:  #Finger pointer mode
        listener = Finger_Control_Listener(
            Mouse,
            smooth_aggressiveness=smooth_aggressiveness,
            smooth_falloff=smooth_falloff)
        print "Using finger mode..."
    elif palm_mode:  #Palm control mode
        listener = Palm_Control_Listener(Mouse)
        print "Using palm mode..."
    elif motion_mode:  #Motion control mode
        listener = Motion_Control_Listener(Mouse)
        print "Using motion mode..."

    controller = Leap.Controller()  #Get a Leap controller
    print "Adding Listener."
    controller.add_listener(listener)  #Attach the listener

    #Keep this process running until Enter is pressed
    print "Press Enter to quit..."
    sys.stdin.readline()
    #Remove the sample listener when done
    controller.remove_listener(listener)
示例#8
0
def main():
    controller = Leap.Controller()
    time.sleep(2)
    print(controller.is_connected)
    controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
    try:
        #run(controller)
        run()
    except KeyboardInterrupt:
        sys.exit(0)
示例#9
0
    def watch_params_in_gesture(self, gesture):
        if len(gesture.hands) > 0:  #FIX hands ?
            gesture_params = {}
            if gesture.type == 1:
                gesture = Leap.SwipeGesture(gesture)
                d = gesture.direction
                gesture.direction_name = 'not sure'
                if d.x > 0.7: gesture.direction_name = 'right'
                if d.x <= -0.7: gesture.direction_name = 'left'
                if d.y > 0.7: gesture.direction_name = 'top'
                if d.y <= -0.7: gesture.direction_name = 'bottom'
                if d.z > 0.7: gesture.direction_name = 'back'
                if d.z <= -0.7: gesture.direction_name = 'front'

                if circle.pointable.direction.angle_to(
                        circle.normal) <= Leap.PI / 2:
                    gesture.clockwiseness = "clockwise"
                else:
                    gesture.clockwiseness = "counterclockwise"

                watched_params = WATCHED_PARAMS_IN_SWIPE
            if gesture.type == 4:
                gesture = Leap.CircleGesture(gesture)
                watched_params = WATCHED_PARAMS_IN_CIRCLE
            if gesture.type == 5:
                gesture.activated = True
                watched_params = WATCHED_PARAMS_IN_SCREEN_TAP
            if gesture.type == 6:
                gesture.activated = True
                watched_params = WATCHED_PARAMS_IN_KEY_TAP

            for path, api in watched_params.items():
                try:
                    gesture_params[path] = eval('gesture.' + api)
                except:
                    print "%s\t%s not found. Valid api ?" % (path, api)
            self.sender.send_gesture(gesture_params)
示例#10
0
class LeapWrapper(BaseWrapper):
    """Wrapper around the Leap meta-learner.

    Arguments:
        model (nn.Module): classifier.
        optimizer_cls: optimizer class.
        meta_optimizer_cls: meta optimizer class.
        optimizer_kwargs (dict): kwargs to pass to optimizer upon construction.
        meta_optimizer_kwargs (dict): kwargs to pass to meta optimizer upon
            construction.
        meta_kwargs (dict): kwargs to pass to meta-learner upon construction.
        criterion (func): loss criterion to use.
    """
    def __init__(self, model, optimizer_cls, meta_optimizer_cls,
                 optimizer_kwargs, meta_optimizer_kwargs, meta_kwargs,
                 criterion):
        super(LeapWrapper, self).__init__(criterion, model, optimizer_cls,
                                          optimizer_kwargs)
        self.meta = Leap(model, **meta_kwargs)

        self.meta_optimizer_cls = \
            optim.SGD if meta_optimizer_cls.lower() == 'sgd' else optim.Adam
        self.meta_optimizer = self.meta_optimizer_cls(self.meta.parameters(),
                                                      **meta_optimizer_kwargs)

    def _partial_meta_update(self, l, final):
        self.meta.update(l, self.model)

    def _final_meta_update(self):
        self.meta.normalize()
        self.meta_optimizer.step()
        self.meta_optimizer.zero_grad()

    def run_task(self, task, train, meta_train):
        if meta_train:
            self.meta.init_task()

        if train:
            self.meta.to(self.model)

        return super(LeapWrapper, self).run_task(task, train, meta_train)
示例#11
0
def main():
    controller.enable_gesture(Leap.Gesture.TYPE_SWIPE)
    #Default
    finger_mode = False
    palm_mode = True
    motion_mode = False
    smooth_aggressiveness = 8
    smooth_falloff = 1.3

    listener = Palm_Control_Listener(Mouse)
    controller = Leap.Controller()  #Get a Leap controller
    controller.set_policy_flags(Leap.Controller.POLICY_BACKGROUND_FRAMES)
    controller.add_listener(listener)  #Attach the listener

    #Keep this process running until Enter is pressed
    print "Press Enter to quit..."
    sys.stdin.readline()
    #Remove the sample listener when done
    controller.remove_listener(listener)
示例#12
0
def main(osc_setup):

    print "----------------------------------Initializing ----------------------------------"
    print

    actor = Sender(osc_setup)
    listener = Hands_Listener(
        actor)  #Get listener which herits from Leap.Listener
    controller = Leap.Controller()  #Get a Leap controller

    print "Waiting for the Leap..."
    print

    controller.add_listener(listener)  #Attach the listener

    print "Press Enter to quit..."
    print
    print "---------------------------------- Running ----------------------------------"

    sys.stdin.readline()

    #Remove the sample listener when done
    controller.remove_listener(listener)
示例#13
0
文件: input.py 项目: euxcet/airtyping
def main():

    controller = Leap.Controller()

    # Enable swipe gesture
    controller.enable_gesture(Leap.Gesture.TYPE_SWIPE)
    controller.config.set("Gesture.Swipe.MinLength", 40.0)
    controller.config.set("Gesture.Swipe.MinVelocity", 40)
    controller.config.save()

    listener = Listener()
    controller.add_listener(listener)

    keyboard = Registration().register()
    parser = Parser(keyboard)
    parser.run()
    #Keep this process running until Enter is pressed
    print "Press Enter to quit..."
    try:
        sys.stdin.readline()
    except KeyboardInterrupt:
        pass
    finally:
        controller.remove_listener(listener)
示例#14
0
def leap_adapt(model,
               source_corpus,
               target_corpus,
               char2idx,
               args,
               device,
               lang_model_n_words=0):
    model = model.to(device)
    leap = Leap(model)
    meta_optimizer = torch.optim.Adam(leap.parameters(),
                                      lr=args.leap_meta_lr_init)
    lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
        meta_optimizer,
        factor=args.lr_decay,
        patience=args.patience,
        threshold=args.threshold)
    best_score = 3

    for meta_epoch in np.arange(args.n_meta_epochs):
        source_valid_cosine = []
        target_valid_cosine = []

        model.train()
        for meta_batch in np.arange(args.n_meta_batch):
            meta_optimizer.zero_grad()

            leap.init_task()
            leap.to(model)
            inner_optimizer = torch.optim.Adam(model.parameters(),
                                               lr=args.leap_inner_lr_init)
            for inner_batch in np.arange(args.n_task_steps):
                inner_optimizer.zero_grad()
                source_train_contexts, source_train_targets, source_train_vocabs = source_corpus.get_batch(
                    args.meta_batch_size,
                    args.n_shot,
                    char2idx,
                    device,
                    fixed=args.fixed_shot)
                pred_emb = model.forward(source_train_contexts,
                                         source_train_vocabs)
                loss = -nn.functional.cosine_similarity(
                    pred_emb, source_train_targets).mean()
                loss.backward()
                leap.update(loss, model)
                inner_optimizer.step()

            leap.init_task()
            leap.to(model)
            inner_optimizer = torch.optim.Adam(model.parameters(),
                                               lr=args.leap_inner_lr_init)
            for inner_batch in np.arange(args.n_task_steps):
                inner_optimizer.zero_grad()
                target_train_contexts, target_train_targets, target_train_vocabs = target_corpus.get_batch(
                    args.meta_batch_size,
                    args.n_shot,
                    char2idx,
                    device,
                    fixed=args.fixed_shot,
                    repeat_ctxs=args.meta_repeat_ctxs)
                pred_emb = model.forward(target_train_contexts,
                                         target_train_vocabs)
                loss = -nn.functional.cosine_similarity(
                    pred_emb, target_train_targets).mean()
                loss.backward()
                leap.update(loss, model)
                inner_optimizer.step()

            leap.normalize()
            meta_optimizer.step()

        leap.to(model)
        model.eval()
        with torch.no_grad():
            for batch in np.arange(args.n_batch):
                source_valid_contexts, source_valid_targets, source_valid_vocabs = source_corpus.get_batch(
                    args.meta_batch_size,
                    args.n_shot,
                    char2idx,
                    device,
                    use_valid=True,
                    fixed=args.fixed_shot)
                pred_emb = model.forward(source_valid_contexts,
                                         source_valid_vocabs)
                loss = -nn.functional.cosine_similarity(
                    pred_emb, source_valid_targets).mean()
                source_valid_cosine += [loss.cpu().numpy()]

                target_valid_contexts, target_valid_targets, target_valid_vocabs = target_corpus.get_batch(
                    args.meta_batch_size,
                    args.n_shot,
                    char2idx,
                    device,
                    use_valid=True,
                    fixed=args.fixed_shot,
                    repeat_ctxs=args.meta_repeat_ctxs)
                pred_emb = model.forward(target_valid_contexts,
                                         target_valid_vocabs)
                loss = -nn.functional.cosine_similarity(
                    pred_emb, target_valid_targets).mean()
                target_valid_cosine += [loss.cpu().numpy()]

        avg_source_valid, avg_target_valid = np.average(
            source_valid_cosine), np.average(target_valid_cosine)
        score = avg_target_valid
        lr_scheduler.step(score)
        print(
            f"Average source cosine loss: {avg_source_valid}; Average target cosine loss: {avg_target_valid}"
        )

        if score < best_score:
            best_score = score
            torch.save(model.state_dict(),
                       os.path.join(args.save_dir, 'leap_model.pt'))

        if meta_optimizer.param_groups[0]['lr'] < args.leap_lr_early_stop:
            print('LR early stop')
            break
示例#15
0
class Common(object):
    """
    Common methods for the setup protocol.  Used through subclasses for
    ligand, protein an complex setup.  Methods are expected to be called
    in the right 'order' thus a second layer needs to take control of this.
    """

    PROT_MAP = {
        'HIS': 'HIP',
        'ASP': 'ASH',
        'GLU': 'GLH',
        'LYS': 'LYN',
        'CYS': 'CYM',
        'ARG': 'ARG',
        'TYR': 'TYR'
    }

    TOP_EXT = os.extsep + 'parm7'
    RST_EXT = os.extsep + 'rst7'
    SSBONDS_OFFSET = 0

    def __new__(cls, *args, **kwargs):
        """Prevent direct instantiation."""

        if cls is Common:
            raise TypeError('Common may not be instantiated directly.')

        return object.__new__(cls)

    def __init__(self, mol_name):
        """
        :param mol_name: (file) name of molecules
        :type mol_name: string
        :raises: SetupError
        """

        self.mol_name = mol_name
        self.mol_file = ''
        self.mol_fmt = ''

        self.sander_rst = ''
        self.sander_crd = ''
        self.ssbond_file = ''
        self.namd_prefix = ''

        self.min_no = 0  # number of current minimisation step
        self.md_no = 0  # number of current MD step

        self.charge = 0.0
        self.box_dims = []
        self.volume = 0.0
        self.density = 0.0

        self.amber_top = ''  # only set in _amber_top_common
        self.amber_crd = ''  # only set in _amber_top_common
        self.amber_pdb = ''

        self._parm_overwrite = None
        self.mdengine = None

        self.leap = Leap(self.force_fields, self.solvent_load)

        # set in __init__.py before this __init__(): do not set here or anywhere
        # else as they are meant to be constants for the whole class hierarchy!
        #self.ff_cmd, self.ff_addon, self.solvent, self.solvent_load
        #self.solvent_box, self.MDEngine, self.parmchk_version, self.gaff

    # FIXME: remove
    @staticmethod
    def copy_files(srcs, filenames=None, overwrite=False):
        """
        Copy files from basedir to the current directory.

        :param src: the source directories to copy from
        :type src: list of str
        :param filenames: the filenames to be copied
        :type filenames: list of str
        :param overwrite: overwrite the files in the current dir?
        :type overwrite: bool
        """

        try:
            for src in srcs:
                logger.write('%sopying directory contents of %s to %s' %
                             ('Overwrite mode: c' if overwrite else 'C', src,
                              os.getcwd()))

                if not filenames:
                    filenames = os.listdir(src)

                for filename in filenames:
                    if overwrite or not os.access(filename, os.F_OK):
                        src_file = os.path.join(src, filename)

                        # FIXME: only here to accommodate Complex
                        if os.access(src_file, os.F_OK):
                            shutil.copy(src_file, '.')

        except OSError as why:
            raise errors.SetupError(why)

    def _amber_top_common(self,
                          boxtype='',
                          boxlength='10.0',
                          neutralize=0,
                          align=None,
                          remove_first=False,
                          conc=0.0,
                          dens=1.0):
        """Common scripting commands for leap.  Internal function only.

        :param boxtype: rectangular, octahedron or set
        :type boxtype: string
        :param boxlength: box length in Angstrom
        :type boxlength: float
        :param neutralize: 1=minimum number of ions, 2=use conc
        :type neutralize: int
        :param align: align axes?
        :type align: bool
        :param remove_first: remove first molecule?
        :type remove_first: bool
        :param conc: ion concentration in mol/litres
        :type conc: float
        :param dens: expected target density
        :type dens: float
        :raises: SetupError
        """

        leapin = self.leap.generate_init()

        if os.access(const.SSBOND_FILE, os.R_OK):
            pairs = ssbonds(const.SSBOND_FILE, self.__class__.SSBONDS_OFFSET)
            cmd = []

            for a, b in pairs:
                cmd.append('bond s.%i.SG s.%i.SG\n' % (a, b))

            leapin += ''.join(cmd)

            self.ssbond_file = const.SSBOND_FILE

        boxdata = None

        if align:
            leapin += 'alignAxes s\n'

        # bug #976: input may contain ions and water
        #leapin += self.solvent_load

        if boxtype:
            self.amber_top = const.LEAP_SOLVATED + self.TOP_EXT
            self.amber_crd = const.LEAP_SOLVATED + self.RST_EXT
            self.amber_pdb = const.LEAP_SOLVATED + const.PDB_EXT

            if boxtype == 'octahedron':
                leapin += ('solvateOct s %s %s 0.75\n' %
                           (self.solvent_box, boxlength))
            elif boxtype == 'rectangular':
                leapin += ('solvateBox s %s %s 0.75\n' %
                           (self.solvent_box, boxlength))
            elif boxtype == 'set':  # assumes coords already centered
                leapin += (
                    'set default nocenter on\nsetBox s centers {%s}\n' %
                    ' '.join([str(float(b) / 2.0) for b in self.box_dims[:3]]))
            elif boxtype == 'setvdw':
                leapin += 'setBox s vdw\n'
            else:
                raise errors.SetupError('Unknown box type: %s' % boxtype)
        else:
            self.amber_top = const.LEAP_VACUUM + self.TOP_EXT
            self.amber_crd = const.LEAP_VACUUM + self.RST_EXT
            self.amber_pdb = const.LEAP_VACUUM + const.PDB_EXT

        if self._parm_overwrite:  # how cute...
            self.amber_top = self._parm_overwrite + self.TOP_EXT
            self.amber_crd = self._parm_overwrite + self.RST_EXT
            self.amber_pdb = self._parm_overwrite + const.PDB_EXT

        if neutralize == 1:  # minimum number of ions
            nions = abs(round(self.charge))

            # add explicit number of ions because leap just truncates the int!
            if self.charge < 0.0:
                leapin += 'addIons s Na+ %i\n' % nions
            elif self.charge > 0.0:
                leapin += 'addIons s Cl- %i\n' % nions
        elif neutralize == 2:  # neutralise to set concentration
            self.get_box_info()

            self.amber_top = const.LEAP_IONIZED + self.TOP_EXT
            self.amber_crd = const.LEAP_IONIZED + self.RST_EXT
            self.amber_pdb = const.LEAP_IONIZED + const.PDB_EXT

            nions = abs(round(self.charge))

            # FIXME: check if this is correct
            volume = self.volume * self.density / dens

            # 1 mol/l = 6.022140857*10^23 particles/litre (NIST)
            # 1 A^3   = 10^-27 l
            npart = round(0.0006022141 * conc * volume)

            if self.charge < 0.0:
                npos = npart + nions
                nneg = npart
            elif self.charge > 0.0:
                npos = npart
                nneg = npart + nions
            else:
                npos = nneg = npart

            logger.write('box info: V = %f A^3, rho = %f g/cc\n'
                         'charge = %f; computed #pos = %i, #neg = %i\n' %
                         (self.volume, self.density, self.charge, npos, nneg))

            leapin += 'addIonsRand s Na+ %i Cl- %i 2.0\n' % (npos, nneg)

        leapin += ('saveAmberParm s "%s" "%s"\nsavepdb s "%s"\n' %
                   (self.amber_top, self.amber_crd, self.amber_pdb))

        if remove_first:
            # NOTE: this only removes the first unit!
            leapin += ('remove s s.1\nsaveAmberParm s "%s" "%s"\n'
                       'savepdb s "%s"\n' %
                       (const.NOT_FIRST_TOP, const.NOT_FIRST_CRD,
                        const.NOT_FIRST_PDB))

        leapin += 'quit\n'

        self.sander_crd = self.amber_crd

        return leapin

    def setup_MDEngine(self, mdprog='sander', mdpref='', mdpost=''):
        """
        Instantiate MD engine.
        """

        self.get_box_dims(self.sander_crd)

        self.mdengine = self.MDEngine(self.amber_top, self.amber_crd,
                                      self.sander_crd, self.sander_rst,
                                      self.amber_pdb, self.box_dims,
                                      self.solvent, mdprog, mdpref, mdpost)

    @report
    def minimize(self,
                 namelist='%ALL',
                 nsteps=100,
                 ncyc=10,
                 restraint='',
                 restr_force=10.0):
        """
        Use the AMBER/sander module to minimize a system.

        :param config: MD paramers, if start with '%' respective default is
           chosen, otherwise a full sander namelist as string
        :type config: string
        :param nsteps: maximum number of conjugated gradient steps
        :type nsteps: integer
        :param ncyc: number of initial steepest decent steps
        :type ncyc: float
        :param restraint: pre-defined restraints
        :type restraint: string
        :param restr_force: force constant for the restraints in kcal/mol/AA
        :type restr_force: float
        :raises: SetupError
        """

        if not self.amber_top or not self.amber_crd:
            raise errors.SetupError('Topology and/or coordinates missing.  '
                                    'Please run amber_create_top first.')

        self.mdengine.minimize(namelist, nsteps, ncyc, restraint, restr_force)
        self.amber_crd = self.mdengine.sander_crd  # FIXME: only for AMBER

    @report
    def md(self,
           namelist='',
           nsteps=1000,
           T=300.0,
           p=1.0,
           restraint='',
           restr_force=10.0,
           nrestr=1,
           wrap=True):
        """
        Use the sander module from AMBER to run molecular dynamics on a system.

        :param namelist: MD paramers, if start with '%' respective default is
           chosen, otherwise a full sander namelist as string
        :type namelist: string
        :param nsteps: maximum number of MD steps
        :type nsteps: integer
        :param T: temperature
        :type T: float
        :param p: pressure
        :type p: float
        :param restraint: pre-defined restraints
            backbone, heavy, protein, notligand, notsolvent or empty string
            for no restraints.  Any other string is passed on as a mask.  Must
            be set to any true value if namelist is not a preset template and
            restraints are to be used in the custom namelist.
        :type restraint: string
        :param restr_force: force constant for the restraints in kcal/mol/AA
        :type restr_force: float
        :param nrel: number of restraint relaxation steps
        :type nrel: integer
        :param wrap: wrap coordinates in a periodic system
        :type wrap: bool
        :raises: SetupError
        """

        if not namelist:
            raise errors.SetupError('No namelist supplied.')

        # FIXME: clean up nrestr to be consistent between MD programs
        self.mdengine.md(namelist, nsteps, T, p, restraint, restr_force,
                         nrestr, wrap)

        # FIXME: do we also want to density?
        self.box_dims = self.mdengine.get_box_dims()
        self.amber_crd = self.mdengine.sander_crd  # FIXME: only for AMBER

    def to_rst7(self):
        """
        Ask MD engine to convert coordinates to rst7 format.

        FIXME: must be called explicitly!
        """

        self.mdengine.to_rst7()
        self.amber_crd = self.mdengine.sander_crd

    @report
    def flatten_rings(self):
        """
        Make aromatic rings planar.  Useful for MC like Sire.

        :raises: Sire error
        """

        import Sire.IO
        import Sire.Mol

        import warnings

        # FIXME: suppress a warning over a fmcs/Sire double data type
        #        registration collision
        with warnings.catch_warnings():
            warnings.filterwarnings(
                'ignore', 'to-Python converter '
                'for.*already registered')
            import Sire.Move

        import Sire.Units
        import Sire.Config  # NOTE: make sure paths are set
        #       correctly in __init__.py!

        logger.write('flattening rings of residues %s' %
                     ', '.join(const.AROMATICS))

        amber = Sire.IO.Amber()
        molecules = amber.readCrdTop(self.amber_crd, self.amber_top)[0]

        zmat_maker = Sire.IO.ZmatrixMaker()
        protein_zmatrices = os.path.join(Sire.Config.parameter_directory,
                                         'amber.zmatrices')
        zmat_maker.loadTemplates(protein_zmatrices)

        newmols = Sire.Mol.Molecules()

        molnums = molecules.molNums()

        for idx in range(0, len(molnums)):
            molnum = molnums[idx]
            curr_mol = molecules.at(molnum).molecule()

            try:
                curr_mol = zmat_maker.applyTemplates(curr_mol)
            except UserWarning as error:
                error_type = re.search(const.RE_SIRE_ERROR_STR,
                                       str(error)).group(1)

                if (error_type == 'SireError::invalid_key'
                        or error_type == 'SireBase::missing_property'):
                    newmols.add(curr_mol)
                    continue
                else:
                    raise error

            zmatrix = curr_mol.property('z-matrix')
            zmatrixcoords = Sire.Move.ZMatrixCoords(zmatrix, curr_mol)
            zmatlines = zmatrixcoords.lines()

            for zline in zmatlines:
                at0 = curr_mol.select(zline.atom())
                at1 = curr_mol.select(zline.bond())
                at2 = curr_mol.select(zline.angle())
                at3 = curr_mol.select(zline.dihedral())

                if (str(at0.residue().name().value()) in const.AROMATICS and
                        str(at1.residue().name().value()) in const.AROMATICS
                        and str(at2.residue().name().value())
                        in const.AROMATICS and str(
                            at3.residue().name().value()) in const.AROMATICS):

                    dihname = '%s-%s-%s-%s' % (at0.name().value(), at1.name(
                    ).value(), at2.name().value(), at3.name().value())

                    if dihname in const.TORSIONS_TO_ZERO:
                        zmatrixcoords.setDihedral(zline.atom(),
                                                  0.0 * Sire.Units.degrees)
                    elif dihname in const.TORSIONS_TO_ONEHUNDREDEIGHTY:
                        zmatrixcoords.setDihedral(zline.atom(),
                                                  180.0 * Sire.Units.degrees)

            ncoor = zmatrixcoords.toCartesian()
            molec = curr_mol.edit().setProperty('coordinates', ncoor).commit()
            newmols.add(molec)

        Sire.IO.PDB().write(newmols, const.FLAT_RINGS_FILE)

        self.amber_pdb = const.FLAT_RINGS_FILE
        self.mol_file = self.amber_pdb
        self.mol_fmt = 'pdb'

    # called in morph.py (1x), common.py/setup_MDEngine (1x)
    def get_box_dims(self, filename=None):
        """
        Get box dimensions from sander .rst file.

        :param filename: name of .rst file
        :type filename: string
        """

        if not filename:
            filename = self.sander_rst

        with open(filename, 'r') as rst:
            for line in rst:
                self.box_dims = line

        self.box_dims = self.box_dims.split()

    # called in common.py/_amber_top_common (1x)
    def get_box_info(self):
        """
        Use Sire to get information about the system: volume, density,
        box dimensions.

        NOTE: Sire prmtop reader is slow!
        """

        # Sire.Mol.Molecules, Sire.Vol.PeriodicBox or Sire.Vol.Cartesian
        molecules, space = \
                   Sire.IO.Amber().readCrdTop(self.amber_crd, self.amber_top)

        if space.isPeriodic():
            self.volume = space.volume().value()  # in A^3

            # NOTE: currently rectangular box only
            x = space.dimensions().x()
            y = space.dimensions().y()
            z = space.dimensions().z()
            self.box_dims = (x, y, z)  # in Angstrom

            total_mass = 0.0  # in amu

            for num in molecules.molNums():
                mol = molecules.at(num).molecule()

                for atom in mol.atoms():
                    total_mass += atom.property('mass').value()

            # in g/cc
            self.density = total_mass * const.AMU2GRAMS / self.volume
示例#16
0
 def __init__(self, actor):
     super(Listener, self).__init__()
     self.actor = actor
     self.center = Leap.Vector(GLOBALS['CENTER_X'], GLOBALS['CENTER_Y'],
                               GLOBALS['CENTER_Z'])
示例#17
0
 def to_leap(self):
     return Leap.Vector(self.x, self.y, self.z)
示例#18
0
net.collect_params()
type(net.collect_params())

net.collect_params().initialize(mx.init.Normal(sigma=1.), ctx=model_ctx)

square_loss = gluon.loss.L2Loss()

epochs = 3
loss_sequence = []
num_batches = num_examples / batch_size

verbose = 1

##########
meta_steps = 10
leap = Leap(net)
meta_trainer = gluon.Trainer(list(leap.parameters()), 'sgd',
                             {'learning_rate': 0.0001})
meta_logger = MetaLogger(num_tasks)
log_params = True
##########

for ms in range(meta_steps):
    for task in range(num_tasks):
        train_data = train_data_all[task]

        leap.to(net)
        leap.init_task()

        trainer = gluon.Trainer(net.collect_params(), 'sgd',
                                {'learning_rate': 0.0001})
示例#19
0
def run(debug=False):

    controller = Leap.Controller()
    time.sleep(2)
    print(controller.is_connected)
    controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
    counter = -20
    maps_initialized = False
    previous_sum = 0
    current_sum = 0
    baseline = 0

    executor = ThreadPoolExecutor(max_workers=1)
    id_ = ''
    with open('id.txt', 'r+') as f:
        id_ = f.readline()

    id_ = re.search(r'(\d+)', id_).group(0)
    print('the real id is', id_)
    # Set the baseline
    print('Calibrating, please wait...')
    while counter < 0:
        frame = controller.frame()
        image = frame.images[0]
        if image.is_valid:
            if not maps_initialized:
                left_coordinates, left_coefficients = convert_distortion_maps(
                    frame.images[0])
                right_coordinates, right_coefficients = convert_distortion_maps(
                    frame.images[1])

                maps_initialized = True

            undistorted_left = undistort(image, left_coordinates,
                                         left_coefficients, 400, 400)
            undistorted_right = undistort(image, right_coordinates,
                                          right_coefficients, 400, 400)

            newsum = sum([
                image.data[i] for i in range(0, image.width * image.height, 50)
            ])
            #print('Counter:', counter, '| Val:', newsum)
            if counter >= -17:
                baseline += newsum
            # ba = bytearray(image.data)
            # print(sum(ba))
            counter += 1
            # cv2.imshow('Left Camera', undistorted_left)
            # cv2.imshow('Right Camera', undistorted_right)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        #print(counter)

    baseline /= 17
    mult = 1.03
    print('Done!')
    if debug:
        print('Baseline: {:,}, Threashhold: {}'.format(baseline,
                                                       baseline * mult))
    onspike = False
    while (True):
        frame = controller.frame()
        #print(frame.current_frames_per_second)
        image = frame.images[0]
        if image.is_valid:
            if not maps_initialized:
                left_coordinates, left_coefficients = convert_distortion_maps(
                    frame.images[0])
                right_coordinates, right_coefficients = convert_distortion_maps(
                    frame.images[1])

                maps_initialized = True

            undistorted_left = undistort(image, left_coordinates,
                                         left_coefficients, 400, 400)
            undistorted_right = undistort(image, right_coordinates,
                                          right_coefficients, 400, 400)

            #display images

            #buffer_size = image.bytes_per_pixel * image.width * image.height
            #print(sum([image.data[i] for i in range(0,image.width*image.height,20)]))
            #pprint(image.data_pointer)
            if counter % 1 == 0:
                previous_sum = current_sum
                current_sum = sum([
                    image.data[i]
                    for i in range(0, image.width * image.height, 50)
                ])
                # print('{:,}'.format(current_sum), '|', '{:,}'.format(current_sum - previous_sum))
                if debug:
                    print(abs(current_sum))  #-previous_sum))
                if (abs(current_sum) >
                        mult * baseline) and previous_sum != 0 and not onspike:
                    print('Trashed!')
                    executor.submit(updater.addone, id_)
                    onspike = True
                elif not abs(current_sum) > mult * baseline:
                    onspike = False
                counter = 0

            # ba = bytearray(image.data)
            # print(sum(ba))
            counter += 1
            if debug:
                cv2.imshow('Left Camera', undistorted_left)
                cv2.imshow('Right Camera', undistorted_right)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
示例#20
0
 def __init__(self):
     self.keep_tracking = False
     self.listener = GestureListener()
     self.controller = Leap.Controller()