Example #1
0
        public BinarizerAnnotator(string annotatorName, Properties props)
        {
            this.tlppClass = props.GetProperty(annotatorName + ".tlppClass", DefaultTlppClass);
            ITreebankLangParserParams tlpp = ReflectionLoading.LoadByReflection(tlppClass);

            this.binarizer = TreeBinarizer.SimpleTreeBinarizer(tlpp.HeadFinder(), tlpp.TreebankLanguagePack());
        }
Example #2
0
 public PerceptronModel(ShiftReduceOptions op, IIndex <ITransition> transitionIndex, ICollection <string> knownStates, ICollection <string> rootStates, ICollection <string> rootOnlyStates)
     : base(op, transitionIndex, knownStates, rootStates, rootOnlyStates)
 {
     // Serializable
     this.featureWeights = Generics.NewHashMap();
     string[] classes = op.featureFactoryClass.Split(";");
     if (classes.Length == 1)
     {
         this.featureFactory = ReflectionLoading.LoadByReflection(classes[0]);
     }
     else
     {
         FeatureFactory[] factories = new FeatureFactory[classes.Length];
         for (int i = 0; i < classes.Length; ++i)
         {
             int paren = classes[i].IndexOf('(');
             if (paren >= 0)
             {
                 string arg = Sharpen.Runtime.Substring(classes[i], paren + 1, classes[i].Length - 1);
                 factories[i] = ReflectionLoading.LoadByReflection(Sharpen.Runtime.Substring(classes[i], 0, paren), arg);
             }
             else
             {
                 factories[i] = ReflectionLoading.LoadByReflection(classes[i]);
             }
         }
         this.featureFactory = new CombinationFeatureFactory(factories);
     }
 }
Example #3
0
        /// <summary>Solves the problem using OWLQN.</summary>
        /// <remarks>
        /// Solves the problem using OWLQN.  The solution
        /// is stored in the
        /// <c>lambda</c>
        /// array of
        /// <c>prob</c>
        /// .  Note that the
        /// likelihood function will be a penalized L2 likelihood function unless you
        /// have turned this off via setting the priorSigmaS to 0.0.
        /// </remarks>
        /// <param name="weight">
        /// Controls the sparseness/regularization of the L1 solution.
        /// The bigger the number the sparser the solution.  Weights between
        /// 0.01 and 1.0 typically give good performance.
        /// </param>
        public virtual void SolveL1(double weight)
        {
            CGRunner.LikelihoodFunction df  = new CGRunner.LikelihoodFunction(prob, tol, useGaussianPrior, priorSigmaS, sigmaSquareds);
            IMinimizer <IDiffFunction>  owl = ReflectionLoading.LoadByReflection("edu.stanford.nlp.optimization.OWLQNMinimizer", weight);

            prob.lambda = owl.Minimize(df, tol, new double[df.DomainDimension()]);
            PrintOptimizationResults(df, null);
        }
Example #4
0
        public ParserAnnotator(string annotatorName, Properties props)
        {
            string model = props.GetProperty(annotatorName + ".model", LexicalizedParser.DefaultParserLoc);

            if (model == null)
            {
                throw new ArgumentException("No model specified for Parser annotator " + annotatorName);
            }
            this.Verbose = PropertiesUtils.GetBool(props, annotatorName + ".debug", false);
            string[] flags = ConvertFlagsToArray(props.GetProperty(annotatorName + ".flags"));
            this.parser            = LoadModel(model, Verbose, flags);
            this.maxSentenceLength = PropertiesUtils.GetInt(props, annotatorName + ".maxlen", -1);
            string treeMapClass = props.GetProperty(annotatorName + ".treemap");

            if (treeMapClass == null)
            {
                this.treeMap = null;
            }
            else
            {
                this.treeMap = ReflectionLoading.LoadByReflection(treeMapClass, props);
            }
            this.maxParseTime = PropertiesUtils.GetLong(props, annotatorName + ".maxtime", -1);
            this.kBest        = PropertiesUtils.GetInt(props, annotatorName + ".kbest", 1);
            this.keepPunct    = PropertiesUtils.GetBool(props, annotatorName + ".keepPunct", true);
            string buildGraphsProperty = annotatorName + ".buildgraphs";

            if (!this.parser.GetTLPParams().SupportsBasicDependencies())
            {
                if (PropertiesUtils.GetBool(props, buildGraphsProperty))
                {
                    log.Info("WARNING: " + buildGraphsProperty + " set to true, but " + this.parser.GetTLPParams().GetType() + " does not support dependencies");
                }
                this.BuildGraphs = false;
            }
            else
            {
                this.BuildGraphs = PropertiesUtils.GetBool(props, buildGraphsProperty, true);
            }
            if (this.BuildGraphs)
            {
                bool generateOriginalDependencies = PropertiesUtils.GetBool(props, annotatorName + ".originalDependencies", false);
                parser.GetTLPParams().SetGenerateOriginalDependencies(generateOriginalDependencies);
                ITreebankLanguagePack tlp         = parser.GetTLPParams().TreebankLanguagePack();
                IPredicate <string>   punctFilter = this.keepPunct ? Filters.AcceptFilter() : tlp.PunctuationWordRejectFilter();
                this.gsf = tlp.GrammaticalStructureFactory(punctFilter, parser.GetTLPParams().TypedDependencyHeadFinder());
            }
            else
            {
                this.gsf = null;
            }
            this.nThreads = PropertiesUtils.GetInt(props, annotatorName + ".nthreads", PropertiesUtils.GetInt(props, "nthreads", 1));
            bool usesBinary = StanfordCoreNLP.UsesBinaryTrees(props);

            this.saveBinaryTrees   = PropertiesUtils.GetBool(props, annotatorName + ".binaryTrees", usesBinary);
            this.noSquash          = PropertiesUtils.GetBool(props, annotatorName + ".nosquash", false);
            this.extraDependencies = MetaClass.Cast(props.GetProperty(annotatorName + ".extradependencies", "NONE"), typeof(GrammaticalStructure.Extras));
        }
