Beispiel #1
0
    def sample_motion(self, N, numeric=True, start_margin=0, end_margin=0):
        r"""
        Return a sampling of the motion.

        TODO:

        Doc, examples
        """
        a, b = self._interval
        if numeric:
            if self._sampling_type == 'uniform':
                return [self.realization(RR(a + (i/Integer(N)) * (b-a)),  numeric=True) 
                        for i in range(start_margin, N+1-end_margin)]
            elif self._sampling_type == 'tan':
                return [self.realization(tan(RR(a + (i/Integer(N)) * (b-a))),  numeric=True) 
                        for i in range(start_margin, N+1-end_margin)]
            else:
                raise exceptions.NotImplementedError('Sampling ' + str(self._sampling_type) + ' is not supported.')
        else:
            if self._sampling_type == 'uniform':
                return [self.realization(a + (i/Integer(N)) * (b-a)) 
                        for i in range(start_margin, N+1-end_margin)]
            elif self._sampling_type == 'tan':
                return [self.realization(tan(a + (i/Integer(N)) * (b-a))) 
                        for i in range(start_margin, N+1-end_margin)]
            else:
                raise exceptions.NotImplementedError('Sampling ' + str(self._sampling_type) + ' is not supported.')
    def make_ner_file(self, clean_visible_path, ner_xml_path):
        '''run tagger a child process to get XML output'''
        if self.template is None:
            raise exceptions.NotImplementedError('''
Subclasses must specify a class property "template" that provides
command string format for running a tagger.  It should take
%(tagger_root_path)s as the path from the config file,
%(clean_visible_path)s as the input XML file, and %(ner_xml_path)s as
the output path to create.
''')
        tagger_config = dict(tagger_root_path=self.config['tagger_root_path'],
                             clean_visible_path=clean_visible_path,
                             ner_xml_path=ner_xml_path)
        ## get a java_heap_size or default to 1GB
        tagger_config['java_heap_size'] = self.config.get('java_heap_size', '')
        cmd = self.template % tagger_config
        logger.critical(cmd)
        start_time = time.time()
        ## make sure we are using as little memory as possible
        gc.collect()
        try:
            self._child = subprocess.Popen(cmd,
                                           stderr=subprocess.PIPE,
                                           shell=True)
        except OSError, exc:
            msg = traceback.format_exc(exc)
            msg += make_memory_info_msg(clean_visible_path, ner_xml_path)
            # instead of sys.ext, do proper shutdown
            #sys.exit(int(self.config['exit_code_on_out_of_memory']))
            raise PipelineOutOfMemory(msg)
Beispiel #3
0
 def type_name(self):
     """
     Returns the type name.
     https://heycam.github.io/webidl/#dfn-type-name
     Note that a type name is not necessarily unique.
     """
     raise exceptions.NotImplementedError()
Beispiel #4
0
    def realization(self, value,  numeric=False):
        r"""
        Return the realization for given value of the parameter.

        TODO:

        Doc, examples
        """
        res = {}
        if self._par_type == 'symbolic':
            subs_dict = { self._parameter : value}
            for v in self._graph.vertices():
                if numeric:
                    res[v] = vector([RR(xi.subs(subs_dict)) for xi in self._parametrization[v]])
                else:
                    res[v] = vector([xi.subs(subs_dict) for xi in self._parametrization[v]])
            return res
        elif self._par_type == 'rational':
            h = self._field.hom(value)
            for v in self._graph.vertices():
                if numeric:
                    res[v] = vector([RR(h(xi)) for xi in self._parametrization[v]])
                else:
                    res[v] = vector([h(xi) for xi in self._parametrization[v]])
            return res
        else:
            raise exceptions.NotImplementedError('')
Beispiel #5
0
    def print_(self, raw=False, defaults_display='include'):
        """
        Print.

        Arguments:
        - raw -- see print_conf
        - defaults_display -- whether to display defaults and how to display
                              them. Permitted values:
          - include -- display defaults like any other values inline in
                       appropriate section
          - exclude -- do not show values same as their default
          - show, extra -- display default values separately

        """
        print "\n=== %s ===" % self.id
        if defaults_display:
            defaults_display = defaults_display.lower()
        if not defaults_display or defaults_display == 'include':
            defs = {}
            show_defaults = False
        elif defaults_display == 'exclude':
            defs = self.defaults
            show_defaults = False
        elif defaults_display in ('show', 'extra'):
            defs = self.defaults
            show_defaults = True
        else:
            raise exceptions.NotImplementedError(
                'print_ does not know how to handle %s' % (defaults_display, ))
        self.print_conf(self.conf,
                        raw=raw,
                        defaults=defs,
                        show_defaults=show_defaults)
 def does_inherit_getter(self):
     """
     Returns True if |self| inherits its getter.
     https://heycam.github.io/webidl/#dfn-inherit-getter
     @return bool
     """
     raise exceptions.NotImplementedError()
Beispiel #7
0
 def type_name(self):
     """
     Returns type name of this type.
     https://heycam.github.io/webidl/#dfn-type-name
     @return str
     """
     raise exceptions.NotImplementedError()
 def own_members(self):
     """
     Returns dictionary members which do not include inherited
     Dictionaries' members.
     @return tuple(DictionaryMember)
     """
     raise exceptions.NotImplementedError()
Beispiel #9
0
    def get_fields(self):
        """
        Get serializable fields
        Must be defined in any subclass
        """

        raise exceptions.NotImplementedError()
Beispiel #10
0
 def operation_groups(self):
     """
     Returns a list of OperationGroup. Each OperationGroup may have an
     operation or a set of overloaded operations.
     @return tuple(OperationGroup)
     """
     raise exceptions.NotImplementedError()
 def is_custom(self):
     """
     Returns True if this Constructor is defined in the form of
     [CustomConstructor=(...)]
     @return bool
     """
     raise exceptions.NotImplementedError()
Beispiel #12
0
 def named_constructor(self):
     """
     Returns a named constructor, if this interface has it. Otherwise, returns
     None.
     @return NamedConstructor?
     """
     raise exceptions.NotImplementedError()
Beispiel #13
0
 def exposed_interfaces(self):
     """
     Returns a tuple of Interfaces that are exposed to |self|. If |self| is
     not a global interface, returns an empty tuple.
     @return tuple(Interface)
     """
     raise exceptions.NotImplementedError()
Beispiel #14
0
 def operation_groups(self):
     """
     Returns a tuple of OperationGroup. Each OperationGroup has operation(s)
     defined in this interface and [Unforgeable] operations in ancestors.
     @return tuple(OperationGroup)
     """
     raise exceptions.NotImplementedError()
Beispiel #15
0
 def attributes(self):
     """
     Returns a tuple of attributes including [Unforgeable] attributes in
     ancestors.
     @return tuple(Attribute)
     """
     raise exceptions.NotImplementedError()
Beispiel #16
0
 def inherited_interface(self):
     """
     Returns an Interface from which this interface inherits. If this
     interface does not inherit, returns None.
     @return Interface?
     """
     raise exceptions.NotImplementedError()
Beispiel #17
0
 def exposures(self):
     """
     Returns a set of Exposure's that are applicable on an object.
     https://heycam.github.io/webidl/#Exposed
     @return tuple(Expsure)
     """
     raise exceptions.NotImplementedError()