Example #5
0
        public virtual LogisticClassifier <L, F> TrainClassifier(GeneralDataset <L, F> data, double l1reg, double tol, LogPrior prior, bool biased)
        {
            if (data is RVFDataset)
            {
                ((RVFDataset <L, F>)data).EnsureRealValues();
            }
            if (data.labelIndex.Size() != 2)
            {
                throw new Exception("LogisticClassifier is only for binary classification!");
            }
            IMinimizer <IDiffFunction> minim;

            if (!biased)
            {
                LogisticObjectiveFunction lof = null;
                if (data is Dataset <object, object> )
                {
                    lof = new LogisticObjectiveFunction(data.NumFeatureTypes(), data.GetDataArray(), data.GetLabelsArray(), prior);
                }
                else
                {
                    if (data is RVFDataset <object, object> )
                    {
                        lof = new LogisticObjectiveFunction(data.NumFeatureTypes(), data.GetDataArray(), data.GetValuesArray(), data.GetLabelsArray(), prior);
                    }
                }
                if (l1reg > 0.0)
                {
                    minim = ReflectionLoading.LoadByReflection("edu.stanford.nlp.optimization.OWLQNMinimizer", l1reg);
                }
                else
                {
                    minim = new QNMinimizer(lof);
                }
                weights = minim.Minimize(lof, tol, new double[data.NumFeatureTypes()]);
            }
            else
            {
                BiasedLogisticObjectiveFunction lof = new BiasedLogisticObjectiveFunction(data.NumFeatureTypes(), data.GetDataArray(), data.GetLabelsArray(), prior);
                if (l1reg > 0.0)
                {
                    minim = ReflectionLoading.LoadByReflection("edu.stanford.nlp.optimization.OWLQNMinimizer", l1reg);
                }
                else
                {
                    minim = new QNMinimizer(lof);
                }
                weights = minim.Minimize(lof, tol, new double[data.NumFeatureTypes()]);
            }
            featureIndex = data.featureIndex;
            classes[0]   = data.labelIndex.Get(0);
            classes[1]   = data.labelIndex.Get(1);
            return(new LogisticClassifier <L, F>(weights, featureIndex, classes));
        }
Example #6
0
        private void SetProperties(Properties props)
        {
            trainingThreads       = PropertiesUtils.GetInt(props, "trainingThreads", trainingThreads);
            wordCutOff            = PropertiesUtils.GetInt(props, "wordCutOff", wordCutOff);
            initRange             = PropertiesUtils.GetDouble(props, "initRange", initRange);
            maxIter               = PropertiesUtils.GetInt(props, "maxIter", maxIter);
            batchSize             = PropertiesUtils.GetInt(props, "batchSize", batchSize);
            adaEps                = PropertiesUtils.GetDouble(props, "adaEps", adaEps);
            adaAlpha              = PropertiesUtils.GetDouble(props, "adaAlpha", adaAlpha);
            regParameter          = PropertiesUtils.GetDouble(props, "regParameter", regParameter);
            dropProb              = PropertiesUtils.GetDouble(props, "dropProb", dropProb);
            hiddenSize            = PropertiesUtils.GetInt(props, "hiddenSize", hiddenSize);
            embeddingSize         = PropertiesUtils.GetInt(props, "embeddingSize", embeddingSize);
            numPreComputed        = PropertiesUtils.GetInt(props, "numPreComputed", numPreComputed);
            evalPerIter           = PropertiesUtils.GetInt(props, "evalPerIter", evalPerIter);
            clearGradientsPerIter = PropertiesUtils.GetInt(props, "clearGradientsPerIter", clearGradientsPerIter);
            saveIntermediate      = PropertiesUtils.GetBool(props, "saveIntermediate", saveIntermediate);
            unlabeled             = PropertiesUtils.GetBool(props, "unlabeled", unlabeled);
            cPOS   = PropertiesUtils.GetBool(props, "cPOS", cPOS);
            noPunc = PropertiesUtils.GetBool(props, "noPunc", noPunc);
            doWordEmbeddingGradUpdate = PropertiesUtils.GetBool(props, "doWordEmbeddingGradUpdate", doWordEmbeddingGradUpdate);
            // Runtime parsing options
            sentenceDelimiter = PropertiesUtils.GetString(props, "sentenceDelimiter", sentenceDelimiter);
            tagger            = PropertiesUtils.GetString(props, "tagger.model", tagger);
            string escaperClass = props.GetProperty("escaper");

            escaper = escaperClass != null?ReflectionLoading.LoadByReflection(escaperClass) : null;

            // Language options
            language = props.Contains("language") ? GetLanguage(props.GetProperty("language")) : language;
            tlp      = [email protected]();
            // if a tlp was specified go with that
            string tlpCanonicalName = props.GetProperty("tlp");

            if (tlpCanonicalName != null)
            {
                try
                {
                    tlp = ReflectionLoading.LoadByReflection(tlpCanonicalName);
                    System.Console.Error.WriteLine("Loaded TreebankLanguagePack: " + tlpCanonicalName);
                }
                catch (Exception)
                {
                    System.Console.Error.WriteLine("Error: Failed to load TreebankLanguagePack: " + tlpCanonicalName);
                }
            }
        }
Example #7
0
        public static ShiftReduceOptions BuildTrainingOptions(string tlppClass, string[] args)
        {
            ShiftReduceOptions op = new ShiftReduceOptions();

            op.SetOptions("-forceTags", "-debugOutputFrequency", "1", "-quietEvaluation");
            if (tlppClass != null)
            {
                op.tlpParams = ReflectionLoading.LoadByReflection(tlppClass);
            }
            op.SetOptions(args);
            if (op.trainOptions.randomSeed == 0)
            {
                op.trainOptions.randomSeed = Runtime.NanoTime();
                log.Info("Random seed not set by options, using " + op.trainOptions.randomSeed);
            }
            return(op);
        }
Example #8
0
        public virtual IFunction <IList <IHasWord>, IList <TaggedWord> > LoadTagger()
        {
            Options op = GetOp();

            if (op.testOptions.preTag)
            {
                lock (this)
                {
                    // TODO: rather coarse synchronization
                    if (!op.testOptions.taggerSerializedFile.Equals(taggerPath))
                    {
                        taggerPath = op.testOptions.taggerSerializedFile;
                        tagger     = ReflectionLoading.LoadByReflection("edu.stanford.nlp.tagger.maxent.MaxentTagger", taggerPath);
                    }
                    return(tagger);
                }
            }
            else
            {
                return(null);
            }
        }
Example #9
0
 public virtual void Init(Properties props)
 {
     // TODO: Can get custom mention matcher
     mentionMatcher = ReflectionLoading.LoadByReflection("edu.stanford.nlp.kbp.entitylinking.classify.namematcher.RuleBasedNameMatcher", "dcoref.mentionMatcher", props);
 }