Beispiel #18
0
    def __init__(self,
                 model,
                 num_samples,
                 num_chains=3,
                 betas=None):
        """ Initializes the sampler with the model.

        :param model: The model to sample from.
        :type model: Valid model Class.

        :param num_samples: The number of samples to generate.
                            .. Note:: Optimal performance (ATLAS,MKL) is achieved if the number of samples equals the \
                            batchsize.
        :type num_samples:

        :param num_chains: The number of Markov chains.
        :type num_chains: int

        :param betas: Array of inverse temperatures to sample from, its dimensionality needs to equal the number of \
                      chains or if None is given the inverse temperatures are initialized linearly from 0.0 to 1.0 \
                      in 'num_chains' steps.
        :type betas: int, None
        """
        if not model._fast_PT:
            raise ex.NotImplementedError("Only more efficient for Binary RBMs")

        # Check and set the model                
        if not hasattr(model, 'probability_h_given_v'):
            raise ex.ValueError("The model needs to implement the function probability_h_given_v!")
        if not hasattr(model, 'probability_v_given_h'):
            raise ex.ValueError("The model needs to implement the function probability_v_given_h!")
        if not hasattr(model, 'sample_h'):
            raise ex.ValueError("The model needs to implement the function sample_h!")
        if not hasattr(model, 'sample_v'):
            raise ex.ValueError("The model needs to implement the function sample_v!")
        if not hasattr(model, 'energy'):
            raise ex.ValueError("The model needs to implement the function energy!")
        if not hasattr(model, 'input_dim'):
            raise ex.ValueError("The model needs to implement the parameter input_dim!")
        self.model = model

        # Initialize persistent Markov chains to Gaussian random samples.
        self.num_samples = num_samples
        self.chains = model.sample_v(numx.random.randn(num_chains * self.num_samples, model.input_dim) * 0.01)

        # Sets the beta values
        self.num_betas = num_chains
        if betas is None:
            self.betas = numx.linspace(0.0, 1.0, num_chains).reshape(num_chains, 1)
        else:
            self.betas = self.betas.reshape(numx.array(betas).shape[0], 1)
            if self.betas.shape[0] != num_chains:
                raise ex.ValueError("The number of betas and Markov chains must be equivalent!")

        # Repeat betas batchsize times
        self.betas = numx.tile(self.betas.T, self.num_samples).T.reshape(num_chains * self.num_samples, 1)

        # Indices of the chains on temperature beta = 1.0
        self.select_indices = numx.arange(self.num_betas - 1, self.num_samples * self.num_betas, self.num_betas)
Beispiel #19
0
    def create_imgs(self, dir_path, sub_dir):
        #
        #  FULL_DOC
        #
        if 1:
            raise exceptions.NotImplementedError('check this code!')
        if URL_STRUCTURE == 1:
            dest_full = os.path.join(settings.MEDIA_ROOT,
                                     settings.DIR_FULL_DOC, sub_dir)
        else:
            dest_full = os.path.join(settings.MEDIA_ROOT,
                                     settings.DIR_FULL_DOC, sub_dir)

        cmd = ['%s -path %s' % (IMG_CMD, dest_full)]
        cmd.append('-format jpg')
        cmd.append('-define jpeg:size=260x200')
        cmd.append('-thumbnail 200x %s/*.original' % dir_path)
        p = subprocess.Popen(' '.join(cmd),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=True)
        retcode = p.wait()
        if retcode:
            err_msg = p.stderr.read()
            print '*** Error'
            self.error_count += 1
            print err_msg
            if 0:  #not parse_error(err_msg): Skip analyse for the moment...
                sys.exit(1)

        #
        # BRIEF_DOC
        #
        """
        mogrify -path BRIEF_DOC/subdir1/subdir2
            -format jpg
            -thumbnail x110 FULL_DOC/subdir1/subdir2/*.jpg

        """
        dest_brief = os.path.join(settings.MEDIA_ROOT, settings.DIR_BRIEF_DOC,
                                  sub_dir)
        cmd = ['%s -path %s' % (IMG_CMD, dest_brief)]
        cmd.append('-format jpg')
        cmd.append('-thumbnail x110 %s/*.jpg' % dest_full)
        p = subprocess.Popen(' '.join(cmd),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=True)
        retcode = p.wait()
        if retcode:
            err_msg = p.stderr.read()
            print '*** Error'
            self.error_count += 1
            print err_msg
            if 0:  #not parse_error(err_msg): Skip analyse for the moment...
                sys.exit(1)
        return