Example #10
0
        // = false;
        // not an instantiable class
        /// <summary>Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile file-with-trees [-po matching-pattern operation] operation-file-1 operation-file-2 ...</summary>
        /// <remarks>
        /// Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile file-with-trees [-po matching-pattern operation] operation-file-1 operation-file-2 ... operation-file-n
        /// <h4>Arguments:</h4>
        /// Each argument should be the name of a transformation file that contains a list of pattern
        /// and transformation operation list pairs.  That is, it is a sequence of pairs of a
        /// <see cref="Edu.Stanford.Nlp.Trees.Tregex.TregexPattern"/>
        /// pattern on one or more lines, then a
        /// blank line (empty or whitespace), then a list of transformation operations one per line
        /// (as specified by <b>Legal operation syntax</b> below) to apply when the pattern is matched,
        /// and then another blank line (empty or whitespace).
        /// Note the need for blank lines: The code crashes if they are not present as separators
        /// (although the blank line at the end of the file can be omitted).
        /// The script file can include comment lines, either whole comment lines or
        /// trailing comments introduced by %, which extend to the end of line.  A needed percent
        /// mark can be escaped by a preceding backslash.
        /// <p>
        /// For example, if you want to excise an SBARQ node whenever it is the parent of an SQ node,
        /// and relabel the SQ node to S, your transformation file would look like this:
        /// <blockquote>
        /// <code>
        /// SBARQ=n1 &lt; SQ=n2<br />
        /// <br />
        /// excise n1 n1<br />
        /// relabel n2 S
        /// </code>
        /// </blockquote>
        /// <h4>Options:</h4>
        /// <ul>
        /// <li>
        /// <c>-treeFile &lt;filename&gt;</c>
        /// specify the name of the file that has the trees you want to transform.
        /// <li>
        /// <c>-po &lt;matchPattern&gt; &lt;operation&gt;</c>
        /// Apply a single operation to every tree using the specified match pattern and the specified operation.  Use this option
        /// when you want to quickly try the effect of one pattern/surgery combination, and are too lazy to write a transformation file.
        /// <li>
        /// <c>-s</c>
        /// Print each output tree on one line (default is pretty-printing).
        /// <li>
        /// <c>-m</c>
        /// For every tree that had a matching pattern, print "before" (prepended as "Operated on:") and "after" (prepended as "Result:").  Unoperated on trees just pass through the transducer as usual.
        /// <li>
        /// <c>-encoding X</c>
        /// Uses character set X for input and output of trees.
        /// <li>
        /// <c>-macros &lt;filename&gt;</c>
        /// A file of macros to use on the tregex pattern.  Macros should be one per line, with original and replacement separated by tabs.
        /// <li>
        /// <c>-hf &lt;headFinder-class-name&gt;</c>
        /// use the specified
        /// <see cref="Edu.Stanford.Nlp.Trees.IHeadFinder"/>
        /// class to determine headship relations.
        /// <li>
        /// <c>-hfArg &lt;string&gt;</c>
        /// pass a string argument in to the
        /// <see cref="Edu.Stanford.Nlp.Trees.IHeadFinder"/>
        /// class's constructor.
        /// <c>-hfArg</c>
        /// can be used multiple times to pass in multiple arguments.
        /// <li>
        /// <c>-trf &lt;TreeReaderFactory-class-name&gt;</c>
        /// use the specified
        /// <see cref="Edu.Stanford.Nlp.Trees.ITreeReaderFactory"/>
        /// class to read trees from files.
        /// </ul>
        /// <h4>Legal operation syntax:</h4>
        /// <ul>
        /// <li>
        /// <c>delete &lt;name&gt;</c>
        /// deletes the node and everything below it.
        /// <li>
        /// <c>prune &lt;name&gt;</c>
        /// Like delete, but if, after the pruning, the parent has no children anymore, the parent is pruned too.  Pruning continues to affect all ancestors until one is found with remaining children.  This may result in a null tree.
        /// <li>
        /// <c>excise &lt;name1&gt; &lt;name2&gt;</c>
        /// The name1 node should either dominate or be the same as the name2 node.  This excises out everything from
        /// name1 to name2.  All the children of name2 go into the parent of name1, where name1 was.
        /// <li>
        /// <c>relabel &lt;name&gt; &lt;new-label&gt;</c>
        /// Relabels the node to have the new label. <br />
        /// There are three possible forms: <br />
        /// <c>relabel nodeX VP</c>
        /// - for changing a node label to an
        /// alphanumeric string <br />
        /// <c>relabel nodeX /''/</c>
        /// - for relabeling a node to
        /// something that isn't a valid identifier without quoting <br />
        /// <c>relabel nodeX /^VB(.*)$/verb\\/$1/</c>
        /// - for regular
        /// expression based relabeling. In this case, all matches of the
        /// regular expression against the node label are replaced with the
        /// replacement String.  This has the semantics of Java/Perl's
        /// replaceAll: you may use capturing groups and put them in
        /// replacements with $n. For example, if the pattern is /foo/bar/
        /// and the node matched is "foo", the replaceAll semantics result in
        /// "barbar".  If the pattern is /^foo(.*)$/bar$1/ and node matched is
        /// "foofoo", relabel will result in "barfoo".  <br />
        /// When using the regex replacement method, you can also use the
        /// sequences ={node} and %{var} in the replacement string to use
        /// captured nodes or variable strings in the replacement string.
        /// For example, if the Tregex pattern was "duck=bar" and the relabel
        /// is /foo/={bar}/, "foofoo" will be replaced with "duckduck". <br />
        /// To concatenate two nodes named in the tregex pattern, for
        /// example, you can use the pattern /^.*$/={foo}={bar}/.  Note that
        /// the ^.*$ is necessary to make sure the regex pattern only matches
        /// and replaces once on the entire node name. <br />
        /// To get an "=" or a "%" in the replacement, using \ escaping.
        /// Also, as in the example you can escape a slash in the middle of
        /// the second and third forms with \\/ and \\\\. <br />
        /// <li>
        /// <c>insert &lt;name&gt; &lt;position&gt;</c>
        /// or
        /// <c>insert &lt;tree&gt; &lt;position&gt;</c>
        /// inserts the named node or tree into the position specified.
        /// <li>
        /// <c>move &lt;name&gt; &lt;position&gt;</c>
        /// moves the named node into the specified position.
        /// <p>Right now the  only ways to specify position are:
        /// <p>
        /// <c>$+ &lt;name&gt;</c>
        /// the left sister of the named node<br />
        /// <c>$- &lt;name&gt;</c>
        /// the right sister of the named node<br />
        /// <c>&gt;i &lt;name&gt;</c>
        /// the i_th daughter of the named node<br />
        /// <c>&gt;-i &lt;name&gt;</c>
        /// the i_th daughter, counting from the right, of the named node.
        /// <li>
        /// <c>replace &lt;name1&gt; &lt;name2&gt;</c>
        /// deletes name1 and inserts a copy of name2 in its place.
        /// <li>
        /// <c>replace &lt;name&gt; &lt;tree&gt; &lt;tree2&gt;...</c>
        /// deletes name and inserts the new tree(s) in its place.  If
        /// more than one replacement tree is given, each of the new
        /// subtrees will be added in order where the old tree was.
        /// Multiple subtrees at the root is an illegal operation and
        /// will throw an exception.
        /// <li>
        /// <c>createSubtree &lt;auxiliary-tree-or-label&gt; &lt;name1&gt; [&lt;name2&gt;]</c>
        /// Create a subtree out of all the nodes from
        /// <c>&lt;name1&gt;</c>
        /// through
        /// <c>&lt;name2&gt;</c>
        /// . The subtree is moved to the foot of the given
        /// auxiliary tree, and the tree is inserted where the nodes of
        /// the subtree used to reside. If a simple label is provided as
        /// the first argument, the subtree is given a single parent with
        /// a name corresponding to the label.  To limit the operation to
        /// just one node, elide
        /// <c>&lt;name2&gt;</c>
        /// .
        /// <li>
        /// <c>adjoin &lt;auxiliary_tree&gt; &lt;name&gt;</c>
        /// Adjoins the specified auxiliary tree into the named node.
        /// The daughters of the target node will become the daughters of the foot of the auxiliary tree.
        /// <li>
        /// <c>adjoinH &lt;auxiliary_tree&gt; &lt;name&gt;</c>
        /// Similar to adjoin, but preserves the target node
        /// and makes it the root of
        /// <c>&lt;tree&gt;</c>
        /// . (It is still accessible as
        /// <c>name</c>
        /// .  The root of the
        /// auxiliary tree is ignored.)
        /// <li>
        /// <c>adjoinF &lt;auxiliary_tree&gt; &lt;name&gt;</c>
        /// Similar to adjoin,
        /// but preserves the target node and makes it the foot of
        /// <c>&lt;tree&gt;</c>
        /// .
        /// (It is still accessible as
        /// <c>name</c>
        /// , and retains its status as parent of its children.
        /// The root of the auxiliary tree is ignored.)
        /// <li> <dt>
        /// <c>coindex &lt;name1&gt; &lt;name2&gt; ... &lt;nameM&gt;</c>
        /// Puts a (Penn Treebank style)
        /// coindexation suffix of the form "-N" on each of nodes name_1 through name_m.  The value of N will be
        /// automatically generated in reference to the existing coindexations in the tree, so that there is never
        /// an accidental clash of indices across things that are not meant to be coindexed.
        /// </ul>
        /// <p>
        /// In the context of
        /// <c>adjoin</c>
        /// ,
        /// <c>adjoinH</c>
        /// ,
        /// <c>adjoinF</c>
        /// , and
        /// <c>createSubtree</c>
        /// , an auxiliary
        /// tree is a tree in Penn Treebank format with
        /// <c>@</c>
        /// on
        /// exactly one of the leaves denoting the foot of the tree.
        /// The operations which use the foot use the labeled node.
        /// For example:
        /// </p>
        /// <blockquote>
        /// Tsurgeon:
        /// <c>adjoin (FOO (BAR@)) foo</c>
        /// <br />
        /// Tregex:
        /// <c>B=foo</c>
        /// <br />
        /// Input:
        /// <c>(A (B 1 2))</c>
        /// Output:
        /// <c>(A (FOO (BAR 1 2)))</c>
        /// </blockquote>
        /// <p>
        /// Tsurgeon applies the same operation to the same tree for as long
        /// as the given tregex operation matches.  This means that infinite
        /// loops are very easy to cause.  One common situation where this comes up
        /// is with an insert operation will repeats infinitely many times
        /// unless you add an expression to the tregex that matches against
        /// the inserted pattern.  For example, this pattern will infinite loop:
        /// </p>
        /// <blockquote>
        /// <code>
        /// TregexPattern tregex = TregexPattern.compile("S=node &lt;&lt; NP"); <br />
        /// TsurgeonPattern tsurgeon = Tsurgeon.parseOperation("insert (NP foo) &gt;-1 node");
        /// </code>
        /// </blockquote>
        /// <p>
        /// This pattern, though, will terminate:
        /// </p>
        /// <blockquote>
        /// <code>
        /// TregexPattern tregex = TregexPattern.compile("S=node &lt;&lt; NP !&lt;&lt; foo"); <br />
        /// TsurgeonPattern tsurgeon = Tsurgeon.parseOperation("insert (NP foo) &gt;-1 node");
        /// </code>
        /// </blockquote>
        /// <p>
        /// Tsurgeon has (very) limited support for conditional statements.
        /// If a pattern is prefaced with
        /// <c>if exists &lt;name&gt;</c>
        /// ,
        /// the rest of the pattern will only execute if
        /// the named node was found in the corresponding TregexMatcher.
        /// </p>
        /// </remarks>
        /// <param name="args">
        /// a list of names of files each of which contains a single tregex matching pattern plus a list, one per line,
        /// of transformation operations to apply to the matched pattern.
        /// </param>
        /// <exception cref="System.Exception">If an I/O or pattern syntax error</exception>
        public static void Main(string[] args)
        {
            string headFinderClassName = null;
            string headFinderOption    = "-hf";

            string[] headFinderArgs      = null;
            string   headFinderArgOption = "-hfArg";
            string   encoding            = "UTF-8";
            string   encodingOption      = "-encoding";

            if (args.Length == 0)
            {
                log.Info("Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile <file-with-trees> [-po <matching-pattern> <operation>] <operation-file-1> <operation-file-2> ... <operation-file-n>");
                System.Environment.Exit(0);
            }
            string treePrintFormats;
            string singleLineOption = "-s";
            string verboseOption    = "-v";
            string matchedOption    = "-m";
            // if set, then print original form of trees that are matched & thus operated on
            string patternOperationOption = "-po";
            string treeFileOption         = "-treeFile";
            string trfOption     = "-trf";
            string macroOption   = "-macros";
            string macroFilename = string.Empty;
            IDictionary <string, int> flagMap = Generics.NewHashMap();

            flagMap[patternOperationOption] = 2;
            flagMap[treeFileOption]         = 1;
            flagMap[trfOption]        = 1;
            flagMap[singleLineOption] = 0;
            flagMap[encodingOption]   = 1;
            flagMap[headFinderOption] = 1;
            flagMap[macroOption]      = 1;
            IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, flagMap);

            args = argsMap[null];
            if (argsMap.Contains(headFinderOption))
            {
                headFinderClassName = argsMap[headFinderOption][0];
            }
            if (argsMap.Contains(headFinderArgOption))
            {
                headFinderArgs = argsMap[headFinderArgOption];
            }
            if (argsMap.Contains(verboseOption))
            {
                verbose = true;
            }
            if (argsMap.Contains(singleLineOption))
            {
                treePrintFormats = "oneline,";
            }
            else
            {
                treePrintFormats = "penn,";
            }
            if (argsMap.Contains(encodingOption))
            {
                encoding = argsMap[encodingOption][0];
            }
            if (argsMap.Contains(macroOption))
            {
                macroFilename = argsMap[macroOption][0];
            }
            TreePrint          tp    = new TreePrint(treePrintFormats, new PennTreebankLanguagePack());
            PrintWriter        pwOut = new PrintWriter(new OutputStreamWriter(System.Console.Out, encoding), true);
            ITreeReaderFactory trf;

            if (argsMap.Contains(trfOption))
            {
                string trfClass = argsMap[trfOption][0];
                trf = ReflectionLoading.LoadByReflection(trfClass);
            }
            else
            {
                trf = new TregexPattern.TRegexTreeReaderFactory();
            }
            Treebank trees = new DiskTreebank(trf, encoding);

            if (argsMap.Contains(treeFileOption))
            {
                trees.LoadPath(argsMap[treeFileOption][0]);
            }
            if (trees.IsEmpty())
            {
                log.Info("Warning: No trees specified to operate on.  Use -treeFile path option.");
            }
            TregexPatternCompiler compiler;

            if (headFinderClassName == null)
            {
                compiler = new TregexPatternCompiler();
            }
            else
            {
                IHeadFinder hf;
                if (headFinderArgs == null)
                {
                    hf = ReflectionLoading.LoadByReflection(headFinderClassName);
                }
                else
                {
                    hf = ReflectionLoading.LoadByReflection(headFinderClassName, (object[])headFinderArgs);
                }
                compiler = new TregexPatternCompiler(hf);
            }
            Macros.AddAllMacros(compiler, macroFilename, encoding);
            IList <Pair <TregexPattern, TsurgeonPattern> > ops = new List <Pair <TregexPattern, TsurgeonPattern> >();

            if (argsMap.Contains(patternOperationOption))
            {
                TregexPattern   matchPattern = compiler.Compile(argsMap[patternOperationOption][0]);
                TsurgeonPattern p            = ParseOperation(argsMap[patternOperationOption][1]);
                ops.Add(new Pair <TregexPattern, TsurgeonPattern>(matchPattern, p));
            }
            else
            {
                foreach (string arg in args)
                {
                    IList <Pair <TregexPattern, TsurgeonPattern> > pairs = GetOperationsFromFile(arg, encoding, compiler);
                    foreach (Pair <TregexPattern, TsurgeonPattern> pair in pairs)
                    {
                        if (verbose)
                        {
                            log.Info(pair.Second());
                        }
                        ops.Add(pair);
                    }
                }
            }
            foreach (Tree t in trees)
            {
                Tree original = t.DeepCopy();
                Tree result   = ProcessPatternsOnTree(ops, t);
                if (argsMap.Contains(matchedOption) && matchedOnTree)
                {
                    pwOut.Println("Operated on: ");
                    DisplayTree(original, tp, pwOut);
                    pwOut.Println("Result: ");
                }
                DisplayTree(result, tp, pwOut);
            }
        }
Example #11
0
 public static Edu.Stanford.Nlp.Tagger.Common.Tagger LoadModel(string path)
 {
     // TODO: we can avoid ReflectionLoading if we instead use the
     // serialization mechanism in MaxentTagger.  Similar to ParserGrammar
     return(ReflectionLoading.LoadByReflection("edu.stanford.nlp.tagger.maxent.MaxentTagger", path));
 }
Example #12
0
        public SerializedAnnotationCreator(string name, Properties props)
        {
            string serializerClass = props.GetProperty(name + ".serializer");

            serializer = ReflectionLoading.LoadByReflection(serializerClass);
        }
        public static Edu.Stanford.Nlp.Tagger.IO.TaggedFileRecord CreateRecord(Properties config, string description)
        {
            string[] pieces = description.Split(",");
            if (pieces.Length == 1)
            {
                return(new Edu.Stanford.Nlp.Tagger.IO.TaggedFileRecord(description, TaggedFileRecord.Format.Text, GetEncoding(config), GetTagSeparator(config), null, null, null, null, null, null, null));
            }
            string[] args = new string[pieces.Length - 1];
            System.Array.Copy(pieces, 0, args, 0, pieces.Length - 1);
            string file = pieces[pieces.Length - 1];

            TaggedFileRecord.Format format         = TaggedFileRecord.Format.Text;
            string                 encoding        = GetEncoding(config);
            string                 tagSeparator    = GetTagSeparator(config);
            ITreeTransformer       treeTransformer = null;
            TreeNormalizer         treeNormalizer  = null;
            ITreeReaderFactory     trf             = null;
            NumberRangesFileFilter treeRange       = null;
            IPredicate <Tree>      treeFilter      = null;
            int wordColumn = null;
            int tagColumn  = null;

            foreach (string arg in args)
            {
                string[] argPieces = arg.Split("=", 2);
                if (argPieces.Length != 2)
                {
                    throw new ArgumentException("TaggedFileRecord argument " + arg + " has an unexpected number of =s");
                }
                if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], Format))
                {
                    format = TaggedFileRecord.Format.ValueOf(argPieces[1]);
                }
                else
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], Encoding))
                    {
                        encoding = argPieces[1];
                    }
                    else
                    {
                        if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TagSeparator))
                        {
                            tagSeparator = argPieces[1];
                        }
                        else
                        {
                            if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TreeTransformer))
                            {
                                treeTransformer = ReflectionLoading.LoadByReflection(argPieces[1]);
                            }
                            else
                            {
                                if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TreeNormalizer))
                                {
                                    treeNormalizer = ReflectionLoading.LoadByReflection(argPieces[1]);
                                }
                                else
                                {
                                    if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TreeReader))
                                    {
                                        trf = ReflectionLoading.LoadByReflection(argPieces[1]);
                                    }
                                    else
                                    {
                                        if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TreeRange))
                                        {
                                            string range = argPieces[1].ReplaceAll(":", ",");
                                            treeRange = new NumberRangesFileFilter(range, true);
                                        }
                                        else
                                        {
                                            if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TreeFilter))
                                            {
                                                treeFilter = ReflectionLoading.LoadByReflection(argPieces[1]);
                                            }
                                            else
                                            {
                                                if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], WordColumn))
                                                {
                                                    wordColumn = int.Parse(argPieces[1]);
                                                }
                                                else
                                                {
                                                    if (Sharpen.Runtime.EqualsIgnoreCase(argPieces[0], TagColumn))
                                                    {
                                                        tagColumn = int.Parse(argPieces[1]);
                                                    }
                                                    else
                                                    {
                                                        throw new ArgumentException("TaggedFileRecord argument " + argPieces[0] + " is unknown");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(new Edu.Stanford.Nlp.Tagger.IO.TaggedFileRecord(file, format, encoding, tagSeparator, treeTransformer, treeNormalizer, trf, treeRange, treeFilter, wordColumn, tagColumn));
        }
Example #14
0
 public virtual void InitializeTraining(double numTrees)
 {
     this.uwModelTrainer = ReflectionLoading.LoadByReflection(uwModelTrainerClass);
     uwModelTrainer.InitializeTraining(op, this, wordIndex, tagIndex, numTrees);
 }
 public static ITimeExpressionExtractor Create(string className, string name, Properties props)
 {
     return(ReflectionLoading.LoadByReflection(className, name, props));
 }
 public static ITimeExpressionExtractor Create(string className)
 {
     return(ReflectionLoading.LoadByReflection(className));
 }
Example #17
0
        public virtual void TestNoArgs()
        {
            string s = ReflectionLoading.LoadByReflection("java.lang.String");

            NUnit.Framework.Assert.AreEqual(string.Empty, s);
        }
Example #18
0
        public virtual void TestOneArg()
        {
            string s = ReflectionLoading.LoadByReflection("java.lang.String", "foo");

            NUnit.Framework.Assert.AreEqual("foo", s);
        }
Example #19
0
        /// <summary>Loads treebank and prints it.</summary>
        /// <remarks>
        /// Loads treebank and prints it.
        /// All files below the designated
        /// <c>filePath</c>
        /// within the given
        /// number range if any are loaded.  You can normalize the trees or not
        /// (English-specific) and print trees one per line up to a certain length
        /// (for EVALB).
        /// <p>
        /// Usage:
        /// <c>java edu.stanford.nlp.trees.Treebanks [-maxLength n|-normalize|-treeReaderFactory class] filePath [numberRanges]</c>
        /// </remarks>
        /// <param name="args">Array of command-line arguments</param>
        /// <exception cref="System.IO.IOException">If there is a treebank file access problem</exception>
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsage();
                return;
            }
            int                        i = 0;
            int                        maxLength;
            int                        minLength;
            int                        maxL              = int.MaxValue;
            int                        minL              = -1;
            bool                       normalized        = false;
            bool                       decimate          = false;
            bool                       pennPrintTrees    = false;
            bool                       oneLinePrint      = false;
            bool                       printTaggedWords  = false;
            bool                       printWords        = false;
            bool                       correct           = false;
            string                     annotationOptions = null;
            bool                       summary           = false;
            bool                       timing            = false;
            bool                       yield             = false;
            bool                       punct             = false;
            bool                       sentenceLengths   = false;
            bool                       countTaggings     = false;
            bool                       removeCodeTrees   = false;
            string                     decimatePrefix    = null;
            string                     encoding          = TreebankLanguagePackConstants.DefaultEncoding;
            string                     suffix            = Treebank.DefaultTreeFileSuffix;
            ITreeReaderFactory         trf     = null;
            ITreebankLanguagePack      tlp     = null;
            IList <IPredicate <Tree> > filters = new List <IPredicate <Tree> >();

            while (i < args.Length && args[i].StartsWith("-"))
            {
                if (args[i].Equals("-maxLength") && i + 1 < args.Length)
                {
                    maxL = System.Convert.ToInt32(args[i + 1]);
                    i   += 2;
                }
                else
                {
                    if (args[i].Equals("-minLength") && i + 1 < args.Length)
                    {
                        minL = System.Convert.ToInt32(args[i + 1]);
                        i   += 2;
                    }
                    else
                    {
                        if (args[i].Equals("-h") || args[i].Equals("-help"))
                        {
                            PrintUsage();
                            i++;
                        }
                        else
                        {
                            if (args[i].Equals("-normalized"))
                            {
                                normalized = true;
                                i         += 1;
                            }
                            else
                            {
                                if (Sharpen.Runtime.EqualsIgnoreCase(args[i], "-tlp"))
                                {
                                    try
                                    {
                                        object o = Sharpen.Runtime.GetType(args[i + 1]).GetDeclaredConstructor().NewInstance();
                                        tlp = (ITreebankLanguagePack)o;
                                        trf = tlp.TreeReaderFactory();
                                    }
                                    catch (Exception)
                                    {
                                        log.Info("Couldn't instantiate as TreebankLanguagePack: " + args[i + 1]);
                                        return;
                                    }
                                    i += 2;
                                }
                                else
                                {
                                    if (args[i].Equals("-treeReaderFactory") || args[i].Equals("-trf"))
                                    {
                                        try
                                        {
                                            object o = Sharpen.Runtime.GetType(args[i + 1]).GetDeclaredConstructor().NewInstance();
                                            trf = (ITreeReaderFactory)o;
                                        }
                                        catch (Exception)
                                        {
                                            log.Info("Couldn't instantiate as TreeReaderFactory: " + args[i + 1]);
                                            return;
                                        }
                                        i += 2;
                                    }
                                    else
                                    {
                                        if (args[i].Equals("-suffix"))
                                        {
                                            suffix = args[i + 1];
                                            i     += 2;
                                        }
                                        else
                                        {
                                            if (args[i].Equals("-decimate"))
                                            {
                                                decimate       = true;
                                                decimatePrefix = args[i + 1];
                                                i += 2;
                                            }
                                            else
                                            {
                                                if (args[i].Equals("-encoding"))
                                                {
                                                    encoding = args[i + 1];
                                                    i       += 2;
                                                }
                                                else
                                                {
                                                    if (args[i].Equals("-correct"))
                                                    {
                                                        correct = true;
                                                        i      += 1;
                                                    }
                                                    else
                                                    {
                                                        if (args[i].Equals("-summary"))
                                                        {
                                                            summary = true;
                                                            i      += 1;
                                                        }
                                                        else
                                                        {
                                                            if (args[i].Equals("-yield"))
                                                            {
                                                                yield = true;
                                                                i    += 1;
                                                            }
                                                            else
                                                            {
                                                                if (args[i].Equals("-punct"))
                                                                {
                                                                    punct = true;
                                                                    i    += 1;
                                                                }
                                                                else
                                                                {
                                                                    if (args[i].Equals("-pennPrint"))
                                                                    {
                                                                        pennPrintTrees = true;
                                                                        i++;
                                                                    }
                                                                    else
                                                                    {
                                                                        if (args[i].Equals("-oneLine"))
                                                                        {
                                                                            oneLinePrint = true;
                                                                            i++;
                                                                        }
                                                                        else
                                                                        {
                                                                            if (args[i].Equals("-taggedWords"))
                                                                            {
                                                                                printTaggedWords = true;
                                                                                i++;
                                                                            }
                                                                            else
                                                                            {
                                                                                if (args[i].Equals("-words"))
                                                                                {
                                                                                    printWords = true;
                                                                                    i++;
                                                                                }
                                                                                else
                                                                                {
                                                                                    if (args[i].Equals("-annotate"))
                                                                                    {
                                                                                        annotationOptions = args[i + 1];
                                                                                        i += 2;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        if (args[i].Equals("-timing"))
                                                                                        {
                                                                                            timing = true;
                                                                                            i++;
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            if (args[i].Equals("-countTaggings"))
                                                                                            {
                                                                                                countTaggings = true;
                                                                                                i++;
                                                                                            }
                                                                                            else
                                                                                            {
                                                                                                if (args[i].Equals("-sentenceLengths"))
                                                                                                {
                                                                                                    sentenceLengths = true;
                                                                                                    i++;
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                    if (args[i].Equals("-removeCodeTrees"))
                                                                                                    {
                                                                                                        removeCodeTrees = true;
                                                                                                        i++;
                                                                                                    }
                                                                                                    else
                                                                                                    {
                                                                                                        if (args[i].Equals("-filter"))
                                                                                                        {
                                                                                                            IPredicate <Tree> filter = ReflectionLoading.LoadByReflection(args[i + 1]);
                                                                                                            filters.Add(filter);
                                                                                                            i += 2;
                                                                                                        }
                                                                                                        else
                                                                                                        {
                                                                                                            log.Info("Unknown option: " + args[i]);
                                                                                                            i++;
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            maxLength = maxL;
            minLength = minL;
            Treebank treebank;

            if (trf == null)
            {
                trf = null;
            }
            if (normalized)
            {
                treebank = new DiskTreebank();
            }
            else
            {
                treebank = new DiskTreebank(trf, encoding);
            }
            foreach (IPredicate <Tree> filter_1 in filters)
            {
                treebank = new FilteringTreebank(treebank, filter_1);
            }
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.Console.Out, encoding), true);

            if (i + 1 < args.Length)
            {
                treebank.LoadPath(args[i], new NumberRangesFileFilter(args[i + 1], true));
            }
            else
            {
                if (i < args.Length)
                {
                    treebank.LoadPath(args[i], suffix, true);
                }
                else
                {
                    PrintUsage();
                    return;
                }
            }
            // log.info("Loaded " + treebank.size() + " trees from " + args[i]);
            if (annotationOptions != null)
            {
                // todo Not yet implemented
                log.Info("annotationOptions not yet implemented");
            }
            if (summary)
            {
                System.Console.Out.WriteLine(treebank.TextualSummary());
            }
            if (sentenceLengths)
            {
                SentenceLengths(treebank, args[i], ((i + 1) < args.Length ? args[i + 1] : null), pw);
            }
            if (punct)
            {
                PrintPunct(treebank, tlp, pw);
            }
            if (correct)
            {
                treebank = new EnglishPTBTreebankCorrector().TransformTrees(treebank);
            }
            if (pennPrintTrees)
            {
                treebank.Apply(null);
            }
            if (oneLinePrint)
            {
                treebank.Apply(null);
            }
            if (printWords)
            {
                TreeNormalizer tn = new BobChrisTreeNormalizer();
                treebank.Apply(null);
            }
            if (printTaggedWords)
            {
                TreeNormalizer tn = new BobChrisTreeNormalizer();
                treebank.Apply(null);
            }
            if (countTaggings)
            {
                CountTaggings(treebank, pw);
            }
            if (yield)
            {
                treebank.Apply(null);
            }
            if (decimate)
            {
                TextWriter w1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(decimatePrefix + "-train.txt"), encoding));
                TextWriter w2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(decimatePrefix + "-dev.txt"), encoding));
                TextWriter w3 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(decimatePrefix + "-test.txt"), encoding));
                treebank.Decimate(w1, w2, w3);
            }
            if (timing)
            {
                RunTiming(treebank);
            }
            if (removeCodeTrees)
            {
                // this is a bit of a hack. It only works on an individual file
                if (new File(args[i]).IsDirectory())
                {
                    throw new Exception("-removeCodeTrees only works on a single file");
                }
                string treebankStr = IOUtils.SlurpFile(args[i]);
                treebankStr = treebankStr.ReplaceAll("\\( \\(CODE <[^>]+>\\)\\)", string.Empty);
                TextWriter w = new OutputStreamWriter(new FileOutputStream(args[i]), encoding);
                w.Write(treebankStr);
                w.Close();
            }
        }