Beispiel #20
0
 def named_property_handler(self):
     """
     Returns a set of handlers (getter/setter/deleter) for the named
     property.
     @return NamedPropertyHandler?
     """
     # TODO: Include anonymous handlers of ancestors. https://crbug.com/695972
     raise exceptions.NotImplementedError()
Beispiel #21
0
    def is_correct(self, question, parameters):
        """
        Whether the answer is correct.
        Pass the question itself and the parameters, if any.
        """

        raise exceptions.NotImplementedError(
            "This question type has no correction method.")
Beispiel #22
0
def notice(title="notice_time_limit", msg="Test"):
    plt = platform.system()
    if plt == "Darwin":
        os.system(
            "osascript -e 'display notification \"{}\" with title \"{}\"'".
            format(msg, title))
    else:
        raise exceptions.NotImplementedError("Not supported OS **yet**")
Beispiel #23
0
    def _keyphraseConsumption(self, corpus, keyphrases):
        """Consumes the keyphrases associcated to the documents of a given corpus.

    Args:
      corpus: The C{KBCorpus} from which the keyphrases have been extracted.
      keyphrases: The extracted keyphrases (C{map} of C{list} of
        C{KBTextualUnit}s associated to a document's name).
    """

        raise exceptions.NotImplementedError()
Beispiel #24
0
 def get_newsletter_receiver_collections(self):
     """
     Returns a dict of valid receiver collections
     has to be overriden in the object to return a tuple of querysets
     return (('all',{}),)
     {} is used to filter the queryset when evaluating the
     get_receiver_filtered_queryset function.
     """
     raise exceptions.NotImplementedError(
         "Override this method in your class!")
Beispiel #25
0
def get_date_for_device(device, filename):
    '''
    Retrieves date from file using device dependent algorithm.
    :param device: name of device that shot the video.
    :param filename: name of the file.
    :return: datetime.date object.
    '''
    if device == 'nexus5':
        return parse_date_nexus5(filename)
    else:
        raise exceptions.NotImplementedError('Unknown device: ' + device)
Beispiel #26
0
    def _candidateClustering(self, document):
        """Clusters the candidates of a given document.

    Args:
      document: The C{KBDocument} from which the candidates must be clustered.

    Returns:
      The C{list} of C{KBTextualUnitCluster}s).
    """

        raise exceptions.NotImplementedError()
Beispiel #27
0
 def _bell(self):
     '''ring the bell if requested.'''
     if self.bell_style == 'none':
         pass
     elif self.bell_style == 'visible':
         raise exceptions.NotImplementedError(
             "Bellstyle visible is not implemented yet.")
     elif self.bell_style == 'audible':
         self.console.bell()
     else:
         raise ReadlineError("Bellstyle %s unknown." % self.bell_style)
Beispiel #28
0
    def loadFromR(self, filename):
        """
        Loads object from R data file.

        Parameters:
            filename: string
                string that gives the filename and the location of the file

        """
        raise exceptions.NotImplementedError(
            "not implemented to load from Rdata file")
Beispiel #29
0
    def url(self, _external=False):
        """
        The URL where a JSON representation of the document based on MongoCoderMixin_'s encode_mongo_ method can be found.

        .. warning::

            Subclasses of MongoCoderDocument should implement this method.
        """

        raise exceptions.NotImplementedError(
            "The single-object URL of this document class is not defined.")
Beispiel #30
0
    def tokenizeSentences(self, text):
        """Tokenizes a text into sentences.

    Args:
      text: The C{string} text to tokenize.

    Returns:
      The ordered C{list} of every C{string} sentence of the C{text}.
    """

        raise exceptions.NotImplementedError()