Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/moses-smt/mosesdecoder.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Jamroot4
-rw-r--r--contrib/server/mosesserver.cpp3
-rw-r--r--jam-files/sanity.jam4
-rw-r--r--lm/COPYING674
-rw-r--r--lm/COPYING.LESSER165
-rw-r--r--lm/Jamfile20
-rw-r--r--lm/LICENSE12
-rw-r--r--lm/README44
-rwxr-xr-xlm/clean.sh3
-rwxr-xr-xlm/compile.sh16
-rw-r--r--lm/fragment.cc37
-rw-r--r--lm/max_order.hh2
-rw-r--r--lm/partial.hh167
-rw-r--r--lm/partial_test.cc199
-rw-r--r--lm/state.hh2
-rwxr-xr-xlm/test.sh10
-rw-r--r--lm/word_index.hh3
-rw-r--r--moses-chart-cmd/src/IOWrapper.h2
-rw-r--r--moses-chart-cmd/src/Main.cpp17
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.cpp9
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.h4
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.cpp11
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.h6
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.cpp12
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.h6
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.cpp10
-rw-r--r--moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.h6
-rw-r--r--moses/src/ChartCell.cpp25
-rw-r--r--moses/src/ChartCell.h37
-rw-r--r--moses/src/ChartCellCollection.cpp47
-rw-r--r--moses/src/ChartCellCollection.h62
-rw-r--r--moses/src/ChartCellLabel.h16
-rw-r--r--moses/src/ChartCellLabelSet.h16
-rw-r--r--moses/src/ChartManager.cpp145
-rw-r--r--moses/src/ChartManager.h11
-rw-r--r--moses/src/ChartParser.cpp168
-rw-r--r--moses/src/ChartParser.h72
-rw-r--r--moses/src/ChartParserCallback.h24
-rw-r--r--moses/src/ChartRuleLookupManager.h17
-rw-r--r--moses/src/ChartTranslationOptionList.cpp8
-rw-r--r--moses/src/ChartTranslationOptionList.h14
-rw-r--r--moses/src/ChartTranslationOptions.cpp4
-rw-r--r--moses/src/CompactPT/PhraseDictionaryCompact.h2
-rw-r--r--moses/src/Incremental/Fill.cpp145
-rw-r--r--moses/src/Incremental/Fill.h54
-rw-r--r--moses/src/Incremental/Jamfile1
-rw-r--r--moses/src/Incremental/Manager.cpp121
-rw-r--r--moses/src/Incremental/Manager.h35
-rw-r--r--moses/src/Jamfile2
-rw-r--r--moses/src/LM/Base.cpp5
-rw-r--r--moses/src/LM/Base.h5
-rw-r--r--moses/src/LM/Jamfile2
-rw-r--r--moses/src/LM/Ken.cpp5
-rw-r--r--moses/src/Phrase.cpp12
-rw-r--r--moses/src/Phrase.h2
-rw-r--r--moses/src/PhraseDictionary.h5
-rw-r--r--moses/src/PhraseDictionaryDynSuffixArray.cpp2
-rw-r--r--moses/src/PhraseDictionaryDynSuffixArray.h2
-rw-r--r--moses/src/PhraseDictionaryMemory.h2
-rw-r--r--moses/src/PhraseDictionaryTreeAdaptor.h2
-rw-r--r--moses/src/RuleCubeItem.cpp2
-rw-r--r--moses/src/RuleTable/Loader.h2
-rw-r--r--moses/src/RuleTable/LoaderCompact.cpp3
-rw-r--r--moses/src/RuleTable/LoaderCompact.h2
-rw-r--r--moses/src/RuleTable/LoaderHiero.cpp4
-rw-r--r--moses/src/RuleTable/LoaderHiero.h2
-rw-r--r--moses/src/RuleTable/LoaderStandard.cpp86
-rw-r--r--moses/src/RuleTable/LoaderStandard.h4
-rw-r--r--moses/src/RuleTable/PhraseDictionaryALSuffixArray.cpp5
-rw-r--r--moses/src/RuleTable/PhraseDictionaryFuzzyMatch.cpp2
-rw-r--r--moses/src/RuleTable/PhraseDictionaryFuzzyMatch.h3
-rw-r--r--moses/src/RuleTable/PhraseDictionaryOnDisk.cpp2
-rw-r--r--moses/src/RuleTable/PhraseDictionaryOnDisk.h2
-rw-r--r--moses/src/RuleTable/PhraseDictionarySCFG.cpp2
-rw-r--r--moses/src/RuleTable/PhraseDictionarySCFG.h2
-rw-r--r--moses/src/RuleTable/Trie.cpp5
-rw-r--r--moses/src/RuleTable/UTrie.cpp2
-rw-r--r--moses/src/RuleTable/UTrie.h2
-rw-r--r--moses/src/Scope3Parser/Parser.cpp4
-rw-r--r--moses/src/Scope3Parser/Parser.h10
-rw-r--r--moses/src/Scope3Parser/StackLatticeBuilder.cpp9
-rw-r--r--moses/src/Scope3Parser/StackLatticeBuilder.h2
-rw-r--r--moses/src/Scope3Parser/StackLatticeSearcher.h2
-rw-r--r--moses/src/Sentence.cpp4
-rw-r--r--moses/src/StackVec.h6
-rw-r--r--moses/src/StaticData.cpp6
-rw-r--r--moses/src/StaticData.h3
-rw-r--r--moses/src/TypeDef.h1
-rw-r--r--moses/src/Word.cpp19
-rw-r--r--moses/src/Word.h3
-rwxr-xr-xscripts/generic/trainlm-irst.perl4
-rw-r--r--search/Jamfile5
-rw-r--r--search/arity.hh8
-rw-r--r--search/config.hh25
-rw-r--r--search/context.hh65
-rw-r--r--search/edge.hh31
-rw-r--r--search/edge_generator.cc120
-rw-r--r--search/edge_generator.hh58
-rw-r--r--search/edge_queue.cc25
-rw-r--r--search/edge_queue.hh73
-rw-r--r--search/final.hh39
-rw-r--r--search/note.hh12
-rw-r--r--search/rule.cc43
-rw-r--r--search/rule.hh20
-rw-r--r--search/source.hh48
-rw-r--r--search/types.hh18
-rw-r--r--search/vertex.cc48
-rw-r--r--search/vertex.hh158
-rw-r--r--search/vertex_generator.cc83
-rw-r--r--search/vertex_generator.hh59
-rw-r--r--search/weights.cc71
-rw-r--r--search/weights.hh52
-rw-r--r--search/weights_test.cc38
-rw-r--r--util/COPYING674
-rw-r--r--util/COPYING.LESSER165
-rw-r--r--util/Jamfile14
-rw-r--r--util/LICENSE20
-rw-r--r--util/have.hh2
-rw-r--r--util/string_piece.cc192
-rw-r--r--util/util.xcodeproj/project.pbxproj297
120 files changed, 2677 insertions, 2509 deletions
diff --git a/Jamroot b/Jamroot
index e9a2845bd..ec20a7fdd 100644
--- a/Jamroot
+++ b/Jamroot
@@ -112,9 +112,9 @@ project : requirements
;
#Add directories here if you want their incidental targets too (i.e. tests).
-build-projects util lm moses/src mert moses-cmd/src moses-chart-cmd/src mira scripts regression-testing ;
+build-projects lm util search moses/src mert moses-cmd/src moses-chart-cmd/src mira scripts regression-testing ;
-alias programs : lm//query lm//build_binary lm//kenlm_max_order moses-chart-cmd/src//moses_chart moses-cmd/src//programs OnDiskPt//CreateOnDiskPt OnDiskPt//queryOnDiskPt mert//programs contrib/server//mosesserver misc//programs mira//programs symal phrase-extract phrase-extract//lexical-reordering phrase-extract//extract-ghkm phrase-extract//pcfg-extract phrase-extract//pcfg-score biconcor ;
+alias programs : lm//programs moses-chart-cmd/src//moses_chart moses-cmd/src//programs OnDiskPt//CreateOnDiskPt OnDiskPt//queryOnDiskPt mert//programs contrib/server//mosesserver misc//programs symal phrase-extract phrase-extract//lexical-reordering phrase-extract//extract-ghkm phrase-extract//pcfg-extract phrase-extract//pcfg-score biconcor mira//mira ;
install-bin-libs programs ;
install-headers headers-base : [ path.glob-tree biconcor contrib lm mert misc moses-chart-cmd moses-cmd OnDiskPt phrase-extract symal util : *.hh *.h ] : . ;
diff --git a/contrib/server/mosesserver.cpp b/contrib/server/mosesserver.cpp
index f040d8b12..dc721894e 100644
--- a/contrib/server/mosesserver.cpp
+++ b/contrib/server/mosesserver.cpp
@@ -175,8 +175,7 @@ public:
stringstream out, graphInfo, transCollOpts;
map<string, xmlrpc_c::value> retData;
- SearchAlgorithm searchAlgorithm = staticData.GetSearchAlgorithm();
- if (searchAlgorithm == ChartDecoding) {
+ if (staticData.IsChart()) {
TreeInput tinput;
const vector<FactorType> &inputFactorOrder =
staticData.GetInputFactorOrder();
diff --git a/jam-files/sanity.jam b/jam-files/sanity.jam
index c8435862c..ab126c9fb 100644
--- a/jam-files/sanity.jam
+++ b/jam-files/sanity.jam
@@ -63,7 +63,7 @@ requirements = ;
FORCE-STATIC = [ option.get "static" : : "yes" ] ;
if $(FORCE-STATIC) {
- requirements += <runtime-link>static ;
+ requirements += <link>static <runtime-link>static ;
}
#Determine if a library can be compiled statically.
@@ -260,3 +260,5 @@ if [ option.get "sanity-test" : : "yes" ] {
EXIT "Bad" : 1 ;
}
}
+
+use-project /top : . ;
diff --git a/lm/COPYING b/lm/COPYING
deleted file mode 100644
index 94a9ed024..000000000
--- a/lm/COPYING
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/lm/COPYING.LESSER b/lm/COPYING.LESSER
deleted file mode 100644
index cca7fc278..000000000
--- a/lm/COPYING.LESSER
+++ /dev/null
@@ -1,165 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-
- This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
- 0. Additional Definitions.
-
- As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
- "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
- An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
- A "Combined Work" is a work produced by combining or linking an
-Application with the Library. The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
- The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
- The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
- 1. Exception to Section 3 of the GNU GPL.
-
- You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
- 2. Conveying Modified Versions.
-
- If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
- a) under this License, provided that you make a good faith effort to
- ensure that, in the event an Application does not supply the
- function or data, the facility still operates, and performs
- whatever part of its purpose remains meaningful, or
-
- b) under the GNU GPL, with none of the additional permissions of
- this License applicable to that copy.
-
- 3. Object Code Incorporating Material from Library Header Files.
-
- The object code form of an Application may incorporate material from
-a header file that is part of the Library. You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
- a) Give prominent notice with each copy of the object code that the
- Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the object code with a copy of the GNU GPL and this license
- document.
-
- 4. Combined Works.
-
- You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
- a) Give prominent notice with each copy of the Combined Work that
- the Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
- document.
-
- c) For a Combined Work that displays copyright notices during
- execution, include the copyright notice for the Library among
- these notices, as well as a reference directing the user to the
- copies of the GNU GPL and this license document.
-
- d) Do one of the following:
-
- 0) Convey the Minimal Corresponding Source under the terms of this
- License, and the Corresponding Application Code in a form
- suitable for, and under terms that permit, the user to
- recombine or relink the Application with a modified version of
- the Linked Version to produce a modified Combined Work, in the
- manner specified by section 6 of the GNU GPL for conveying
- Corresponding Source.
-
- 1) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (a) uses at run time
- a copy of the Library already present on the user's computer
- system, and (b) will operate properly with a modified version
- of the Library that is interface-compatible with the Linked
- Version.
-
- e) Provide Installation Information, but only if you would otherwise
- be required to provide such information under section 6 of the
- GNU GPL, and only to the extent that such information is
- necessary to install and execute a modified version of the
- Combined Work produced by recombining or relinking the
- Application with a modified version of the Linked Version. (If
- you use option 4d0, the Installation Information must accompany
- the Minimal Corresponding Source and Corresponding Application
- Code. If you use option 4d1, you must provide the Installation
- Information in the manner specified by section 6 of the GNU GPL
- for conveying Corresponding Source.)
-
- 5. Combined Libraries.
-
- You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
- a) Accompany the combined library with a copy of the same work based
- on the Library, uncombined with any other library facilities,
- conveyed under the terms of this License.
-
- b) Give prominent notice with the combined library that part of it
- is a work based on the Library, and explaining where to find the
- accompanying uncombined form of the same work.
-
- 6. Revised Versions of the GNU Lesser General Public License.
-
- The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
- If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
-Library.
diff --git a/lm/Jamfile b/lm/Jamfile
index fd169b000..045dfee92 100644
--- a/lm/Jamfile
+++ b/lm/Jamfile
@@ -1,20 +1,12 @@
-# If you need higher order, change this option
-# Having this limit means that State can be
-# (KENLM_MAX_ORDER - 1) * sizeof(float) bytes instead of
-# sizeof(float*) + (KENLM_MAX_ORDER - 1) * sizeof(float) + malloc overhead
-max-order = [ option.get "max-kenlm-order" : 6 : 6 ] ;
-if ( $(max-order) != 6 ) {
- echo "Setting KenLM maximum n-gram order to $(max-order)" ;
-}
-max-order = <define>KENLM_MAX_ORDER=$(max-order) ;
-
-lib kenlm : bhiksha.cc binary_format.cc config.cc lm_exception.cc model.cc quantize.cc read_arpa.cc search_hashed.cc search_trie.cc trie.cc trie_sort.cc value_build.cc virtual_interface.cc vocab.cc ../util//kenutil : <include>.. $(max-order) : : <include>.. <library>../util//kenutil $(max-order) ;
+lib kenlm : bhiksha.cc binary_format.cc config.cc lm_exception.cc model.cc quantize.cc read_arpa.cc search_hashed.cc search_trie.cc trie.cc trie_sort.cc value_build.cc virtual_interface.cc vocab.cc ../util//kenutil : <include>.. : : <include>.. <library>../util//kenutil ;
import testing ;
-run left_test.cc ../util//kenutil kenlm ..//boost_unit_test_framework : : test.arpa ;
-run model_test.cc ../util//kenutil kenlm ..//boost_unit_test_framework : : test.arpa test_nounk.arpa ;
+run left_test.cc ../util//kenutil kenlm /top//boost_unit_test_framework : : test.arpa ;
+run model_test.cc ../util//kenutil kenlm /top//boost_unit_test_framework : : test.arpa test_nounk.arpa ;
exe query : ngram_query.cc kenlm ../util//kenutil ;
exe build_binary : build_binary.cc kenlm ../util//kenutil ;
-exe kenlm_max_order : max_order.cc : <include>.. $(max-order) ;
+exe kenlm_max_order : max_order.cc : <include>.. ;
+
+alias programs : query build_binary kenlm_max_order ;
diff --git a/lm/LICENSE b/lm/LICENSE
deleted file mode 100644
index ea98515f4..000000000
--- a/lm/LICENSE
+++ /dev/null
@@ -1,12 +0,0 @@
- Avenue code is free software: you can redistribute it and/or modify
- it under the terms of the GNU Lesser General Public License as published
- by the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Avenue code is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with Avenue code. If not, see <http://www.gnu.org/licenses/>.
diff --git a/lm/README b/lm/README
deleted file mode 100644
index 03c2da8f5..000000000
--- a/lm/README
+++ /dev/null
@@ -1,44 +0,0 @@
-Language model inference code by Kenneth Heafield <kenlm at kheafield.com>
-
-THE GIT REPOSITORY https://github.com/kpu/kenlm IS WHERE ACTIVE DEVELOPMENT HAPPENS. IT MAY RETURN SILENTLY WRONG ANSWERS OR BE SILENTLY BINARY-INCOMPATIBLE WITH STABLE RELEASES.
-
-The website http://kheafield.com/code/kenlm/ has more documentation. If you're a decoder developer, please download the latest version from there instead of copying from another decoder.
-
-Two data structures are supported: probing and trie. Probing is a probing hash table with keys that ere 64-bit hashes of n-grams and floats as values. Trie is a fairly standard trie but with bit-level packing so it uses the minimum number of bits to store word indices and pointers. The trie node entries are sorted by word index. Probing is the fastest and uses the most memory. Trie uses the least memory and a bit slower.
-
-With trie, resident memory is 58% of IRST's smallest version and 21% of SRI's compact version. Simultaneously, trie CPU's use is 81% of IRST's fastest version and 84% of SRI's fast version. KenLM's probing hash table implementation goes even faster at the expense of using more memory. See http://kheafield.com/code/kenlm/benchmark/.
-
-Binary format via mmap is supported. Run ./build_binary to make one then pass the binary file name to the appropriate Model constructor.
-
-
-PLATFORMS
-murmur_hash.cc and bit_packing.hh perform unaligned reads and writes that make the code architecture-dependent.
-It has been sucessfully tested on x86_64, x86, and PPC64.
-ARM support is reportedly working, at least on the iphone, but I cannot test this.
-
-Runs on Linux, OS X, Cygwin, and MinGW.
-
-Hideo Okuma and Tomoyuki Yoshimura from NICT contributed ports to ARM and MinGW. Hieu Hoang is working on a native Windows port.
-
-
-DECODER DEVELOPERS
-- I recommend copying the code and distributing it with your decoder. However, please send improvements upstream as indicated in CONTRIBUTORS.
-
-- It does not depend on Boost or ICU. If you use ICU, define HAVE_ICU in util/have.hh (uncomment the line) to avoid a name conflict. Defining HAVE_BOOST will let you hash StringPiece.
-
-- Most people have zlib. If you don't want to depend on that, comment out #define HAVE_ZLIB in util/have.hh. This will disable loading gzipped ARPA files.
-
-- There are two build systems: compile.sh and Jamroot+Jamfile. They're pretty simple and are intended to be reimplemented in your build system.
-
-- Use either the interface in lm/model.hh or lm/virtual_interface.hh. Interface documentation is in comments of lm/virtual_interface.hh and lm/model.hh.
-
-- There are several possible data structures in model.hh. Use RecognizeBinary in binary_format.hh to determine which one a user has provided. You probably already implement feature functions as an abstract virtual base class with several children. I suggest you co-opt this existing virtual dispatch by templatizing the language model feature implementation on the KenLM model identified by RecognizeBinary. This is the strategy used in Moses and cdec.
-
-- See lm/config.hh for tuning options.
-
-
-CONTRIBUTORS
-Contributions to KenLM are welcome. Please base your contributions on https://github.com/kpu/kenlm and send pull requests (or I might give you commit access). Downstream copies in Moses and cdec are maintained by overwriting them so do not make changes there.
-
-
-The name was Hieu Hoang's idea, not mine.
diff --git a/lm/clean.sh b/lm/clean.sh
deleted file mode 100755
index 4d2d01f79..000000000
--- a/lm/clean.sh
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-cd "$(dirname "$0")/.."
-rm -rf {lm,util}/*.o lm/query lm/build_binary {lm,util}/*_test lm/test.binary* lm/test.arpa?????? util/file_piece.cc.gz
diff --git a/lm/compile.sh b/lm/compile.sh
deleted file mode 100755
index a9283c892..000000000
--- a/lm/compile.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-#This is just an example compilation. You should integrate these files into your build system. I can provide boost jam if you want.
-#If your code uses ICU, edit util/string_piece.hh and uncomment #define USE_ICU
-#I use zlib by default. If you don't want to depend on zlib, remove #define USE_ZLIB from util/file_piece.hh
-
-#don't need to use if compiling with moses Makefiles already
-
-cd "$(dirname "$0")/.."
-
-set -e
-
-for i in util/{bit_packing,ersatz_progress,exception,file_piece,murmur_hash,file,mmap} lm/{bhiksha,binary_format,config,lm_exception,model,quantize,read_arpa,search_hashed,search_trie,trie,trie_sort,virtual_interface,vocab}; do
- g++ -I. -O3 -DNDEBUG $CXXFLAGS -c $i.cc -o $i.o
-done
-g++ -I. -O3 -DNDEBUG $CXXFLAGS lm/build_binary.cc {lm,util}/*.o -lz -o lm/build_binary
-g++ -I. -O3 -DNDEBUG $CXXFLAGS lm/ngram_query.cc {lm,util}/*.o -lz -o lm/query
diff --git a/lm/fragment.cc b/lm/fragment.cc
new file mode 100644
index 000000000..0267cd4eb
--- /dev/null
+++ b/lm/fragment.cc
@@ -0,0 +1,37 @@
+#include "lm/binary_format.hh"
+#include "lm/model.hh"
+#include "lm/left.hh"
+#include "util/tokenize_piece.hh"
+
+template <class Model> void Query(const char *name) {
+ Model model(name);
+ std::string line;
+ lm::ngram::ChartState ignored;
+ while (getline(std::cin, line)) {
+ lm::ngram::RuleScore<Model> scorer(model, ignored);
+ for (util::TokenIter<util::SingleCharacter, true> i(line, ' '); i; ++i) {
+ scorer.Terminal(model.GetVocabulary().Index(*i));
+ }
+ std::cout << scorer.Finish() << '\n';
+ }
+}
+
+int main(int argc, char *argv[]) {
+ if (argc != 2) {
+ std::cerr << "Expected model file name." << std::endl;
+ return 1;
+ }
+ const char *name = argv[1];
+ lm::ngram::ModelType model_type = lm::ngram::PROBING;
+ lm::ngram::RecognizeBinary(name, model_type);
+ switch (model_type) {
+ case lm::ngram::PROBING:
+ Query<lm::ngram::ProbingModel>(name);
+ break;
+ case lm::ngram::REST_PROBING:
+ Query<lm::ngram::RestProbingModel>(name);
+ break;
+ default:
+ std::cerr << "Model type not supported yet." << std::endl;
+ }
+}
diff --git a/lm/max_order.hh b/lm/max_order.hh
index e89f36a18..989f83247 100644
--- a/lm/max_order.hh
+++ b/lm/max_order.hh
@@ -8,5 +8,5 @@
#define KENLM_MAX_ORDER 6
#endif
#ifndef KENLM_ORDER_MESSAGE
-#define KENLM_ORDER_MESSAGE "Recompile with e.g. `bjam --kenlm-max-order=6 -a' to change the maximum order."
+#define KENLM_ORDER_MESSAGE "If your build system supports changing KENLM_MAX_ORDER, change it there and recompile. In the KenLM tarball or Moses, use e.g. `bjam --kenlm-max-order=6 -a'. Otherwise, edit lm/max_order.hh."
#endif
diff --git a/lm/partial.hh b/lm/partial.hh
new file mode 100644
index 000000000..1dede359a
--- /dev/null
+++ b/lm/partial.hh
@@ -0,0 +1,167 @@
+#ifndef LM_PARTIAL__
+#define LM_PARTIAL__
+
+#include "lm/return.hh"
+#include "lm/state.hh"
+
+#include <algorithm>
+
+#include <assert.h>
+
+namespace lm {
+namespace ngram {
+
+struct ExtendReturn {
+ float adjust;
+ bool make_full;
+ unsigned char next_use;
+};
+
+template <class Model> ExtendReturn ExtendLoop(
+ const Model &model,
+ unsigned char seen, const WordIndex *add_rbegin, const WordIndex *add_rend, const float *backoff_start,
+ const uint64_t *pointers, const uint64_t *pointers_end,
+ uint64_t *&pointers_write,
+ float *backoff_write) {
+ unsigned char add_length = add_rend - add_rbegin;
+
+ float backoff_buf[2][KENLM_MAX_ORDER - 1];
+ float *backoff_in = backoff_buf[0], *backoff_out = backoff_buf[1];
+ std::copy(backoff_start, backoff_start + add_length, backoff_in);
+
+ ExtendReturn value;
+ value.make_full = false;
+ value.adjust = 0.0;
+ value.next_use = add_length;
+
+ unsigned char i = 0;
+ unsigned char length = pointers_end - pointers;
+ // pointers_write is NULL means that the existing left state is full, so we should use completed probabilities.
+ if (pointers_write) {
+ // Using full context, writing to new left state.
+ for (; i < length; ++i) {
+ FullScoreReturn ret(model.ExtendLeft(
+ add_rbegin, add_rbegin + value.next_use,
+ backoff_in,
+ pointers[i], i + seen + 1,
+ backoff_out,
+ value.next_use));
+ std::swap(backoff_in, backoff_out);
+ if (ret.independent_left) {
+ value.adjust += ret.prob;
+ value.make_full = true;
+ ++i;
+ break;
+ }
+ value.adjust += ret.rest;
+ *pointers_write++ = ret.extend_left;
+ if (value.next_use != add_length) {
+ value.make_full = true;
+ ++i;
+ break;
+ }
+ }
+ }
+ // Using some of the new context.
+ for (; i < length && value.next_use; ++i) {
+ FullScoreReturn ret(model.ExtendLeft(
+ add_rbegin, add_rbegin + value.next_use,
+ backoff_in,
+ pointers[i], i + seen + 1,
+ backoff_out,
+ value.next_use));
+ std::swap(backoff_in, backoff_out);
+ value.adjust += ret.prob;
+ }
+ float unrest = model.UnRest(pointers + i, pointers_end, i + seen + 1);
+ // Using none of the new context.
+ value.adjust += unrest;
+
+ std::copy(backoff_in, backoff_in + value.next_use, backoff_write);
+ return value;
+}
+
+template <class Model> float RevealBefore(const Model &model, const Right &reveal, const unsigned char seen, bool reveal_full, Left &left, Right &right) {
+ assert(seen < reveal.length || reveal_full);
+ uint64_t *pointers_write = reveal_full ? NULL : left.pointers;
+ float backoff_buffer[KENLM_MAX_ORDER - 1];
+ ExtendReturn value(ExtendLoop(
+ model,
+ seen, reveal.words + seen, reveal.words + reveal.length, reveal.backoff + seen,
+ left.pointers, left.pointers + left.length,
+ pointers_write,
+ left.full ? backoff_buffer : (right.backoff + right.length)));
+ if (reveal_full) {
+ left.length = 0;
+ value.make_full = true;
+ } else {
+ left.length = pointers_write - left.pointers;
+ value.make_full |= (left.length == model.Order() - 1);
+ }
+ if (left.full) {
+ for (unsigned char i = 0; i < value.next_use; ++i) value.adjust += backoff_buffer[i];
+ } else {
+ // If left wasn't full when it came in, put words into right state.
+ std::copy(reveal.words + seen, reveal.words + seen + value.next_use, right.words + right.length);
+ right.length += value.next_use;
+ left.full = value.make_full || (right.length == model.Order() - 1);
+ }
+ return value.adjust;
+}
+
+template <class Model> float RevealAfter(const Model &model, Left &left, Right &right, const Left &reveal, unsigned char seen) {
+ assert(seen < reveal.length || reveal.full);
+ uint64_t *pointers_write = left.full ? NULL : (left.pointers + left.length);
+ ExtendReturn value(ExtendLoop(
+ model,
+ seen, right.words, right.words + right.length, right.backoff,
+ reveal.pointers + seen, reveal.pointers + reveal.length,
+ pointers_write,
+ right.backoff));
+ if (reveal.full) {
+ for (unsigned char i = 0; i < value.next_use; ++i) value.adjust += right.backoff[i];
+ right.length = 0;
+ value.make_full = true;
+ } else {
+ right.length = value.next_use;
+ value.make_full |= (right.length == model.Order() - 1);
+ }
+ if (!left.full) {
+ left.length = pointers_write - left.pointers;
+ left.full = value.make_full || (left.length == model.Order() - 1);
+ }
+ return value.adjust;
+}
+
+template <class Model> float Subsume(const Model &model, Left &first_left, const Right &first_right, const Left &second_left, Right &second_right, const unsigned int between_length) {
+ assert(first_right.length < KENLM_MAX_ORDER);
+ assert(second_left.length < KENLM_MAX_ORDER);
+ assert(between_length < KENLM_MAX_ORDER - 1);
+ uint64_t *pointers_write = first_left.full ? NULL : (first_left.pointers + first_left.length);
+ float backoff_buffer[KENLM_MAX_ORDER - 1];
+ ExtendReturn value(ExtendLoop(
+ model,
+ between_length, first_right.words, first_right.words + first_right.length, first_right.backoff,
+ second_left.pointers, second_left.pointers + second_left.length,
+ pointers_write,
+ second_left.full ? backoff_buffer : (second_right.backoff + second_right.length)));
+ if (second_left.full) {
+ for (unsigned char i = 0; i < value.next_use; ++i) value.adjust += backoff_buffer[i];
+ } else {
+ std::copy(first_right.words, first_right.words + value.next_use, second_right.words + second_right.length);
+ second_right.length += value.next_use;
+ value.make_full |= (second_right.length == model.Order() - 1);
+ }
+ if (!first_left.full) {
+ first_left.length = pointers_write - first_left.pointers;
+ first_left.full = value.make_full || second_left.full || (first_left.length == model.Order() - 1);
+ }
+ assert(first_left.length < KENLM_MAX_ORDER);
+ assert(second_right.length < KENLM_MAX_ORDER);
+ return value.adjust;
+}
+
+} // namespace ngram
+} // namespace lm
+
+#endif // LM_PARTIAL__
diff --git a/lm/partial_test.cc b/lm/partial_test.cc
new file mode 100644
index 000000000..8d309c85a
--- /dev/null
+++ b/lm/partial_test.cc
@@ -0,0 +1,199 @@
+#include "lm/partial.hh"
+
+#include "lm/left.hh"
+#include "lm/model.hh"
+#include "util/tokenize_piece.hh"
+
+#define BOOST_TEST_MODULE PartialTest
+#include <boost/test/unit_test.hpp>
+#include <boost/test/floating_point_comparison.hpp>
+
+namespace lm {
+namespace ngram {
+namespace {
+
+const char *TestLocation() {
+ if (boost::unit_test::framework::master_test_suite().argc < 2) {
+ return "test.arpa";
+ }
+ return boost::unit_test::framework::master_test_suite().argv[1];
+}
+
+Config SilentConfig() {
+ Config config;
+ config.arpa_complain = Config::NONE;
+ config.messages = NULL;
+ return config;
+}
+
+struct ModelFixture {
+ ModelFixture() : m(TestLocation(), SilentConfig()) {}
+
+ RestProbingModel m;
+};
+
+BOOST_FIXTURE_TEST_SUITE(suite, ModelFixture)
+
+BOOST_AUTO_TEST_CASE(SimpleBefore) {
+ Left left;
+ left.full = false;
+ left.length = 0;
+ Right right;
+ right.length = 0;
+
+ Right reveal;
+ reveal.length = 1;
+ WordIndex period = m.GetVocabulary().Index(".");
+ reveal.words[0] = period;
+ reveal.backoff[0] = -0.845098;
+
+ BOOST_CHECK_CLOSE(0.0, RevealBefore(m, reveal, 0, false, left, right), 0.001);
+ BOOST_CHECK_EQUAL(0, left.length);
+ BOOST_CHECK(!left.full);
+ BOOST_CHECK_EQUAL(1, right.length);
+ BOOST_CHECK_EQUAL(period, right.words[0]);
+ BOOST_CHECK_CLOSE(-0.845098, right.backoff[0], 0.001);
+
+ WordIndex more = m.GetVocabulary().Index("more");
+ reveal.words[1] = more;
+ reveal.backoff[1] = -0.4771212;
+ reveal.length = 2;
+ BOOST_CHECK_CLOSE(0.0, RevealBefore(m, reveal, 1, false, left, right), 0.001);
+ BOOST_CHECK_EQUAL(0, left.length);
+ BOOST_CHECK(!left.full);
+ BOOST_CHECK_EQUAL(2, right.length);
+ BOOST_CHECK_EQUAL(period, right.words[0]);
+ BOOST_CHECK_EQUAL(more, right.words[1]);
+ BOOST_CHECK_CLOSE(-0.845098, right.backoff[0], 0.001);
+ BOOST_CHECK_CLOSE(-0.4771212, right.backoff[1], 0.001);
+}
+
+BOOST_AUTO_TEST_CASE(AlsoWouldConsider) {
+ WordIndex would = m.GetVocabulary().Index("would");
+ WordIndex consider = m.GetVocabulary().Index("consider");
+
+ ChartState current;
+ current.left.length = 1;
+ current.left.pointers[0] = would;
+ current.left.full = false;
+ current.right.length = 1;
+ current.right.words[0] = would;
+ current.right.backoff[0] = -0.30103;
+
+ Left after;
+ after.full = false;
+ after.length = 1;
+ after.pointers[0] = consider;
+
+ // adjustment for would consider
+ BOOST_CHECK_CLOSE(-1.687872 - -0.2922095 - 0.30103, RevealAfter(m, current.left, current.right, after, 0), 0.001);
+
+ BOOST_CHECK_EQUAL(2, current.left.length);
+ BOOST_CHECK_EQUAL(would, current.left.pointers[0]);
+ BOOST_CHECK_EQUAL(false, current.left.full);
+
+ WordIndex also = m.GetVocabulary().Index("also");
+ Right before;
+ before.length = 1;
+ before.words[0] = also;
+ before.backoff[0] = -0.30103;
+ // r(would) = -0.2922095 [i would], r(would -> consider) = -1.988902 [b(would) + p(consider)]
+ // p(also -> would) = -2, p(also would -> consider) = -3
+ BOOST_CHECK_CLOSE(-2 + 0.2922095 -3 + 1.988902, RevealBefore(m, before, 0, false, current.left, current.right), 0.001);
+ BOOST_CHECK_EQUAL(0, current.left.length);
+ BOOST_CHECK(current.left.full);
+ BOOST_CHECK_EQUAL(2, current.right.length);
+ BOOST_CHECK_EQUAL(would, current.right.words[0]);
+ BOOST_CHECK_EQUAL(also, current.right.words[1]);
+}
+
+BOOST_AUTO_TEST_CASE(EndSentence) {
+ WordIndex loin = m.GetVocabulary().Index("loin");
+ WordIndex period = m.GetVocabulary().Index(".");
+ WordIndex eos = m.GetVocabulary().EndSentence();
+
+ ChartState between;
+ between.left.length = 1;
+ between.left.pointers[0] = eos;
+ between.left.full = true;
+ between.right.length = 0;
+
+ Right before;
+ before.words[0] = period;
+ before.words[1] = loin;
+ before.backoff[0] = -0.845098;
+ before.backoff[1] = 0.0;
+
+ before.length = 1;
+ BOOST_CHECK_CLOSE(-0.0410707, RevealBefore(m, before, 0, true, between.left, between.right), 0.001);
+ BOOST_CHECK_EQUAL(0, between.left.length);
+}
+
+float ScoreFragment(const RestProbingModel &model, unsigned int *begin, unsigned int *end, ChartState &out) {
+ RuleScore<RestProbingModel> scorer(model, out);
+ for (unsigned int *i = begin; i < end; ++i) {
+ scorer.Terminal(*i);
+ }
+ return scorer.Finish();
+}
+
+void CheckAdjustment(const RestProbingModel &model, float expect, const Right &before_in, bool before_full, ChartState between, const Left &after_in) {
+ Right before(before_in);
+ Left after(after_in);
+ after.full = false;
+ float got = 0.0;
+ for (unsigned int i = 1; i < 5; ++i) {
+ if (before_in.length >= i) {
+ before.length = i;
+ got += RevealBefore(model, before, i - 1, false, between.left, between.right);
+ }
+ if (after_in.length >= i) {
+ after.length = i;
+ got += RevealAfter(model, between.left, between.right, after, i - 1);
+ }
+ }
+ if (after_in.full) {
+ after.full = true;
+ got += RevealAfter(model, between.left, between.right, after, after.length);
+ }
+ if (before_full) {
+ got += RevealBefore(model, before, before.length, true, between.left, between.right);
+ }
+ // Sometimes they're zero and BOOST_CHECK_CLOSE fails for this.
+ BOOST_CHECK(fabs(expect - got) < 0.001);
+}
+
+void FullDivide(const RestProbingModel &model, StringPiece str) {
+ std::vector<WordIndex> indices;
+ for (util::TokenIter<util::SingleCharacter, true> i(str, ' '); i; ++i) {
+ indices.push_back(model.GetVocabulary().Index(*i));
+ }
+ ChartState full_state;
+ float full = ScoreFragment(model, &indices.front(), &indices.back() + 1, full_state);
+
+ ChartState before_state;
+ before_state.left.full = false;
+ RuleScore<RestProbingModel> before_scorer(model, before_state);
+ float before_score = 0.0;
+ for (unsigned int before = 0; before < indices.size(); ++before) {
+ for (unsigned int after = before; after <= indices.size(); ++after) {
+ ChartState after_state, between_state;
+ float after_score = ScoreFragment(model, &indices.front() + after, &indices.front() + indices.size(), after_state);
+ float between_score = ScoreFragment(model, &indices.front() + before, &indices.front() + after, between_state);
+ CheckAdjustment(model, full - before_score - after_score - between_score, before_state.right, before_state.left.full, between_state, after_state.left);
+ }
+ before_scorer.Terminal(indices[before]);
+ before_score = before_scorer.Finish();
+ }
+}
+
+BOOST_AUTO_TEST_CASE(Strings) {
+ FullDivide(m, "also would consider");
+ FullDivide(m, "looking on a little more loin . </s>");
+ FullDivide(m, "in biarritz watching considering looking . on a little more loin also would consider higher to look good unknown the screening foo bar , unknown however unknown </s>");
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+} // namespace
+} // namespace ngram
+} // namespace lm
diff --git a/lm/state.hh b/lm/state.hh
index 830e40aa2..551510a8e 100644
--- a/lm/state.hh
+++ b/lm/state.hh
@@ -47,6 +47,8 @@ class State {
unsigned char length;
};
+typedef State Right;
+
inline uint64_t hash_value(const State &state, uint64_t seed = 0) {
return util::MurmurHashNative(state.words, sizeof(WordIndex) * state.length, seed);
}
diff --git a/lm/test.sh b/lm/test.sh
deleted file mode 100755
index 48e415bfd..000000000
--- a/lm/test.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-#Run tests. Requires Boost.
-cd "$(dirname "$0")/.."
-
-set -e
-lm/compile.sh
-for i in util/{bit_packing,file_piece,joint_sort,key_value_packing,probing_hash_table,sorted_uniform,tokenize_piece}_test lm/{model,left}_test; do
- g++ -I. -O3 $CXXFLAGS $i.cc {lm,util}/*.o -lboost_test_exec_monitor -lz -o $i
- pushd $(dirname $i) >/dev/null && ./$(basename $i) || echo "$i failed"; popd >/dev/null
-done
diff --git a/lm/word_index.hh b/lm/word_index.hh
index 67841c30a..e09557a7c 100644
--- a/lm/word_index.hh
+++ b/lm/word_index.hh
@@ -2,8 +2,11 @@
#ifndef LM_WORD_INDEX__
#define LM_WORD_INDEX__
+#include <limits.h>
+
namespace lm {
typedef unsigned int WordIndex;
+const WordIndex kMaxWordIndex = UINT_MAX;
} // namespace lm
typedef lm::WordIndex LMWordIndex;
diff --git a/moses-chart-cmd/src/IOWrapper.h b/moses-chart-cmd/src/IOWrapper.h
index 1bfc6c45b..fdadd1b1e 100644
--- a/moses-chart-cmd/src/IOWrapper.h
+++ b/moses-chart-cmd/src/IOWrapper.h
@@ -92,6 +92,8 @@ public:
void OutputDetailedTranslationReport(const Moses::ChartHypothesis *hypo, const Moses::Sentence &sentence, long translationId);
void Backtrack(const Moses::ChartHypothesis *hypo);
+ Moses::OutputCollector *ExposeSingleBest() { return m_singleBestOutputCollector; }
+
void ResetTranslationId();
Moses::OutputCollector *GetSearchGraphOutputCollector() {
diff --git a/moses-chart-cmd/src/Main.cpp b/moses-chart-cmd/src/Main.cpp
index 9b4a59866..03974595b 100644
--- a/moses-chart-cmd/src/Main.cpp
+++ b/moses-chart-cmd/src/Main.cpp
@@ -57,6 +57,7 @@ POSSIBILITY OF SUCH DAMAGE.
#include "ChartHypothesis.h"
#include "ChartTrellisPath.h"
#include "ChartTrellisPathList.h"
+#include "Incremental/Manager.h"
#include "util/usage.hh"
@@ -87,6 +88,16 @@ public:
VERBOSE(2,"\nTRANSLATING(" << lineNumber << "): " << *m_source);
if ((*m_source).GetSize() == 0) return;
+
+ if (staticData.GetSearchAlgorithm() == ChartIncremental) {
+ Incremental::Manager manager(*m_source, system);
+ manager.ProcessSentence();
+ if (m_ioWrapper.ExposeSingleBest()) {
+ m_ioWrapper.ExposeSingleBest()->Write(lineNumber, manager.String() + '\n');
+ }
+ return;
+ }
+
ChartManager manager(*m_source, &system);
manager.ProcessSentence();
@@ -224,9 +235,9 @@ int main(int argc, char* argv[])
ShowWeights();
exit(0);
}
-
- CHECK(staticData.GetSearchAlgorithm() == ChartDecoding);
-
+
+ CHECK(staticData.IsChart());
+
// set up read/writing class
IOWrapper *ioWrapper = GetIOWrapper(staticData);
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.cpp b/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.cpp
index b3cbfda5b..2ae24aebb 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.cpp
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.cpp
@@ -21,7 +21,7 @@
#include "RuleTable/PhraseDictionarySCFG.h"
#include "InputType.h"
-#include "ChartTranslationOptionList.h"
+#include "ChartParserCallback.h"
#include "DotChartInMemory.h"
#include "StaticData.h"
#include "NonTerminal.h"
@@ -34,7 +34,7 @@ void ChartRuleLookupManagerCYKPlus::AddCompletedRule(
const DottedRule &dottedRule,
const TargetPhraseCollection &tpc,
const WordsRange &range,
- ChartTranslationOptionList &outColl)
+ ChartParserCallback &outColl)
{
// Determine the rule's rank.
size_t rank = 0;
@@ -51,10 +51,7 @@ void ChartRuleLookupManagerCYKPlus::AddCompletedRule(
node = &dottedRule;
while (rank > 0) {
if (node->IsNonTerminal()) {
- const ChartCellLabel &cellLabel = node->GetChartCellLabel();
- const HypoList *stack = cellLabel.GetStack();
- assert(stack);
- m_stackVec[--rank] = stack;
+ m_stackVec[--rank] = &node->GetChartCellLabel();
}
node = node->GetPrev();
}
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.h b/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.h
index 5af2c4b63..78b1f4138 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.h
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerCYKPlus.h
@@ -37,7 +37,7 @@ class ChartRuleLookupManagerCYKPlus : public ChartRuleLookupManager
{
public:
ChartRuleLookupManagerCYKPlus(const InputType &sentence,
- const ChartCellCollection &cellColl)
+ const ChartCellCollectionBase &cellColl)
: ChartRuleLookupManager(sentence, cellColl) {}
protected:
@@ -45,7 +45,7 @@ class ChartRuleLookupManagerCYKPlus : public ChartRuleLookupManager
const DottedRule &dottedRule,
const TargetPhraseCollection &tpc,
const WordsRange &range,
- ChartTranslationOptionList &outColl);
+ ChartParserCallback &outColl);
StackVec m_stackVec;
};
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.cpp b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.cpp
index 57ab61b29..21e51e8d2 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.cpp
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.cpp
@@ -21,7 +21,7 @@
#include "RuleTable/PhraseDictionarySCFG.h"
#include "InputType.h"
-#include "ChartTranslationOptionList.h"
+#include "ChartParserCallback.h"
#include "DotChartInMemory.h"
#include "StaticData.h"
#include "NonTerminal.h"
@@ -32,7 +32,7 @@ namespace Moses
ChartRuleLookupManagerMemory::ChartRuleLookupManagerMemory(
const InputType &src,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionarySCFG &ruleTable)
: ChartRuleLookupManagerCYKPlus(src, cellColl)
, m_ruleTable(ruleTable)
@@ -65,7 +65,7 @@ ChartRuleLookupManagerMemory::~ChartRuleLookupManagerMemory()
void ChartRuleLookupManagerMemory::GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl)
+ ChartParserCallback &outColl)
{
size_t relEndPos = range.GetEndPos() - range.GetStartPos();
size_t absEndPos = range.GetEndPos();
@@ -76,7 +76,7 @@ void ChartRuleLookupManagerMemory::GetChartRuleCollection(
DottedRuleColl &dottedRuleCol = *m_dottedRuleColls[range.GetStartPos()];
const DottedRuleList &expandableDottedRuleList = dottedRuleCol.GetExpandableDottedRuleList();
- const ChartCellLabel &sourceWordLabel = GetCellCollection().Get(WordsRange(absEndPos, absEndPos)).GetSourceWordLabel();
+ const ChartCellLabel &sourceWordLabel = GetSourceAt(absEndPos);
// loop through the rules
// (note that expandableDottedRuleList can be expanded as the loop runs
@@ -183,8 +183,7 @@ void ChartRuleLookupManagerMemory::ExtendPartialRuleApplication(
GetSentence().GetLabelSet(startPos, endPos);
// target non-terminal labels for the remainder
- const ChartCellLabelSet &targetNonTerms =
- GetCellCollection().Get(WordsRange(startPos, endPos)).GetTargetLabelSet();
+ const ChartCellLabelSet &targetNonTerms = GetTargetLabelSet(startPos, endPos);
// note where it was found in the prefix tree of the rule dictionary
const PhraseDictionaryNodeSCFG &node = prevDottedRule.GetLastNode();
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.h b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.h
index 38f06d63e..247ed1e10 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.h
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemory.h
@@ -37,7 +37,7 @@
namespace Moses
{
-class ChartTranslationOptionList;
+class ChartParserCallback;
class DottedRuleColl;
class WordsRange;
@@ -46,14 +46,14 @@ class ChartRuleLookupManagerMemory : public ChartRuleLookupManagerCYKPlus
{
public:
ChartRuleLookupManagerMemory(const InputType &sentence,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionarySCFG &ruleTable);
~ChartRuleLookupManagerMemory();
virtual void GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl);
+ ChartParserCallback &outColl);
private:
void ExtendPartialRuleApplication(
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.cpp b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.cpp
index ca2e1d395..d8270f699 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.cpp
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.cpp
@@ -21,7 +21,7 @@
#include "RuleTable/PhraseDictionaryFuzzyMatch.h"
#include "InputType.h"
-#include "ChartTranslationOptionList.h"
+#include "ChartParserCallback.h"
#include "DotChartInMemory.h"
#include "StaticData.h"
#include "NonTerminal.h"
@@ -32,7 +32,7 @@ namespace Moses
ChartRuleLookupManagerMemoryPerSentence::ChartRuleLookupManagerMemoryPerSentence(
const InputType &src,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionaryFuzzyMatch &ruleTable)
: ChartRuleLookupManagerCYKPlus(src, cellColl)
, m_ruleTable(ruleTable)
@@ -65,7 +65,7 @@ ChartRuleLookupManagerMemoryPerSentence::~ChartRuleLookupManagerMemoryPerSentenc
void ChartRuleLookupManagerMemoryPerSentence::GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl)
+ ChartParserCallback &outColl)
{
size_t relEndPos = range.GetEndPos() - range.GetStartPos();
size_t absEndPos = range.GetEndPos();
@@ -76,8 +76,6 @@ void ChartRuleLookupManagerMemoryPerSentence::GetChartRuleCollection(
DottedRuleColl &dottedRuleCol = *m_dottedRuleColls[range.GetStartPos()];
const DottedRuleList &expandableDottedRuleList = dottedRuleCol.GetExpandableDottedRuleList();
- const ChartCellLabel &sourceWordLabel = GetCellCollection().Get(WordsRange(absEndPos, absEndPos)).GetSourceWordLabel();
-
// loop through the rules
// (note that expandableDottedRuleList can be expanded as the loop runs
// through calls to ExtendPartialRuleApplication())
@@ -95,6 +93,7 @@ void ChartRuleLookupManagerMemoryPerSentence::GetChartRuleCollection(
// look up in rule dictionary, if the current rule can be extended
// with the source word in the last position
+ const ChartCellLabel &sourceWordLabel = GetSourceAt(absEndPos);
const Word &sourceWord = sourceWordLabel.GetLabel();
const PhraseDictionaryNodeSCFG *node = prevDottedRule.GetLastNode().GetChild(sourceWord);
@@ -183,8 +182,7 @@ void ChartRuleLookupManagerMemoryPerSentence::ExtendPartialRuleApplication(
GetSentence().GetLabelSet(startPos, endPos);
// target non-terminal labels for the remainder
- const ChartCellLabelSet &targetNonTerms =
- GetCellCollection().Get(WordsRange(startPos, endPos)).GetTargetLabelSet();
+ const ChartCellLabelSet &targetNonTerms = GetTargetLabelSet(startPos, endPos);
// note where it was found in the prefix tree of the rule dictionary
const PhraseDictionaryNodeSCFG &node = prevDottedRule.GetLastNode();
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.h b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.h
index f2cf805c4..70126ff49 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.h
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerMemoryPerSentence.h
@@ -37,7 +37,7 @@
namespace Moses
{
-class ChartTranslationOptionList;
+class ChartParserCallback;
class DottedRuleColl;
class WordsRange;
@@ -46,14 +46,14 @@ class ChartRuleLookupManagerMemoryPerSentence : public ChartRuleLookupManagerCYK
{
public:
ChartRuleLookupManagerMemoryPerSentence(const InputType &sentence,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionaryFuzzyMatch &ruleTable);
~ChartRuleLookupManagerMemoryPerSentence();
virtual void GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl);
+ ChartParserCallback &outColl);
private:
void ExtendPartialRuleApplication(
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.cpp b/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.cpp
index 80e508176..da87e91b2 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.cpp
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.cpp
@@ -24,7 +24,7 @@
#include "RuleTable/PhraseDictionaryOnDisk.h"
#include "StaticData.h"
#include "DotChartOnDisk.h"
-#include "ChartTranslationOptionList.h"
+#include "ChartParserCallback.h"
#include "../../OnDiskPt/TargetPhraseCollection.h"
using namespace std;
@@ -34,7 +34,7 @@ namespace Moses
ChartRuleLookupManagerOnDisk::ChartRuleLookupManagerOnDisk(
const InputType &sentence,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionaryOnDisk &dictionary,
OnDiskPt::OnDiskWrapper &dbWrapper,
const LMList *languageModels,
@@ -79,7 +79,7 @@ ChartRuleLookupManagerOnDisk::~ChartRuleLookupManagerOnDisk()
void ChartRuleLookupManagerOnDisk::GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl)
+ ChartParserCallback &outColl)
{
const StaticData &staticData = StaticData::Instance();
size_t relEndPos = range.GetEndPos() - range.GetStartPos();
@@ -94,7 +94,7 @@ void ChartRuleLookupManagerOnDisk::GetChartRuleCollection(
const DottedRuleStackOnDisk::SavedNodeColl &savedNodeColl = expandableDottedRuleList.GetSavedNodeColl();
//cerr << "savedNodeColl=" << savedNodeColl.size() << " ";
- const ChartCellLabel &sourceWordLabel = GetCellCollection().Get(WordsRange(absEndPos, absEndPos)).GetSourceWordLabel();
+ const ChartCellLabel &sourceWordLabel = GetSourceAt(absEndPos);
for (size_t ind = 0; ind < (savedNodeColl.size()) ; ++ind) {
const SavedNodeOnDisk &savedNode = *savedNodeColl[ind];
@@ -141,7 +141,7 @@ void ChartRuleLookupManagerOnDisk::GetChartRuleCollection(
// get target nonterminals in this span from chart
const ChartCellLabelSet &chartNonTermSet =
- GetCellCollection().Get(WordsRange(startPos, endPos)).GetTargetLabelSet();
+ GetTargetLabelSet(startPos, endPos);
//const Word &defaultSourceNonTerm = staticData.GetInputDefaultNonTerminal()
// ,&defaultTargetNonTerm = staticData.GetOutputDefaultNonTerminal();
diff --git a/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.h b/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.h
index 333d975cc..e49b413fe 100644
--- a/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.h
+++ b/moses/src/CYKPlusParser/ChartRuleLookupManagerOnDisk.h
@@ -24,7 +24,7 @@
#include "../../../OnDiskPt/OnDiskWrapper.h"
#include "ChartRuleLookupManagerCYKPlus.h"
-#include "ChartTranslationOptionList.h"
+#include "ChartParserCallback.h"
#include "DotChartOnDisk.h"
#include "InputType.h"
#include "RuleTable/PhraseDictionaryOnDisk.h"
@@ -37,7 +37,7 @@ class ChartRuleLookupManagerOnDisk : public ChartRuleLookupManagerCYKPlus
{
public:
ChartRuleLookupManagerOnDisk(const InputType &sentence,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const PhraseDictionaryOnDisk &dictionary,
OnDiskPt::OnDiskWrapper &dbWrapper,
const LMList *languageModels,
@@ -49,7 +49,7 @@ class ChartRuleLookupManagerOnDisk : public ChartRuleLookupManagerCYKPlus
~ChartRuleLookupManagerOnDisk();
virtual void GetChartRuleCollection(const WordsRange &range,
- ChartTranslationOptionList &outColl);
+ ChartParserCallback &outColl);
private:
const PhraseDictionaryOnDisk &m_dictionary;
diff --git a/moses/src/ChartCell.cpp b/moses/src/ChartCell.cpp
index 04b629cd9..df2770533 100644
--- a/moses/src/ChartCell.cpp
+++ b/moses/src/ChartCell.cpp
@@ -37,28 +37,23 @@ namespace Moses
{
extern bool g_debug;
+ChartCellBase::ChartCellBase(size_t startPos, size_t endPos) :
+ m_coverage(startPos, endPos),
+ m_targetLabelSet(m_coverage) {}
+
+ChartCellBase::~ChartCellBase() {}
+
/** Constructor
* \param startPos endPos range of this cell
* \param manager pointer back to the manager
*/
-ChartCell::ChartCell(size_t startPos, size_t endPos, ChartManager &manager)
- :m_coverage(startPos, endPos)
- ,m_sourceWordLabel(NULL)
- ,m_targetLabelSet(m_coverage)
- ,m_manager(manager)
-{
+ChartCell::ChartCell(size_t startPos, size_t endPos, ChartManager &manager) :
+ ChartCellBase(startPos, endPos), m_manager(manager) {
const StaticData &staticData = StaticData::Instance();
m_nBestIsEnabled = staticData.IsNBestEnabled();
- if (startPos == endPos) {
- const Word &sourceWord = manager.GetSource().GetWord(startPos);
- m_sourceWordLabel = new ChartCellLabel(m_coverage, sourceWord);
- }
}
-ChartCell::~ChartCell()
-{
- delete m_sourceWordLabel;
-}
+ChartCell::~ChartCell() {}
/** Add the given hypothesis to the cell.
* Returns true if added, false if not. Maybe it already exists in the collection or score falls below threshold etc.
@@ -117,8 +112,8 @@ void ChartCell::SortHypotheses()
MapType::iterator iter;
for (iter = m_hypoColl.begin(); iter != m_hypoColl.end(); ++iter) {
ChartHypothesisCollection &coll = iter->second;
- m_targetLabelSet.AddConstituent(iter->first, coll);
coll.SortHypotheses();
+ m_targetLabelSet.AddConstituent(iter->first, &coll.GetSortedHypotheses());
}
}
diff --git a/moses/src/ChartCell.h b/moses/src/ChartCell.h
index dd0fc25d3..e57aa4f55 100644
--- a/moses/src/ChartCell.h
+++ b/moses/src/ChartCell.h
@@ -33,6 +33,7 @@
#include "RuleCube.h"
#include "ChartCellLabelSet.h"
+#include <boost/scoped_ptr.hpp>
#include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <boost/version.hpp>
@@ -43,11 +44,27 @@ class ChartTranslationOptionList;
class ChartCellCollection;
class ChartManager;
+class ChartCellBase {
+ public:
+ ChartCellBase(size_t startPos, size_t endPos);
+
+ virtual ~ChartCellBase();
+
+ const ChartCellLabelSet &GetTargetLabelSet() const { return m_targetLabelSet; }
+
+ ChartCellLabelSet &MutableTargetLabelSet() { return m_targetLabelSet; }
+
+ const WordsRange &GetCoverage() const { return m_coverage; }
+
+ protected:
+ const WordsRange m_coverage;
+ ChartCellLabelSet m_targetLabelSet;
+};
+
/** 1 cell in chart decoder.
* Doesn't directly hold hypotheses. Each cell contain a map of ChartHypothesisCollection that have different constituent labels
*/
-class ChartCell
-{
+class ChartCell : public ChartCellBase {
friend std::ostream& operator<<(std::ostream&, const ChartCell&);
public:
#if defined(BOOST_VERSION) && (BOOST_VERSION >= 104200)
@@ -63,11 +80,6 @@ public:
protected:
MapType m_hypoColl;
- WordsRange m_coverage;
-
- ChartCellLabel *m_sourceWordLabel;
- ChartCellLabelSet m_targetLabelSet;
-
bool m_nBestIsEnabled; /**< flag to determine whether to keep track of old arcs */
ChartManager &m_manager;
@@ -92,17 +104,6 @@ public:
const ChartHypothesis *GetBestHypothesis() const;
- //! @todo what is a m_sourceWordLabel?
- const ChartCellLabel &GetSourceWordLabel() const {
- CHECK(m_coverage.GetNumWordsCovered() == 1);
- return *m_sourceWordLabel;
- }
-
- //! @todo what is a m_sourceWordLabel?
- const ChartCellLabelSet &GetTargetLabelSet() const {
- return m_targetLabelSet;
- }
-
void CleanupArcList();
void OutputSizes(std::ostream &out) const;
diff --git a/moses/src/ChartCellCollection.cpp b/moses/src/ChartCellCollection.cpp
index 59e2ff82e..a34687f59 100644
--- a/moses/src/ChartCellCollection.cpp
+++ b/moses/src/ChartCellCollection.cpp
@@ -23,37 +23,32 @@
#include "InputType.h"
#include "WordsRange.h"
-namespace Moses
-{
+namespace Moses {
+
+ChartCellCollectionBase::~ChartCellCollectionBase() {
+ m_source.clear();
+ for (std::vector<std::vector<ChartCellBase*> >::iterator i = m_cells.begin(); i != m_cells.end(); ++i)
+ RemoveAllInColl(*i);
+}
+
+class CubeCellFactory {
+ public:
+ explicit CubeCellFactory(ChartManager &manager) : m_manager(manager) {}
+
+ ChartCell *operator()(size_t start, size_t end) const {
+ return new ChartCell(start, end, m_manager);
+ }
+
+ private:
+ ChartManager &m_manager;
+};
+
/** Costructor
\param input the input sentence
\param manager reference back to the manager
*/
ChartCellCollection::ChartCellCollection(const InputType &input, ChartManager &manager)
- :m_hypoStackColl(input.GetSize())
-{
- size_t size = input.GetSize();
- for (size_t startPos = 0; startPos < size; ++startPos) {
- InnerCollType &inner = m_hypoStackColl[startPos];
- inner.resize(size - startPos);
-
- size_t ind = 0;
- for (size_t endPos = startPos ; endPos < size; ++endPos) {
- ChartCell *cell = new ChartCell(startPos, endPos, manager);
- inner[ind] = cell;
- ++ind;
- }
- }
-}
-
-ChartCellCollection::~ChartCellCollection()
-{
- OuterCollType::iterator iter;
- for (iter = m_hypoStackColl.begin(); iter != m_hypoStackColl.end(); ++iter) {
- InnerCollType &inner = *iter;
- RemoveAllInColl(inner);
- }
-}
+ :ChartCellCollectionBase(input, CubeCellFactory(manager)) {}
} // namespace
diff --git a/moses/src/ChartCellCollection.h b/moses/src/ChartCellCollection.h
index a9d38ceaa..7532503d7 100644
--- a/moses/src/ChartCellCollection.h
+++ b/moses/src/ChartCellCollection.h
@@ -20,37 +20,71 @@
***********************************************************************/
#pragma once
+#include "InputType.h"
#include "ChartCell.h"
#include "WordsRange.h"
+#include <boost/ptr_container/ptr_vector.hpp>
+
namespace Moses
{
class InputType;
class ChartManager;
-/** Hold all the chart cells for 1 input sentence. A variable of this type is held by the ChartManager
- */
-class ChartCellCollection
-{
-public:
- typedef std::vector<ChartCell*> InnerCollType;
- typedef std::vector<InnerCollType> OuterCollType;
+class ChartCellCollectionBase {
+ public:
+ template <class Factory> ChartCellCollectionBase(const InputType &input, const Factory &factory) :
+ m_cells(input.GetSize()) {
+ size_t size = input.GetSize();
+ for (size_t startPos = 0; startPos < size; ++startPos) {
+ std::vector<ChartCellBase*> &inner = m_cells[startPos];
+ inner.reserve(size - startPos);
+ for (size_t endPos = startPos; endPos < size; ++endPos) {
+ inner.push_back(factory(startPos, endPos));
+ }
+ /* Hack: ChartCellLabel shouldn't need to know its span, but the parser
+ * gets it from there :-(. The span is actually stored as a reference,
+ * which needs to point somewhere, so I have it refer to the ChartCell.
+ */
+ m_source.push_back(new ChartCellLabel(inner[0]->GetCoverage(), input.GetWord(startPos)));
+ }
+ }
+
+ virtual ~ChartCellCollectionBase();
+
+ const ChartCellBase &GetBase(const WordsRange &coverage) const {
+ return *m_cells[coverage.GetStartPos()][coverage.GetEndPos() - coverage.GetStartPos()];
+ }
+
+ ChartCellBase &MutableBase(const WordsRange &coverage) {
+ return *m_cells[coverage.GetStartPos()][coverage.GetEndPos() - coverage.GetStartPos()];
+ }
-protected:
- OuterCollType m_hypoStackColl;
-public:
- ChartCellCollection(const InputType &input, ChartManager &manager);
- ~ChartCellCollection();
+ const ChartCellLabel &GetSourceWordLabel(size_t at) const {
+ return m_source[at];
+ }
+
+ private:
+ std::vector<std::vector<ChartCellBase*> > m_cells;
+
+ boost::ptr_vector<ChartCellLabel> m_source;
+};
+
+/** Hold all the chart cells for 1 input sentence. A variable of this type is held by the ChartManager
+ */
+class ChartCellCollection : public ChartCellCollectionBase {
+ public:
+ ChartCellCollection(const InputType &input, ChartManager &manager);
//! get a chart cell for a particular range
ChartCell &Get(const WordsRange &coverage) {
- return *m_hypoStackColl[coverage.GetStartPos()][coverage.GetEndPos() - coverage.GetStartPos()];
+ return static_cast<ChartCell&>(MutableBase(coverage));
}
//! get a chart cell for a particular range
const ChartCell &Get(const WordsRange &coverage) const {
- return *m_hypoStackColl[coverage.GetStartPos()][coverage.GetEndPos() - coverage.GetStartPos()];
+ return static_cast<const ChartCell&>(GetBase(coverage));
}
};
diff --git a/moses/src/ChartCellLabel.h b/moses/src/ChartCellLabel.h
index 3d71230c3..c44462fcc 100644
--- a/moses/src/ChartCellLabel.h
+++ b/moses/src/ChartCellLabel.h
@@ -23,6 +23,8 @@
#include "Word.h"
#include "WordsRange.h"
+namespace search { class Vertex; class VertexGenerator; }
+
namespace Moses
{
@@ -36,8 +38,15 @@ class Word;
class ChartCellLabel
{
public:
+ union Stack {
+ const HypoList *cube; // cube pruning
+ const search::Vertex *incr; // incremental search after filling.
+ search::VertexGenerator *incr_generator; // incremental search during filling.
+ };
+
+
ChartCellLabel(const WordsRange &coverage, const Word &label,
- const HypoList *stack=NULL)
+ Stack stack=Stack())
: m_coverage(coverage)
, m_label(label)
, m_stack(stack)
@@ -45,7 +54,8 @@ class ChartCellLabel
const WordsRange &GetCoverage() const { return m_coverage; }
const Word &GetLabel() const { return m_label; }
- const HypoList *GetStack() const { return m_stack; }
+ Stack GetStack() const { return m_stack; }
+ Stack &MutableStack() { return m_stack; }
bool operator<(const ChartCellLabel &other) const
{
@@ -60,7 +70,7 @@ class ChartCellLabel
private:
const WordsRange &m_coverage;
const Word &m_label;
- const HypoList *m_stack;
+ Stack m_stack;
};
}
diff --git a/moses/src/ChartCellLabelSet.h b/moses/src/ChartCellLabelSet.h
index b828d5fbc..5ea192e51 100644
--- a/moses/src/ChartCellLabelSet.h
+++ b/moses/src/ChartCellLabelSet.h
@@ -46,21 +46,27 @@ class ChartCellLabelSet
public:
typedef MapType::const_iterator const_iterator;
+ typedef MapType::iterator iterator;
ChartCellLabelSet(const WordsRange &coverage) : m_coverage(coverage) {}
const_iterator begin() const { return m_map.begin(); }
const_iterator end() const { return m_map.end(); }
+
+ iterator mutable_begin() { return m_map.begin(); }
+ iterator mutable_end() { return m_map.end(); }
void AddWord(const Word &w)
{
m_map.insert(std::make_pair(w, ChartCellLabel(m_coverage, w)));
}
- void AddConstituent(const Word &w, const ChartHypothesisCollection &coll)
+ // Stack is a HypoList or whatever the search algorithm uses.
+ void AddConstituent(const Word &w, const HypoList *stack)
{
- const HypoList *stack = &(coll.GetSortedHypotheses());
- m_map.insert(std::make_pair(w, ChartCellLabel(m_coverage, w, stack)));
+ ChartCellLabel::Stack s;
+ s.cube = stack;
+ m_map.insert(std::make_pair(w, ChartCellLabel(m_coverage, w, s)));
}
bool Empty() const { return m_map.empty(); }
@@ -73,6 +79,10 @@ class ChartCellLabelSet
return p == m_map.end() ? 0 : &(p->second);
}
+ ChartCellLabel::Stack &FindOrInsert(const Word &w) {
+ return m_map.insert(std::make_pair(w, ChartCellLabel(m_coverage, w))).first->second.MutableStack();
+ }
+
private:
const WordsRange &m_coverage;
MapType m_map;
diff --git a/moses/src/ChartManager.cpp b/moses/src/ChartManager.cpp
index adb11ea94..17f888925 100644
--- a/moses/src/ChartManager.cpp
+++ b/moses/src/ChartManager.cpp
@@ -50,31 +50,16 @@ ChartManager::ChartManager(InputType const& source, const TranslationSystem* sys
,m_system(system)
,m_start(clock())
,m_hypothesisId(0)
+ ,m_parser(source, *system, m_hypoStackColl)
,m_translationOptionList(StaticData::Instance().GetRuleLimit())
- ,m_decodeGraphList(system->GetDecodeGraphs())
-
{
m_system->InitializeBeforeSentenceProcessing(source);
- const std::vector<PhraseDictionaryFeature*> &dictionaries = m_system->GetPhraseDictionaries();
- m_ruleLookupManagers.reserve(dictionaries.size());
- for (std::vector<PhraseDictionaryFeature*>::const_iterator p = dictionaries.begin();
- p != dictionaries.end(); ++p) {
- PhraseDictionaryFeature *pdf = *p;
- const PhraseDictionary *dict = pdf->GetDictionary();
- PhraseDictionary *nonConstDict = const_cast<PhraseDictionary*>(dict);
- m_ruleLookupManagers.push_back(nonConstDict->CreateRuleLookupManager(source, m_hypoStackColl));
- }
}
ChartManager::~ChartManager()
{
m_system->CleanUpAfterSentenceProcessing(m_source);
- RemoveAllInColl(m_ruleLookupManagers);
-
- RemoveAllInColl(m_unksrcs);
- RemoveAllInColl(m_cacheTargetPhraseCollection);
-
clock_t end = clock();
float et = (end - m_start);
et /= (float)CLOCKS_PER_SEC;
@@ -102,7 +87,10 @@ void ChartManager::ProcessSentence()
WordsRange range(startPos, endPos);
// create trans opt
- CreateTranslationOptionsForRange(range);
+ m_translationOptionList.Clear();
+ m_parser.Create(range, m_translationOptionList);
+ m_translationOptionList.ApplyThreshold();
+ PreCalculateScores();
// decode
ChartCell &cell = m_hypoStackColl.Get(range);
@@ -355,130 +343,7 @@ void ChartManager::CreateDeviantPaths(
}
}
-void ChartManager::CreateTranslationOptionsForRange(const WordsRange &wordsRange)
-{
- assert(m_decodeGraphList.size() == m_ruleLookupManagers.size());
-
- m_translationOptionList.Clear();
-
- std::vector <DecodeGraph*>::const_iterator iterDecodeGraph;
- std::vector <ChartRuleLookupManager*>::const_iterator iterRuleLookupManagers = m_ruleLookupManagers.begin();
- for (iterDecodeGraph = m_decodeGraphList.begin(); iterDecodeGraph != m_decodeGraphList.end(); ++iterDecodeGraph, ++iterRuleLookupManagers) {
- const DecodeGraph &decodeGraph = **iterDecodeGraph;
- assert(decodeGraph.GetSize() == 1);
- ChartRuleLookupManager &ruleLookupManager = **iterRuleLookupManagers;
- size_t maxSpan = decodeGraph.GetMaxChartSpan();
- if (maxSpan == 0 || wordsRange.GetNumWordsCovered() <= maxSpan) {
- ruleLookupManager.GetChartRuleCollection(wordsRange, m_translationOptionList);
- }
- }
-
- if (wordsRange.GetNumWordsCovered() == 1 && wordsRange.GetStartPos() != 0 && wordsRange.GetStartPos() != m_source.GetSize()-1) {
- bool alwaysCreateDirectTranslationOption = StaticData::Instance().IsAlwaysCreateDirectTranslationOption();
- if (m_translationOptionList.GetSize() == 0 || alwaysCreateDirectTranslationOption) {
- // create unknown words for 1 word coverage where we don't have any trans options
- const Word &sourceWord = m_source.GetWord(wordsRange.GetStartPos());
- ProcessOneUnknownWord(sourceWord, wordsRange);
- }
- }
-
- m_translationOptionList.ApplyThreshold();
- PreCalculateScores();
-}
-
-//! special handling of ONE unknown words.
-void ChartManager::ProcessOneUnknownWord(const Word &sourceWord, const WordsRange &range)
-{
- // unknown word, add as trans opt
- const StaticData &staticData = StaticData::Instance();
- const UnknownWordPenaltyProducer *unknownWordPenaltyProducer = m_system->GetUnknownWordPenaltyProducer();
- vector<float> wordPenaltyScore(1, -0.434294482); // TODO what is this number?
-
- const ChartCell &chartCell = m_hypoStackColl.Get(range);
- const ChartCellLabel &sourceWordLabel = chartCell.GetSourceWordLabel();
-
- size_t isDigit = 0;
- if (staticData.GetDropUnknown()) {
- const Factor *f = sourceWord[0]; // TODO hack. shouldn't know which factor is surface
- const string &s = f->GetString();
- isDigit = s.find_first_of("0123456789");
- if (isDigit == string::npos)
- isDigit = 0;
- else
- isDigit = 1;
- // modify the starting bitmap
- }
- Phrase* m_unksrc = new Phrase(1);
- m_unksrc->AddWord() = sourceWord;
- m_unksrcs.push_back(m_unksrc);
-
- //TranslationOption *transOpt;
- if (! staticData.GetDropUnknown() || isDigit) {
- // loop
- const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
- UnknownLHSList::const_iterator iterLHS;
- for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
- const string &targetLHSStr = iterLHS->first;
- float prob = iterLHS->second;
-
- // lhs
- //const Word &sourceLHS = staticData.GetInputDefaultNonTerminal();
- Word targetLHS(true);
-
- targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
- CHECK(targetLHS.GetFactor(0) != NULL);
-
- // add to dictionary
- TargetPhrase *targetPhrase = new TargetPhrase(Output);
- TargetPhraseCollection *tpc = new TargetPhraseCollection;
- tpc->Add(targetPhrase);
-
- m_cacheTargetPhraseCollection.push_back(tpc);
- Word &targetWord = targetPhrase->AddWord();
- targetWord.CreateUnknownWord(sourceWord);
-
- // scores
- vector<float> unknownScore(1, FloorScore(TransformScore(prob)));
-
- //targetPhrase->SetScore();
- targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
- targetPhrase->SetScore(m_system->GetWordPenaltyProducer(), wordPenaltyScore);
- targetPhrase->SetSourcePhrase(*m_unksrc);
- targetPhrase->SetTargetLHS(targetLHS);
-
- // chart rule
- m_translationOptionList.Add(*tpc, m_emptyStackVec, range);
- } // for (iterLHS
- } else {
- // drop source word. create blank trans opt
- vector<float> unknownScore(1, FloorScore(-numeric_limits<float>::infinity()));
-
- TargetPhrase *targetPhrase = new TargetPhrase(Output);
- TargetPhraseCollection *tpc = new TargetPhraseCollection;
- tpc->Add(targetPhrase);
- // loop
- const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
- UnknownLHSList::const_iterator iterLHS;
- for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
- const string &targetLHSStr = iterLHS->first;
- //float prob = iterLHS->second;
-
- Word targetLHS(true);
- targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
- CHECK(targetLHS.GetFactor(0) != NULL);
-
- m_cacheTargetPhraseCollection.push_back(tpc);
- targetPhrase->SetSourcePhrase(*m_unksrc);
- targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
- targetPhrase->SetTargetLHS(targetLHS);
-
- // chart rule
- m_translationOptionList.Add(*tpc, m_emptyStackVec, range);
- }
- }
-}
-
void ChartManager::PreCalculateScores()
{
for (size_t i = 0; i < m_translationOptionList.GetSize(); ++i) {
diff --git a/moses/src/ChartManager.h b/moses/src/ChartManager.h
index b179a917a..20f1815e0 100644
--- a/moses/src/ChartManager.h
+++ b/moses/src/ChartManager.h
@@ -29,8 +29,8 @@
#include "WordsRange.h"
#include "SentenceStats.h"
#include "TranslationSystem.h"
-#include "ChartRuleLookupManager.h"
#include "ChartTranslationOptionList.h"
+#include "ChartParser.h"
#include <boost/shared_ptr.hpp>
@@ -54,22 +54,17 @@ private:
static void CreateDeviantPaths(boost::shared_ptr<const ChartTrellisPath>,
const ChartTrellisNode &,
ChartTrellisDetourQueue &);
- void CreateTranslationOptionsForRange(const WordsRange &wordsRange);
- void ProcessOneUnknownWord(const Word &sourceWord, const WordsRange &range);
InputType const& m_source; /**< source sentence to be translated */
ChartCellCollection m_hypoStackColl;
std::auto_ptr<SentenceStats> m_sentenceStats;
const TranslationSystem* m_system;
clock_t m_start; /**< starting time, used for logging */
- std::vector<ChartRuleLookupManager*> m_ruleLookupManagers;
unsigned m_hypothesisId; /* For handing out hypothesis ids to ChartHypothesis */
+ ChartParser m_parser;
+
ChartTranslationOptionList m_translationOptionList; /**< pre-computed list of translation options for the phrases in this sentence */
- std::vector<Phrase*> m_unksrcs;
- std::list<TargetPhraseCollection*> m_cacheTargetPhraseCollection;
- std::vector <DecodeGraph*> m_decodeGraphList;
- StackVec m_emptyStackVec;
//! Some features should be calculated prior to search
boost::unordered_map<TargetPhrase,ScoreComponentCollection, TargetPhraseHasher, TargetPhraseComparator> m_precalculatedScores;
diff --git a/moses/src/ChartParser.cpp b/moses/src/ChartParser.cpp
new file mode 100644
index 000000000..caedad570
--- /dev/null
+++ b/moses/src/ChartParser.cpp
@@ -0,0 +1,168 @@
+// $Id$
+// vim:tabstop=2
+/***********************************************************************
+ Moses - factored phrase-based language decoder
+ Copyright (C) 2010 Hieu Hoang
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ ***********************************************************************/
+
+#include "ChartParser.h"
+#include "ChartParserCallback.h"
+#include "ChartRuleLookupManager.h"
+#include "DummyScoreProducers.h"
+#include "StaticData.h"
+#include "TreeInput.h"
+
+using namespace std;
+using namespace Moses;
+
+namespace Moses
+{
+extern bool g_debug;
+
+ChartParserUnknown::ChartParserUnknown(const TranslationSystem &system) : m_system(system) {}
+
+ChartParserUnknown::~ChartParserUnknown() {
+ RemoveAllInColl(m_unksrcs);
+ RemoveAllInColl(m_cacheTargetPhraseCollection);
+}
+
+void ChartParserUnknown::Process(const Word &sourceWord, const WordsRange &range, ChartParserCallback &to) {
+ // unknown word, add as trans opt
+ const StaticData &staticData = StaticData::Instance();
+ const UnknownWordPenaltyProducer *unknownWordPenaltyProducer = m_system.GetUnknownWordPenaltyProducer();
+ vector<float> wordPenaltyScore(1, -0.434294482); // TODO what is this number?
+
+ size_t isDigit = 0;
+ if (staticData.GetDropUnknown()) {
+ const Factor *f = sourceWord[0]; // TODO hack. shouldn't know which factor is surface
+ const string &s = f->GetString();
+ isDigit = s.find_first_of("0123456789");
+ if (isDigit == string::npos)
+ isDigit = 0;
+ else
+ isDigit = 1;
+ // modify the starting bitmap
+ }
+
+ Phrase* unksrc = new Phrase(1);
+ unksrc->AddWord() = sourceWord;
+ m_unksrcs.push_back(unksrc);
+
+ //TranslationOption *transOpt;
+ if (! staticData.GetDropUnknown() || isDigit) {
+ // loop
+ const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
+ UnknownLHSList::const_iterator iterLHS;
+ for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
+ const string &targetLHSStr = iterLHS->first;
+ float prob = iterLHS->second;
+
+ // lhs
+ //const Word &sourceLHS = staticData.GetInputDefaultNonTerminal();
+ Word targetLHS(true);
+
+ targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
+ CHECK(targetLHS.GetFactor(0) != NULL);
+
+ // add to dictionary
+ TargetPhrase *targetPhrase = new TargetPhrase(Output);
+ Word &targetWord = targetPhrase->AddWord();
+ targetWord.CreateUnknownWord(sourceWord);
+
+ // scores
+ vector<float> unknownScore(1, FloorScore(TransformScore(prob)));
+
+ //targetPhrase->SetScore();
+ targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
+ targetPhrase->SetScore(m_system.GetWordPenaltyProducer(), wordPenaltyScore);
+ targetPhrase->SetSourcePhrase(*unksrc);
+ targetPhrase->SetTargetLHS(targetLHS);
+
+ // chart rule
+ to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
+ } // for (iterLHS
+ } else {
+ // drop source word. create blank trans opt
+ vector<float> unknownScore(1, FloorScore(-numeric_limits<float>::infinity()));
+
+ TargetPhrase *targetPhrase = new TargetPhrase(Output);
+ // loop
+ const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
+ UnknownLHSList::const_iterator iterLHS;
+ for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
+ const string &targetLHSStr = iterLHS->first;
+ //float prob = iterLHS->second;
+
+ Word targetLHS(true);
+ targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
+ CHECK(targetLHS.GetFactor(0) != NULL);
+
+ targetPhrase->SetSourcePhrase(*unksrc);
+ targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
+ targetPhrase->SetTargetLHS(targetLHS);
+
+ // chart rule
+ to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
+ }
+ }
+}
+
+ChartParser::ChartParser(InputType const &source, const TranslationSystem &system, ChartCellCollectionBase &cells) :
+ m_unknown(system),
+ m_decodeGraphList(system.GetDecodeGraphs()),
+ m_source(source) {
+ const std::vector<PhraseDictionaryFeature*> &dictionaries = system.GetPhraseDictionaries();
+ m_ruleLookupManagers.reserve(dictionaries.size());
+ for (std::vector<PhraseDictionaryFeature*>::const_iterator p = dictionaries.begin();
+ p != dictionaries.end(); ++p) {
+ PhraseDictionaryFeature *pdf = *p;
+ const PhraseDictionary *dict = pdf->GetDictionary();
+ PhraseDictionary *nonConstDict = const_cast<PhraseDictionary*>(dict);
+ m_ruleLookupManagers.push_back(nonConstDict->CreateRuleLookupManager(source, cells));
+ }
+}
+
+ChartParser::~ChartParser() {
+ RemoveAllInColl(m_ruleLookupManagers);
+}
+
+void ChartParser::Create(const WordsRange &wordsRange, ChartParserCallback &to) {
+ assert(m_decodeGraphList.size() == m_ruleLookupManagers.size());
+
+ std::vector <DecodeGraph*>::const_iterator iterDecodeGraph;
+ std::vector <ChartRuleLookupManager*>::const_iterator iterRuleLookupManagers = m_ruleLookupManagers.begin();
+ for (iterDecodeGraph = m_decodeGraphList.begin(); iterDecodeGraph != m_decodeGraphList.end(); ++iterDecodeGraph, ++iterRuleLookupManagers) {
+ const DecodeGraph &decodeGraph = **iterDecodeGraph;
+ assert(decodeGraph.GetSize() == 1);
+ ChartRuleLookupManager &ruleLookupManager = **iterRuleLookupManagers;
+ size_t maxSpan = decodeGraph.GetMaxChartSpan();
+ if (maxSpan == 0 || wordsRange.GetNumWordsCovered() <= maxSpan) {
+ ruleLookupManager.GetChartRuleCollection(wordsRange, to);
+ }
+ }
+
+ if (wordsRange.GetNumWordsCovered() == 1 && wordsRange.GetStartPos() != 0 && wordsRange.GetStartPos() != m_source.GetSize()-1) {
+ bool alwaysCreateDirectTranslationOption = StaticData::Instance().IsAlwaysCreateDirectTranslationOption();
+ if (to.Empty() || alwaysCreateDirectTranslationOption) {
+ // create unknown words for 1 word coverage where we don't have any trans options
+ const Word &sourceWord = m_source.GetWord(wordsRange.GetStartPos());
+ m_unknown.Process(sourceWord, wordsRange, to);
+ }
+ }
+}
+
+} // namespace Moses
diff --git a/moses/src/ChartParser.h b/moses/src/ChartParser.h
new file mode 100644
index 000000000..720199f3e
--- /dev/null
+++ b/moses/src/ChartParser.h
@@ -0,0 +1,72 @@
+// $Id$
+// vim:tabstop=2
+/***********************************************************************
+ Moses - factored phrase-based language decoder
+ Copyright (C) 2010 Hieu Hoang
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ ***********************************************************************/
+
+#pragma once
+
+#include "WordsRange.h"
+#include "StackVec.h"
+
+#include <list>
+#include <vector>
+
+namespace Moses
+{
+
+class ChartParserCallback;
+class ChartRuleLookupManager;
+class InputType;
+class TranslationSystem;
+class ChartCellCollectionBase;
+class Word;
+class Phrase;
+class TargetPhraseCollection;
+class DecodeGraph;
+
+class ChartParserUnknown {
+ public:
+ ChartParserUnknown(const TranslationSystem &system);
+ ~ChartParserUnknown();
+
+ void Process(const Word &sourceWord, const WordsRange &range, ChartParserCallback &to);
+
+ private:
+ const TranslationSystem &m_system;
+ std::vector<Phrase*> m_unksrcs;
+ std::list<TargetPhraseCollection*> m_cacheTargetPhraseCollection;
+ StackVec m_emptyStackVec;
+};
+
+class ChartParser {
+ public:
+ ChartParser(const InputType &source, const TranslationSystem &system, ChartCellCollectionBase &cells);
+ ~ChartParser();
+
+ void Create(const WordsRange &range, ChartParserCallback &to);
+
+ private:
+ ChartParserUnknown m_unknown;
+ std::vector <DecodeGraph*> m_decodeGraphList;
+ std::vector<ChartRuleLookupManager*> m_ruleLookupManagers;
+ InputType const& m_source; /**< source sentence to be translated */
+};
+
+}
+
diff --git a/moses/src/ChartParserCallback.h b/moses/src/ChartParserCallback.h
new file mode 100644
index 000000000..797a57156
--- /dev/null
+++ b/moses/src/ChartParserCallback.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "StackVec.h"
+
+#include <list>
+
+namespace Moses {
+
+class TargetPhraseCollection;
+class WordsRange;
+class TargetPhrase;
+
+class ChartParserCallback {
+ public:
+ virtual ~ChartParserCallback() {}
+
+ virtual void Add(const TargetPhraseCollection &, const StackVec &, const WordsRange &) = 0;
+
+ virtual bool Empty() const = 0;
+
+ virtual void AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range) = 0;
+};
+
+} // namespace Moses
diff --git a/moses/src/ChartRuleLookupManager.h b/moses/src/ChartRuleLookupManager.h
index 2c17aea19..da8c98cb4 100644
--- a/moses/src/ChartRuleLookupManager.h
+++ b/moses/src/ChartRuleLookupManager.h
@@ -27,7 +27,7 @@
namespace Moses
{
-class ChartTranslationOptionList;
+class ChartParserCallback;
class WordsRange;
/** Defines an interface for looking up rules in a rule table. Concrete
@@ -40,7 +40,7 @@ class ChartRuleLookupManager
{
public:
ChartRuleLookupManager(const InputType &sentence,
- const ChartCellCollection &cellColl)
+ const ChartCellCollectionBase &cellColl)
: m_sentence(sentence)
, m_cellCollection(cellColl) {}
@@ -51,9 +51,12 @@ public:
return m_sentence;
}
- //! all the chart cells
- const ChartCellCollection &GetCellCollection() const {
- return m_cellCollection;
+ const ChartCellLabelSet &GetTargetLabelSet(size_t begin, size_t end) const {
+ return m_cellCollection.GetBase(WordsRange(begin, end)).GetTargetLabelSet();
+ }
+
+ const ChartCellLabel &GetSourceAt(size_t at) const {
+ return m_cellCollection.GetSourceWordLabel(at);
}
/** abstract function. Return a vector of translation options for given a range in the input sentence
@@ -62,7 +65,7 @@ public:
*/
virtual void GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl) = 0;
+ ChartParserCallback &outColl) = 0;
private:
//! Non-copyable: copy constructor and assignment operator not implemented.
@@ -71,7 +74,7 @@ private:
ChartRuleLookupManager &operator=(const ChartRuleLookupManager &);
const InputType &m_sentence;
- const ChartCellCollection &m_cellCollection;
+ const ChartCellCollectionBase &m_cellCollection;
};
} // namespace Moses
diff --git a/moses/src/ChartTranslationOptionList.cpp b/moses/src/ChartTranslationOptionList.cpp
index eb2add105..8f4422e23 100644
--- a/moses/src/ChartTranslationOptionList.cpp
+++ b/moses/src/ChartTranslationOptionList.cpp
@@ -98,6 +98,14 @@ void ChartTranslationOptionList::Add(const TargetPhraseCollection &tpc,
}
}
+void ChartTranslationOptionList::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range) {
+ TargetPhraseCollection *tpc = new TargetPhraseCollection();
+ tpc->Add(&phrase);
+ waste_memory.push_back(tpc);
+ StackVec empty;
+ Add(*tpc, empty, range);
+}
+
void ChartTranslationOptionList::ApplyThreshold() {
if (m_size > m_ruleLimit) {
// Something's gone wrong if the list has grown to m_ruleLimit * 2
diff --git a/moses/src/ChartTranslationOptionList.h b/moses/src/ChartTranslationOptionList.h
index 3197037c6..0b56b1f61 100644
--- a/moses/src/ChartTranslationOptionList.h
+++ b/moses/src/ChartTranslationOptionList.h
@@ -20,6 +20,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#pragma once
#include "ChartTranslationOptions.h"
+#include "ChartParserCallback.h"
#include "StackVec.h"
#include <vector>
@@ -31,8 +32,7 @@ class TargetPhraseCollection;
class WordsRange;
//! a vector of translations options for a specific range, in a specific sentence
-class ChartTranslationOptionList
-{
+class ChartTranslationOptionList : public ChartParserCallback {
public:
ChartTranslationOptionList(size_t);
~ChartTranslationOptionList();
@@ -45,17 +45,19 @@ class ChartTranslationOptionList
void Add(const TargetPhraseCollection &, const StackVec &,
const WordsRange &);
+ void AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range);
+
+ bool Empty() const { return m_size == 0; }
+
void Clear();
void ApplyThreshold();
private:
typedef std::vector<ChartTranslationOptions*> CollType;
- struct ScoreThresholdPred
- {
+ struct ScoreThresholdPred {
ScoreThresholdPred(float threshold) : m_thresholdScore(threshold) {}
- bool operator()(const ChartTranslationOptions *option)
- {
+ bool operator()(const ChartTranslationOptions *option) {
return option->GetEstimateOfBestScore() >= m_thresholdScore;
}
float m_thresholdScore;
diff --git a/moses/src/ChartTranslationOptions.cpp b/moses/src/ChartTranslationOptions.cpp
index ef21bc1d5..c55948a82 100644
--- a/moses/src/ChartTranslationOptions.cpp
+++ b/moses/src/ChartTranslationOptions.cpp
@@ -21,6 +21,8 @@
#include "ChartHypothesis.h"
+#include "ChartCellLabel.h"
+
namespace Moses
{
@@ -32,7 +34,7 @@ float ChartTranslationOptions::CalcEstimateOfBestScore(
float estimateOfBestScore = targetPhrase.GetFutureScore();
for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end();
++p) {
- const HypoList *stack = *p;
+ const HypoList *stack = (*p)->GetStack().cube;
assert(stack);
assert(!stack->empty());
const ChartHypothesis &bestHypo = **(stack->begin());
diff --git a/moses/src/CompactPT/PhraseDictionaryCompact.h b/moses/src/CompactPT/PhraseDictionaryCompact.h
index 6090967d2..0b983b10c 100644
--- a/moses/src/CompactPT/PhraseDictionaryCompact.h
+++ b/moses/src/CompactPT/PhraseDictionaryCompact.h
@@ -110,7 +110,7 @@ public:
virtual ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &)
+ const ChartCellCollectionBase &)
{
assert(false);
return 0;
diff --git a/moses/src/Incremental/Fill.cpp b/moses/src/Incremental/Fill.cpp
new file mode 100644
index 000000000..2246ea3a3
--- /dev/null
+++ b/moses/src/Incremental/Fill.cpp
@@ -0,0 +1,145 @@
+#include "Incremental/Fill.h"
+
+#include "ChartCellLabel.h"
+#include "ChartCellLabelSet.h"
+#include "TargetPhraseCollection.h"
+#include "TargetPhrase.h"
+#include "Word.h"
+
+#include "lm/model.hh"
+#include "search/context.hh"
+#include "search/note.hh"
+#include "search/vertex.hh"
+#include "search/vertex_generator.hh"
+
+#include <math.h>
+
+namespace Moses {
+namespace Incremental {
+
+template <class Model> Fill<Model>::Fill(search::Context<Model> &context, const std::vector<lm::WordIndex> &vocab_mapping)
+ : context_(context), vocab_mapping_(vocab_mapping), edges_(context.PopLimit()) {}
+
+template <class Model> void Fill<Model>::Add(const TargetPhraseCollection &targets, const StackVec &nts, const WordsRange &) {
+ const unsigned char arity = nts.size();
+ CHECK(arity <= search::kMaxArity);
+
+ search::PartialVertex vertices[search::kMaxArity];
+ float below_score = 0.0;
+ for (unsigned int i = 0; i < nts.size(); ++i) {
+ vertices[i] = nts[i]->GetStack().incr->RootPartial();
+ if (vertices[i].Empty()) return;
+ below_score += vertices[i].Bound();
+ }
+
+ std::vector<lm::WordIndex> words;
+ for (TargetPhraseCollection::const_iterator i(targets.begin()); i != targets.end(); ++i) {
+ words.clear();
+ const TargetPhrase &phrase = **i;
+ const AlignmentInfo::NonTermIndexMap &align = phrase.GetAlignmentInfo().GetNonTermIndexMap();
+ search::PartialEdge &edge = edges_.InitializeEdge();
+
+ size_t i = 0;
+ bool bos = false;
+ unsigned char nt = 0;
+ if (phrase.GetSize() && !phrase.GetWord(0).IsNonTerminal()) {
+ lm::WordIndex index = Convert(phrase.GetWord(0));
+ if (context_.LanguageModel().GetVocabulary().BeginSentence() == index) {
+ bos = true;
+ } else {
+ words.push_back(index);
+ }
+ i = 1;
+ }
+ for (; i < phrase.GetSize(); ++i) {
+ const Word &word = phrase.GetWord(i);
+ if (word.IsNonTerminal()) {
+ edge.nt[nt++] = vertices[align[i]];
+ words.push_back(search::kNonTerminal);
+ } else {
+ words.push_back(Convert(word));
+ }
+ }
+ for (; nt < 2; ++nt) edge.nt[nt] = search::kBlankPartialVertex;
+
+ edge.score = phrase.GetFutureScore() + below_score;
+ search::ScoreRule(context_, words, bos, edge.between);
+
+ search::Note note;
+ note.vp = &phrase;
+ edges_.AddEdge(arity, note);
+ }
+}
+
+template <class Model> void Fill<Model>::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &, const WordsRange &) {
+ std::vector<lm::WordIndex> words;
+ CHECK(phrase.GetSize() <= 1);
+ if (phrase.GetSize())
+ words.push_back(Convert(phrase.GetWord(0)));
+
+ search::PartialEdge &edge = edges_.InitializeEdge();
+ // Appears to be a bug that this does not include language model.
+ edge.score = phrase.GetFutureScore() + search::ScoreRule(context_, words, false, edge.between);
+
+ for (unsigned int i = 0; i < 2; ++i) {
+ edge.nt[i] = search::kBlankPartialVertex;
+ }
+
+ search::Note note;
+ note.vp = &phrase;
+ edges_.AddEdge(0, note);
+}
+
+namespace {
+// Route hypotheses to separate vertices for each left hand side label, populating ChartCellLabelSet out.
+class HypothesisCallback {
+ public:
+ HypothesisCallback(search::ContextBase &context, ChartCellLabelSet &out, boost::object_pool<search::Vertex> &vertex_pool)
+ : context_(context), out_(out), vertex_pool_(vertex_pool) {}
+
+ void NewHypothesis(const search::PartialEdge &partial, search::Note note) {
+ search::VertexGenerator *&entry = out_.FindOrInsert(static_cast<const TargetPhrase *>(note.vp)->GetTargetLHS()).incr_generator;
+ if (!entry) {
+ entry = generator_pool_.construct(context_, *vertex_pool_.construct());
+ }
+ entry->NewHypothesis(partial, note);
+ }
+
+ void FinishedSearch() {
+ for (ChartCellLabelSet::iterator i(out_.mutable_begin()); i != out_.mutable_end(); ++i) {
+ ChartCellLabel::Stack &stack = i->second.MutableStack();
+ stack.incr_generator->FinishedSearch();
+ stack.incr = &stack.incr_generator->Generating();
+ }
+ }
+
+ private:
+ search::ContextBase &context_;
+
+ ChartCellLabelSet &out_;
+
+ boost::object_pool<search::Vertex> &vertex_pool_;
+ boost::object_pool<search::VertexGenerator> generator_pool_;
+};
+} // namespace
+
+template <class Model> void Fill<Model>::Search(ChartCellLabelSet &out, boost::object_pool<search::Vertex> &vertex_pool) {
+ HypothesisCallback callback(context_, out, vertex_pool);
+ edges_.Search(context_, callback);
+}
+
+// TODO: factors (but chart doesn't seem to support factors anyway).
+template <class Model> lm::WordIndex Fill<Model>::Convert(const Word &word) const {
+ std::size_t factor = word.GetFactor(0)->GetId();
+ return (factor >= vocab_mapping_.size() ? 0 : vocab_mapping_[factor]);
+}
+
+template class Fill<lm::ngram::ProbingModel>;
+template class Fill<lm::ngram::RestProbingModel>;
+template class Fill<lm::ngram::TrieModel>;
+template class Fill<lm::ngram::QuantTrieModel>;
+template class Fill<lm::ngram::ArrayTrieModel>;
+template class Fill<lm::ngram::QuantArrayTrieModel>;
+
+} // namespace Incremental
+} // namespace Moses
diff --git a/moses/src/Incremental/Fill.h b/moses/src/Incremental/Fill.h
new file mode 100644
index 000000000..d6d9d4f54
--- /dev/null
+++ b/moses/src/Incremental/Fill.h
@@ -0,0 +1,54 @@
+#pragma once
+
+#include "ChartParserCallback.h"
+#include "StackVec.h"
+
+#include "lm/word_index.hh"
+#include "search/edge_queue.hh"
+
+#include <boost/pool/object_pool.hpp>
+
+#include <list>
+#include <vector>
+
+namespace search {
+template <class Model> class Context;
+class Vertex;
+} // namespace search
+
+namespace Moses {
+class Word;
+class WordsRange;
+class TargetPhraseCollection;
+class WordsRange;
+class ChartCellLabelSet;
+class TargetPhrase;
+
+namespace Incremental {
+
+// Replacement for ChartTranslationOptionList
+// TODO: implement count and score thresholding.
+template <class Model> class Fill : public ChartParserCallback {
+ public:
+ Fill(search::Context<Model> &context, const std::vector<lm::WordIndex> &vocab_mapping);
+
+ void Add(const TargetPhraseCollection &targets, const StackVec &nts, const WordsRange &ignored);
+
+ void AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range);
+
+ bool Empty() const { return edges_.Empty(); }
+
+ void Search(ChartCellLabelSet &out, boost::object_pool<search::Vertex> &vertex_pool);
+
+ private:
+ lm::WordIndex Convert(const Word &word) const ;
+
+ search::Context<Model> &context_;
+
+ const std::vector<lm::WordIndex> &vocab_mapping_;
+
+ search::EdgeQueue edges_;
+};
+
+} // namespace Incremental
+} // namespace Moses
diff --git a/moses/src/Incremental/Jamfile b/moses/src/Incremental/Jamfile
new file mode 100644
index 000000000..5b4c703e9
--- /dev/null
+++ b/moses/src/Incremental/Jamfile
@@ -0,0 +1 @@
+lib Incremental : [ glob *.cpp ] ../../../search//search ..//moses_internal ;
diff --git a/moses/src/Incremental/Manager.cpp b/moses/src/Incremental/Manager.cpp
new file mode 100644
index 000000000..f6a13c14a
--- /dev/null
+++ b/moses/src/Incremental/Manager.cpp
@@ -0,0 +1,121 @@
+#include "Incremental/Manager.h"
+
+#include "Incremental/Fill.h"
+
+#include "ChartCell.h"
+#include "TranslationSystem.h"
+#include "StaticData.h"
+
+#include "search/context.hh"
+#include "search/config.hh"
+#include "search/weights.hh"
+
+#include <boost/lexical_cast.hpp>
+
+namespace Moses {
+namespace Incremental {
+
+namespace {
+struct ChartCellBaseFactory {
+ ChartCellBase *operator()(size_t startPos, size_t endPos) const {
+ return new ChartCellBase(startPos, endPos);
+ }
+};
+} // namespace
+
+Manager::Manager(const InputType &source, const TranslationSystem &system) :
+ source_(source),
+ system_(system),
+ cells_(source, ChartCellBaseFactory()),
+ parser_(source, system, cells_) {
+
+ system.InitializeBeforeSentenceProcessing(source);
+}
+
+Manager::~Manager() {
+ system_.CleanUpAfterSentenceProcessing(source_);
+}
+
+namespace {
+
+void ConstructString(const search::Final &final, std::ostringstream &stream) {
+ const TargetPhrase &phrase = *static_cast<const TargetPhrase*>(final.GetNote().vp);
+ size_t child = 0;
+ for (std::size_t i = 0; i < phrase.GetSize(); ++i) {
+ const Word &word = phrase.GetWord(i);
+ if (word.IsNonTerminal()) {
+ ConstructString(*final.Children()[child++], stream);
+ } else {
+ stream << word[0]->GetString() << ' ';
+ }
+ }
+}
+
+void BestString(const ChartCellLabelSet &labels, std::string &out) {
+ const search::Final *best = NULL;
+ for (ChartCellLabelSet::const_iterator i = labels.begin(); i != labels.end(); ++i) {
+ const search::Final *child = i->second.GetStack().incr->BestChild();
+ if (child && (!best || (child->Bound() > best->Bound()))) {
+ best = child;
+ }
+ }
+ if (!best) {
+ out.clear();
+ return;
+ }
+ std::ostringstream stream;
+ ConstructString(*best, stream);
+ out = stream.str();
+ CHECK(out.size() > 9);
+ // <s>
+ out.erase(0, 4);
+ // </s>
+ out.erase(out.size() - 5);
+ // Hack: include model score
+ out += " ||| ";
+ out += boost::lexical_cast<std::string>(best->Bound());
+}
+
+} // namespace
+
+
+template <class Model> void Manager::LMCallback(const Model &model, const std::vector<lm::WordIndex> &words) {
+ const LanguageModel &abstract = **system_.GetLanguageModels().begin();
+ search::Weights weights(
+ abstract.GetWeight(),
+ abstract.OOVFeatureEnabled() ? abstract.GetOOVWeight() : 0.0,
+ system_.GetWeightWordPenalty());
+ search::Config config(weights, StaticData::Instance().GetCubePruningPopLimit());
+ search::Context<Model> context(config, model);
+
+ size_t size = source_.GetSize();
+
+ boost::object_pool<search::Vertex> vertex_pool(std::max<size_t>(size * size / 2, 32));
+
+ for (size_t width = 1; width <= size; ++width) {
+ for (size_t startPos = 0; startPos <= size-width; ++startPos) {
+ size_t endPos = startPos + width - 1;
+ WordsRange range(startPos, endPos);
+ Fill<Model> filler(context, words);
+ parser_.Create(range, filler);
+ filler.Search(cells_.MutableBase(range).MutableTargetLabelSet(), vertex_pool);
+ }
+ }
+ BestString(cells_.GetBase(WordsRange(0, source_.GetSize() - 1)).GetTargetLabelSet(), output_);
+}
+
+template void Manager::LMCallback<lm::ngram::ProbingModel>(const lm::ngram::ProbingModel &model, const std::vector<lm::WordIndex> &words);
+template void Manager::LMCallback<lm::ngram::RestProbingModel>(const lm::ngram::RestProbingModel &model, const std::vector<lm::WordIndex> &words);
+template void Manager::LMCallback<lm::ngram::TrieModel>(const lm::ngram::TrieModel &model, const std::vector<lm::WordIndex> &words);
+template void Manager::LMCallback<lm::ngram::QuantTrieModel>(const lm::ngram::QuantTrieModel &model, const std::vector<lm::WordIndex> &words);
+template void Manager::LMCallback<lm::ngram::ArrayTrieModel>(const lm::ngram::ArrayTrieModel &model, const std::vector<lm::WordIndex> &words);
+template void Manager::LMCallback<lm::ngram::QuantArrayTrieModel>(const lm::ngram::QuantArrayTrieModel &model, const std::vector<lm::WordIndex> &words);
+
+void Manager::ProcessSentence() {
+ const LMList &lms = system_.GetLanguageModels();
+ UTIL_THROW_IF(lms.size() != 1, util::Exception, "Incremental search only supports one language model.");
+ (*lms.begin())->IncrementalCallback(*this);
+}
+
+} // namespace Incremental
+} // namespace Moses
diff --git a/moses/src/Incremental/Manager.h b/moses/src/Incremental/Manager.h
new file mode 100644
index 000000000..1ca51a5c4
--- /dev/null
+++ b/moses/src/Incremental/Manager.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include "lm/word_index.hh"
+
+#include "ChartCellCollection.h"
+#include "ChartParser.h"
+
+namespace Moses {
+class InputType;
+class TranslationSystem;
+namespace Incremental {
+
+class Manager {
+ public:
+ Manager(const InputType &source, const TranslationSystem &system);
+
+ ~Manager();
+
+ template <class Model> void LMCallback(const Model &model, const std::vector<lm::WordIndex> &words);
+
+ void ProcessSentence();
+
+ const std::string &String() const { return output_; }
+
+ private:
+ const InputType &source_;
+ const TranslationSystem &system_;
+ ChartCellCollectionBase cells_;
+ ChartParser parser_;
+
+ std::string output_;
+};
+} // namespace Incremental
+} // namespace Moses
+
diff --git a/moses/src/Jamfile b/moses/src/Jamfile
index 71c22cd89..4dcfc7437 100644
--- a/moses/src/Jamfile
+++ b/moses/src/Jamfile
@@ -24,7 +24,7 @@ lib moses_internal :
[ glob *.cpp DynSAInclude/*.cpp : PhraseDictionary.cpp ThreadPool.cpp SyntacticLanguageModel.cpp *Test.cpp Mock*.cpp ]
synlm ThreadPool headers rt ;
-lib moses : PhraseDictionary.cpp moses_internal CYKPlusParser//CYKPlusParser CompactPT//CompactPT LM//LM RuleTable//RuleTable Scope3Parser//Scope3Parser fuzzy-match//fuzzy-match headers ../..//z ../../OnDiskPt//OnDiskPt ;
+lib moses : PhraseDictionary.cpp moses_internal CYKPlusParser//CYKPlusParser CompactPT//CompactPT LM//LM RuleTable//RuleTable Scope3Parser//Scope3Parser fuzzy-match//fuzzy-match Incremental//Incremental headers ../..//z ../../OnDiskPt//OnDiskPt ;
alias headers-to-install : [ glob-tree *.h ] ;
diff --git a/moses/src/LM/Base.cpp b/moses/src/LM/Base.cpp
index 45edf973e..0d2548902 100644
--- a/moses/src/LM/Base.cpp
+++ b/moses/src/LM/Base.cpp
@@ -27,6 +27,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h"
+#include "util/exception.hh"
using namespace std;
@@ -54,4 +55,8 @@ float LanguageModel::GetOOVWeight() const {
}
}
+void LanguageModel::IncrementalCallback(Incremental::Manager &manager) const {
+ UTIL_THROW(util::Exception, "Incremental search is only supported by KenLM.");
+}
+
} // namespace Moses
diff --git a/moses/src/LM/Base.h b/moses/src/LM/Base.h
index 424dcb443..450dcd4c2 100644
--- a/moses/src/LM/Base.h
+++ b/moses/src/LM/Base.h
@@ -24,11 +24,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <string>
#include <cstddef>
+
#include "../FeatureFunction.h"
namespace Moses
{
+namespace Incremental { class Manager; }
+
class FactorCollection;
class Factor;
class Phrase;
@@ -90,6 +93,8 @@ public:
virtual void SetFFStateIdx(int state_idx) {
}
+ // KenLM only (others throw an exception): call incremental search with the model and mapping.
+ virtual void IncrementalCallback(Incremental::Manager &manager) const;
};
}
diff --git a/moses/src/LM/Jamfile b/moses/src/LM/Jamfile
index 60f73303d..3011a620c 100644
--- a/moses/src/LM/Jamfile
+++ b/moses/src/LM/Jamfile
@@ -93,4 +93,4 @@ obj Factory.o : Factory.cpp ..//headers $(dependencies) : <include>../DynSAInclu
#Top-level LM library. If you've added a file that doesn't depend on external
#libraries, put it here.
lib LM : Base.cpp Factory.o Implementation.cpp Joint.cpp Ken.cpp MultiFactor.cpp Remote.cpp SingleFactor.cpp ORLM.o
- ../../../lm//kenlm ..//headers $(dependencies) ;
+ ../../../lm//kenlm ..//headers ../Incremental//Incremental $(dependencies) ;
diff --git a/moses/src/LM/Ken.cpp b/moses/src/LM/Ken.cpp
index 374ee8d57..a635ddb08 100644
--- a/moses/src/LM/Ken.cpp
+++ b/moses/src/LM/Ken.cpp
@@ -38,6 +38,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "InputFileStream.h"
#include "StaticData.h"
#include "ChartHypothesis.h"
+#include "Incremental/Manager.h"
#include <boost/shared_ptr.hpp>
@@ -87,6 +88,10 @@ template <class Model> class LanguageModelKen : public LanguageModel {
FFState *EvaluateChart(const ChartHypothesis& cur_hypo, int featureID, ScoreComponentCollection *accumulator) const;
+ void IncrementalCallback(Incremental::Manager &manager) const {
+ manager.LMCallback(*m_ngram, m_lmIdLookup);
+ }
+
private:
LanguageModelKen(const LanguageModelKen<Model> &copy_from);
diff --git a/moses/src/Phrase.cpp b/moses/src/Phrase.cpp
index db808390c..8cc43f832 100644
--- a/moses/src/Phrase.cpp
+++ b/moses/src/Phrase.cpp
@@ -174,13 +174,15 @@ void Phrase::CreateFromString(const std::vector<FactorType> &factorOrder, const
void Phrase::CreateFromStringNewFormat(FactorDirection direction
, const std::vector<FactorType> &factorOrder
- , const std::string &phraseString
+ , const StringPiece &phraseString
, const std::string & /*factorDelimiter */
, Word &lhs)
{
// parse
- vector<string> annotatedWordVector;
- Tokenize(annotatedWordVector, phraseString);
+ vector<StringPiece> annotatedWordVector;
+ for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
+ annotatedWordVector.push_back(*it);
+ }
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
@@ -188,7 +190,7 @@ void Phrase::CreateFromStringNewFormat(FactorDirection direction
m_words.reserve(annotatedWordVector.size()-1);
for (size_t phrasePos = 0 ; phrasePos < annotatedWordVector.size() - 1 ; phrasePos++) {
- string &annotatedWord = annotatedWordVector[phrasePos];
+ StringPiece &annotatedWord = annotatedWordVector[phrasePos];
bool isNonTerminal;
if (annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]") {
// non-term
@@ -211,7 +213,7 @@ void Phrase::CreateFromStringNewFormat(FactorDirection direction
}
// lhs
- string &annotatedWord = annotatedWordVector.back();
+ StringPiece &annotatedWord = annotatedWordVector.back();
CHECK(annotatedWord.substr(0, 1) == "[" && annotatedWord.substr(annotatedWord.size()-1, 1) == "]");
annotatedWord = annotatedWord.substr(1, annotatedWord.size() - 2);
diff --git a/moses/src/Phrase.h b/moses/src/Phrase.h
index 49586271a..d04c151f9 100644
--- a/moses/src/Phrase.h
+++ b/moses/src/Phrase.h
@@ -73,7 +73,7 @@ public:
void CreateFromStringNewFormat(FactorDirection direction
, const std::vector<FactorType> &factorOrder
- , const std::string &phraseString
+ , const StringPiece &phraseString
, const std::string &factorDelimiter
, Word &lhs);
diff --git a/moses/src/PhraseDictionary.h b/moses/src/PhraseDictionary.h
index 3136c47de..ec635c179 100644
--- a/moses/src/PhraseDictionary.h
+++ b/moses/src/PhraseDictionary.h
@@ -46,8 +46,7 @@ namespace Moses
class StaticData;
class InputType;
class WordsRange;
-class ChartTranslationOptionList;
-class ChartCellCollection;
+class ChartCellCollectionBase;
class TranslationSystem;
class ChartRuleLookupManager;
@@ -82,7 +81,7 @@ public:
//! Create a sentence-specific manager for SCFG rule lookup.
virtual ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &) = 0;
+ const ChartCellCollectionBase &) = 0;
protected:
size_t m_tableLimit;
diff --git a/moses/src/PhraseDictionaryDynSuffixArray.cpp b/moses/src/PhraseDictionaryDynSuffixArray.cpp
index 8e32758fa..c54d439de 100644
--- a/moses/src/PhraseDictionaryDynSuffixArray.cpp
+++ b/moses/src/PhraseDictionaryDynSuffixArray.cpp
@@ -79,7 +79,7 @@ void PhraseDictionaryDynSuffixArray::deleteSnt(unsigned /* idx */, unsigned /* n
// need to implement --
}
-ChartRuleLookupManager *PhraseDictionaryDynSuffixArray::CreateRuleLookupManager(const InputType&, const ChartCellCollection&)
+ChartRuleLookupManager *PhraseDictionaryDynSuffixArray::CreateRuleLookupManager(const InputType&, const ChartCellCollectionBase&)
{
CHECK(false);
return 0;
diff --git a/moses/src/PhraseDictionaryDynSuffixArray.h b/moses/src/PhraseDictionaryDynSuffixArray.h
index 8449e3e09..dab84ed2a 100644
--- a/moses/src/PhraseDictionaryDynSuffixArray.h
+++ b/moses/src/PhraseDictionaryDynSuffixArray.h
@@ -32,7 +32,7 @@ public:
void CleanUp(const InputType &source);
void insertSnt(string&, string&, string&);
void deleteSnt(unsigned, unsigned);
- ChartRuleLookupManager *CreateRuleLookupManager(const InputType&, const ChartCellCollection&);
+ ChartRuleLookupManager *CreateRuleLookupManager(const InputType&, const ChartCellCollectionBase&);
private:
BilingualDynSuffixArray *m_biSA;
std::vector<float> m_weight;
diff --git a/moses/src/PhraseDictionaryMemory.h b/moses/src/PhraseDictionaryMemory.h
index dad7f4a9b..5c5c2158b 100644
--- a/moses/src/PhraseDictionaryMemory.h
+++ b/moses/src/PhraseDictionaryMemory.h
@@ -64,7 +64,7 @@ public:
virtual ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &) {
+ const ChartCellCollectionBase &) {
CHECK(false);
return 0;
}
diff --git a/moses/src/PhraseDictionaryTreeAdaptor.h b/moses/src/PhraseDictionaryTreeAdaptor.h
index 97c7d1d3b..a4ef19013 100644
--- a/moses/src/PhraseDictionaryTreeAdaptor.h
+++ b/moses/src/PhraseDictionaryTreeAdaptor.h
@@ -64,7 +64,7 @@ public:
virtual ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &) {
+ const ChartCellCollectionBase &) {
CHECK(false);
return 0;
}
diff --git a/moses/src/RuleCubeItem.cpp b/moses/src/RuleCubeItem.cpp
index ec914e5ee..a25c841c6 100644
--- a/moses/src/RuleCubeItem.cpp
+++ b/moses/src/RuleCubeItem.cpp
@@ -96,7 +96,7 @@ void RuleCubeItem::CreateHypothesisDimensions(const StackVec &stackVec)
{
for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end();
++p) {
- const HypoList *stack = *p;
+ const HypoList *stack = (*p)->GetStack().cube;
assert(stack);
// there have to be hypothesis with the desired non-terminal
diff --git a/moses/src/RuleTable/Loader.h b/moses/src/RuleTable/Loader.h
index fac8900bd..7ca0c339f 100644
--- a/moses/src/RuleTable/Loader.h
+++ b/moses/src/RuleTable/Loader.h
@@ -40,7 +40,7 @@ class RuleTableLoader
virtual bool Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
diff --git a/moses/src/RuleTable/LoaderCompact.cpp b/moses/src/RuleTable/LoaderCompact.cpp
index f8d8baa13..7c3c9b739 100644
--- a/moses/src/RuleTable/LoaderCompact.cpp
+++ b/moses/src/RuleTable/LoaderCompact.cpp
@@ -36,7 +36,7 @@ namespace Moses
bool RuleTableLoaderCompact::Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t /* tableLimit */,
const LMList &languageModels,
@@ -45,6 +45,7 @@ bool RuleTableLoaderCompact::Load(const std::vector<FactorType> &input,
{
PrintUserTime("Start loading compact rule table");
+ InputFileStream inStream(inFile);
LineReader reader(inStream);
// Read and check version number.
diff --git a/moses/src/RuleTable/LoaderCompact.h b/moses/src/RuleTable/LoaderCompact.h
index 42453ac1c..ce26eee0f 100644
--- a/moses/src/RuleTable/LoaderCompact.h
+++ b/moses/src/RuleTable/LoaderCompact.h
@@ -41,7 +41,7 @@ class RuleTableLoaderCompact : public RuleTableLoader
public:
bool Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
diff --git a/moses/src/RuleTable/LoaderHiero.cpp b/moses/src/RuleTable/LoaderHiero.cpp
index db43b2958..0eb8cadc1 100644
--- a/moses/src/RuleTable/LoaderHiero.cpp
+++ b/moses/src/RuleTable/LoaderHiero.cpp
@@ -15,7 +15,7 @@ namespace Moses {
bool RuleTableLoaderHiero::Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
@@ -24,7 +24,7 @@ bool RuleTableLoaderHiero::Load(const std::vector<FactorType> &input,
{
bool ret = RuleTableLoaderStandard::Load(HieroFormat
,input, output
- ,inStream, weight
+ ,inFile, weight
,tableLimit, languageModels
,wpProducer, ruleTable);
return ret;
diff --git a/moses/src/RuleTable/LoaderHiero.h b/moses/src/RuleTable/LoaderHiero.h
index 4a74f90b8..3f77b765c 100644
--- a/moses/src/RuleTable/LoaderHiero.h
+++ b/moses/src/RuleTable/LoaderHiero.h
@@ -19,7 +19,7 @@ class RuleTableLoaderHiero : public RuleTableLoaderStandard
public:
bool Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
diff --git a/moses/src/RuleTable/LoaderStandard.cpp b/moses/src/RuleTable/LoaderStandard.cpp
index 5aa5df255..09b6b4939 100644
--- a/moses/src/RuleTable/LoaderStandard.cpp
+++ b/moses/src/RuleTable/LoaderStandard.cpp
@@ -23,7 +23,9 @@
#include <string>
#include <iterator>
#include <algorithm>
+#include <iostream>
#include <sys/stat.h>
+#include <stdlib.h>
#include "RuleTable/Trie.h"
#include "FactorCollection.h"
#include "Word.h"
@@ -34,6 +36,10 @@
#include "UserMessage.h"
#include "ChartTranslationOptionList.h"
#include "FactorCollection.h"
+#include "util/file_piece.hh"
+#include "util/string_piece.hh"
+#include "util/tokenize_piece.hh"
+
using namespace std;
@@ -41,7 +47,7 @@ namespace Moses
{
bool RuleTableLoaderStandard::Load(const std::vector<FactorType> &input
, const std::vector<FactorType> &output
- , std::istream &inStream
+ , const std::string &inFile
, const std::vector<float> &weight
, size_t tableLimit
, const LMList &languageModels
@@ -50,7 +56,7 @@ bool RuleTableLoaderStandard::Load(const std::vector<FactorType> &input
{
bool ret = Load(MosesFormat
,input, output
- ,inStream, weight
+ ,inFile, weight
,tableLimit, languageModels
,wpProducer, ruleTable);
return ret;
@@ -107,7 +113,7 @@ void ReformateHieroScore(string &scoreString)
scoreString = Join(" ", toks);
}
-string *ReformatHieroRule(const string &lineOrig)
+void ReformatHieroRule(const string &lineOrig, string &out)
{
vector<string> tokens;
vector<float> scoreVector;
@@ -137,13 +143,13 @@ string *ReformatHieroRule(const string &lineOrig)
<< scoreString << " ||| "
<< align.str();
- return new string(ret.str());
+ out = ret.str();
}
bool RuleTableLoaderStandard::Load(FormatType format
, const std::vector<FactorType> &input
, const std::vector<FactorType> &output
- , std::istream &inStream
+ , const std::string &inFile
, const std::vector<float> &weight
, size_t /* tableLimit */
, const LMList &languageModels
@@ -155,49 +161,55 @@ bool RuleTableLoaderStandard::Load(FormatType format
const StaticData &staticData = StaticData::Instance();
const std::string& factorDelimiter = staticData.GetFactorDelimiter();
-
string lineOrig;
size_t count = 0;
- while(getline(inStream, lineOrig)) {
- const string *line;
- if (format == HieroFormat) { // reformat line
- line = ReformatHieroRule(lineOrig);
- }
- else
- { // do nothing to format of line
- line = &lineOrig;
- }
-
- vector<string> tokens;
- vector<float> scoreVector;
+ std::ostream *progress = NULL;
+ IFVERBOSE(1) progress = &std::cerr;
+ util::FilePiece in(inFile.c_str(), progress);
- TokenizeMultiCharSeparator(tokens, *line , "|||" );
+ // reused variables
+ vector<float> scoreVector;
+ StringPiece line;
+ std::string hiero_before, hiero_after;
+
+ while(true) {
+ try {
+ line = in.ReadLine();
+ } catch (const util::EndOfFileException &e) { break; }
+
+ if (format == HieroFormat) { // inefficiently reformat line
+ hiero_before.assign(line.data(), line.size());
+ ReformatHieroRule(hiero_before, hiero_after);
+ line = hiero_after;
+ }
- if (tokens.size() != 4 && tokens.size() != 5) {
+ util::TokenIter<util::MultiCharacter> pipes(line, "|||");
+ StringPiece sourcePhraseString(*pipes);
+ StringPiece targetPhraseString(*++pipes);
+ StringPiece scoreString(*++pipes);
+ StringPiece alignString(*++pipes);
+ StringPiece ruleCountString(*++pipes);
+
+ if (++pipes) {
stringstream strme;
strme << "Syntax error at " << ruleTable.GetFilePath() << ":" << count;
UserMessage::Add(strme.str());
abort();
}
- if (tokens.size() == 4) {
- tokens.push_back("1 1"); //dummy rule count for glue rules
- }
-
- const string &sourcePhraseString = tokens[0]
- , &targetPhraseString = tokens[1]
- , &scoreString = tokens[2]
- , &alignString = tokens[3]
- , &ruleCountString = tokens[4];
-
bool isLHSEmpty = (sourcePhraseString.find_first_not_of(" \t", 0) == string::npos);
if (isLHSEmpty && !staticData.IsWordDeletionEnabled()) {
TRACE_ERR( ruleTable.GetFilePath() << ":" << count << ": pt entry contains empty target, skipping\n");
continue;
}
- Tokenize<float>(scoreVector, scoreString);
+ scoreVector.clear();
+ for (util::TokenIter<util::AnyCharacter, true> s(scoreString, " \t"); s; ++s) {
+ char *err_ind;
+ scoreVector.push_back(strtod(s->data(), &err_ind));
+ UTIL_THROW_IF(err_ind == s->data(), util::Exception, "Bad score " << *s << " on line " << count);
+ }
const size_t numScoreComponents = ruleTable.GetFeature()->GetNumScoreComponents();
if (scoreVector.size() != numScoreComponents) {
stringstream strme;
@@ -206,7 +218,6 @@ bool RuleTableLoaderStandard::Load(FormatType format
UserMessage::Add(strme.str());
abort();
}
- CHECK(scoreVector.size() == numScoreComponents);
// parse source & find pt node
@@ -226,9 +237,7 @@ bool RuleTableLoaderStandard::Load(FormatType format
targetPhrase->SetAlignmentInfo(alignString, sourcePhrase);
targetPhrase->SetTargetLHS(targetLHS);
- if (tokens.size() == 5) {
- targetPhrase->SetRuleCount(ruleCountString, scoreVector);
- }
+ targetPhrase->SetRuleCount(ruleCountString, scoreVector);
//targetPhrase->SetDebugOutput(string("New Format pt ") + line);
// component score, for n-best output
@@ -241,13 +250,6 @@ bool RuleTableLoaderStandard::Load(FormatType format
phraseColl.Add(targetPhrase);
count++;
-
- if (format == HieroFormat) { // reformat line
- delete line;
- }
- else
- { // do nothing
- }
}
// sort and prune each target phrase collection
diff --git a/moses/src/RuleTable/LoaderStandard.h b/moses/src/RuleTable/LoaderStandard.h
index 6fea42794..e0940fdd9 100644
--- a/moses/src/RuleTable/LoaderStandard.h
+++ b/moses/src/RuleTable/LoaderStandard.h
@@ -32,7 +32,7 @@ protected:
bool Load(FormatType format,
const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
@@ -41,7 +41,7 @@ protected:
public:
bool Load(const std::vector<FactorType> &input,
const std::vector<FactorType> &output,
- std::istream &inStream,
+ const std::string &inFile,
const std::vector<float> &weight,
size_t tableLimit,
const LMList &languageModels,
diff --git a/moses/src/RuleTable/PhraseDictionaryALSuffixArray.cpp b/moses/src/RuleTable/PhraseDictionaryALSuffixArray.cpp
index 21acbcab0..709bb721a 100644
--- a/moses/src/RuleTable/PhraseDictionaryALSuffixArray.cpp
+++ b/moses/src/RuleTable/PhraseDictionaryALSuffixArray.cpp
@@ -59,13 +59,10 @@ void PhraseDictionaryALSuffixArray::InitializeForInput(InputType const& source)
string grammarFile = GetFilePath() + "/grammar.out." + SPrint(translationId) + ".gz";
- // data from file
- InputFileStream inFile(grammarFile);
-
std::auto_ptr<RuleTableLoader> loader =
RuleTableLoaderFactory::Create(grammarFile);
std::vector<float> weightT = StaticData::Instance().GetWeights(GetFeature());
- bool ret = loader->Load(*m_input, *m_output, inFile, weightT, m_tableLimit,
+ bool ret = loader->Load(*m_input, *m_output, grammarFile, weightT, m_tableLimit,
*m_languageModels, m_wpProducer, *this);
CHECK(ret);
diff --git a/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.cpp b/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.cpp
index d3a9bb67b..6d23333ad 100644
--- a/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.cpp
+++ b/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.cpp
@@ -84,7 +84,7 @@ namespace Moses
ChartRuleLookupManager *PhraseDictionaryFuzzyMatch::CreateRuleLookupManager(
const InputType &sentence,
- const ChartCellCollection &cellCollection)
+ const ChartCellCollectionBase &cellCollection)
{
return new ChartRuleLookupManagerMemoryPerSentence(sentence, cellCollection, *this);
}
diff --git a/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.h b/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.h
index 8679bdd1c..ed5343f8e 100644
--- a/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.h
+++ b/moses/src/RuleTable/PhraseDictionaryFuzzyMatch.h
@@ -54,13 +54,14 @@ namespace Moses
ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &);
+ const ChartCellCollectionBase &);
void InitializeForInput(InputType const& inputSentence);
void CleanUp(const InputType& source);
virtual const TargetPhraseCollection *GetTargetPhraseCollection(const Phrase& src) const
{
assert(false);
+ return NULL;
}
virtual DecodeType GetDecodeType() const
{
diff --git a/moses/src/RuleTable/PhraseDictionaryOnDisk.cpp b/moses/src/RuleTable/PhraseDictionaryOnDisk.cpp
index 9b0124605..013ad60b8 100644
--- a/moses/src/RuleTable/PhraseDictionaryOnDisk.cpp
+++ b/moses/src/RuleTable/PhraseDictionaryOnDisk.cpp
@@ -91,7 +91,7 @@ void PhraseDictionaryOnDisk::LoadTargetLookup()
ChartRuleLookupManager *PhraseDictionaryOnDisk::CreateRuleLookupManager(
const InputType &sentence,
- const ChartCellCollection &cellCollection)
+ const ChartCellCollectionBase &cellCollection)
{
return new ChartRuleLookupManagerOnDisk(sentence, cellCollection, *this,
m_dbWrapper, m_languageModels,
diff --git a/moses/src/RuleTable/PhraseDictionaryOnDisk.h b/moses/src/RuleTable/PhraseDictionaryOnDisk.h
index f9dcf3a8f..1108ab9a6 100644
--- a/moses/src/RuleTable/PhraseDictionaryOnDisk.h
+++ b/moses/src/RuleTable/PhraseDictionaryOnDisk.h
@@ -82,7 +82,7 @@ public:
virtual ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &);
+ const ChartCellCollectionBase &);
};
} // namespace Moses
diff --git a/moses/src/RuleTable/PhraseDictionarySCFG.cpp b/moses/src/RuleTable/PhraseDictionarySCFG.cpp
index e000deee4..8b4edf64f 100644
--- a/moses/src/RuleTable/PhraseDictionarySCFG.cpp
+++ b/moses/src/RuleTable/PhraseDictionarySCFG.cpp
@@ -90,7 +90,7 @@ PhraseDictionaryNodeSCFG &PhraseDictionarySCFG::GetOrCreateNode(const Phrase &so
ChartRuleLookupManager *PhraseDictionarySCFG::CreateRuleLookupManager(
const InputType &sentence,
- const ChartCellCollection &cellCollection)
+ const ChartCellCollectionBase &cellCollection)
{
return new ChartRuleLookupManagerMemory(sentence, cellCollection, *this);
}
diff --git a/moses/src/RuleTable/PhraseDictionarySCFG.h b/moses/src/RuleTable/PhraseDictionarySCFG.h
index 9e3fcf446..7825801f3 100644
--- a/moses/src/RuleTable/PhraseDictionarySCFG.h
+++ b/moses/src/RuleTable/PhraseDictionarySCFG.h
@@ -45,7 +45,7 @@ class PhraseDictionarySCFG : public RuleTableTrie
ChartRuleLookupManager *CreateRuleLookupManager(
const InputType &,
- const ChartCellCollection &);
+ const ChartCellCollectionBase &);
TO_STRING();
diff --git a/moses/src/RuleTable/Trie.cpp b/moses/src/RuleTable/Trie.cpp
index 017d39826..1fc404b7c 100644
--- a/moses/src/RuleTable/Trie.cpp
+++ b/moses/src/RuleTable/Trie.cpp
@@ -43,16 +43,13 @@ bool RuleTableTrie::Load(const std::vector<FactorType> &input,
m_filePath = filePath;
m_tableLimit = tableLimit;
- // data from file
- InputFileStream inFile(filePath);
-
std::auto_ptr<Moses::RuleTableLoader> loader =
Moses::RuleTableLoaderFactory::Create(filePath);
if (!loader.get())
{
return false;
}
- bool ret = loader->Load(input, output, inFile, weight, tableLimit,
+ bool ret = loader->Load(input, output, filePath, weight, tableLimit,
languageModels, wpProducer, *this);
return ret;
}
diff --git a/moses/src/RuleTable/UTrie.cpp b/moses/src/RuleTable/UTrie.cpp
index d436f4231..c1ea7686f 100644
--- a/moses/src/RuleTable/UTrie.cpp
+++ b/moses/src/RuleTable/UTrie.cpp
@@ -78,7 +78,7 @@ UTrieNode &RuleTableUTrie::GetOrCreateNode(const Phrase &source,
ChartRuleLookupManager *RuleTableUTrie::CreateRuleLookupManager(
const InputType &sentence,
- const ChartCellCollection &cellCollection)
+ const ChartCellCollectionBase &cellCollection)
{
// FIXME This should be a parameter to CreateRuleLookupManager
size_t maxChartSpan = 0;
diff --git a/moses/src/RuleTable/UTrie.h b/moses/src/RuleTable/UTrie.h
index da8d6d90d..82595581a 100644
--- a/moses/src/RuleTable/UTrie.h
+++ b/moses/src/RuleTable/UTrie.h
@@ -50,7 +50,7 @@ class RuleTableUTrie : public RuleTableTrie
const UTrieNode &GetRootNode() const { return m_root; }
ChartRuleLookupManager *CreateRuleLookupManager(const InputType &,
- const ChartCellCollection &);
+ const ChartCellCollectionBase &);
private:
TargetPhraseCollection &GetOrCreateTargetPhraseCollection(
diff --git a/moses/src/Scope3Parser/Parser.cpp b/moses/src/Scope3Parser/Parser.cpp
index 54ab77236..6681b2502 100644
--- a/moses/src/Scope3Parser/Parser.cpp
+++ b/moses/src/Scope3Parser/Parser.cpp
@@ -39,7 +39,7 @@ namespace Moses
void Scope3Parser::GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl)
+ ChartParserCallback &outColl)
{
const size_t start = range.GetStartPos();
const size_t end = range.GetEndPos();
@@ -61,7 +61,7 @@ void Scope3Parser::GetChartRuleCollection(
} else { // Rule has at least one non-terminal.
varSpanNode.CalculateRanges(start, end, m_ranges);
m_latticeBuilder.Build(start, end, ruleNode, varSpanNode, m_ranges,
- this->GetCellCollection(), m_lattice,
+ *this, m_lattice,
m_quickCheckTable);
StackLatticeSearcher<MatchCallback> searcher(m_lattice, m_ranges);
UTrieNode::LabelMap::const_iterator p = labelMap.begin();
diff --git a/moses/src/Scope3Parser/Parser.h b/moses/src/Scope3Parser/Parser.h
index af466ec37..8e2299921 100644
--- a/moses/src/Scope3Parser/Parser.h
+++ b/moses/src/Scope3Parser/Parser.h
@@ -38,7 +38,7 @@ namespace Moses
{
class InputType;
-class ChartCellCollection;
+class ChartCellCollectionBase;
class ChartHypothesisCollection;
class WordsRange;
@@ -48,7 +48,7 @@ class Scope3Parser : public ChartRuleLookupManager
{
public:
Scope3Parser(const InputType &sentence,
- const ChartCellCollection &cellColl,
+ const ChartCellCollectionBase &cellColl,
const RuleTableUTrie &ruleTable,
size_t maxChartSpan)
: ChartRuleLookupManager(sentence, cellColl)
@@ -60,7 +60,7 @@ class Scope3Parser : public ChartRuleLookupManager
void GetChartRuleCollection(
const WordsRange &range,
- ChartTranslationOptionList &outColl);
+ ChartParserCallback &outColl);
private:
// Define a callback type for use by StackLatticeSearcher.
@@ -68,7 +68,7 @@ class Scope3Parser : public ChartRuleLookupManager
{
public:
MatchCallback(const WordsRange &range,
- ChartTranslationOptionList &out)
+ ChartParserCallback &out)
: m_range(range)
, m_out(out)
, m_tpc(NULL) {}
@@ -77,7 +77,7 @@ class Scope3Parser : public ChartRuleLookupManager
m_out.Add(*m_tpc, stackVec, m_range);
}
const WordsRange &m_range;
- ChartTranslationOptionList &m_out;
+ ChartParserCallback &m_out;
const TargetPhraseCollection *m_tpc;
};
diff --git a/moses/src/Scope3Parser/StackLatticeBuilder.cpp b/moses/src/Scope3Parser/StackLatticeBuilder.cpp
index 4afa1b999..711b08a23 100644
--- a/moses/src/Scope3Parser/StackLatticeBuilder.cpp
+++ b/moses/src/Scope3Parser/StackLatticeBuilder.cpp
@@ -19,8 +19,7 @@
#include "StackLatticeBuilder.h"
-#include "ChartCell.h"
-#include "ChartCellCollection.h"
+#include "ChartRuleLookupManager.h"
#include "RuleTable/UTrieNode.h"
#include "Scope3Parser/StackLattice.h"
#include "Scope3Parser/VarSpanNode.h"
@@ -34,7 +33,7 @@ void StackLatticeBuilder::Build(
const UTrieNode &ruleNode,
const VarSpanNode &varSpanNode,
const std::vector<VarSpanNode::NonTermRange> &ranges,
- const ChartCellCollection &chartCellColl,
+ const ChartRuleLookupManager &manager,
StackLattice &lattice,
std::vector<std::vector<bool> > &checkTable)
{
@@ -75,13 +74,11 @@ void StackLatticeBuilder::Build(
StackVec &stackVec = lattice[offset][index][span];
stackVec.clear();
stackVec.reserve(labelVec.size());
- const WordsRange range(start+offset, start+offset+span-1);
- const ChartCell &chartCell = chartCellColl.Get(range);
std::vector<bool>::iterator q = checkTable[index].begin();
for (std::vector<Word>::const_iterator p = labelVec.begin();
p != labelVec.end(); ++p) {
const Word &label = *p;
- const HypoList *stack = chartCell.GetSortedHypotheses(label);
+ const ChartCellLabel *stack = manager.GetTargetLabelSet(start+offset, start+offset+span-1).Find(label);
stackVec.push_back(stack);
*q++ = *q || static_cast<bool>(stack);
}
diff --git a/moses/src/Scope3Parser/StackLatticeBuilder.h b/moses/src/Scope3Parser/StackLatticeBuilder.h
index f17051dc2..5a8a988ba 100644
--- a/moses/src/Scope3Parser/StackLatticeBuilder.h
+++ b/moses/src/Scope3Parser/StackLatticeBuilder.h
@@ -37,7 +37,7 @@ class StackLatticeBuilder
void Build(int, int, const UTrieNode &, const VarSpanNode &,
const std::vector<VarSpanNode::NonTermRange> &,
- const ChartCellCollection &, StackLattice &,
+ const ChartRuleLookupManager &, StackLattice &,
std::vector<std::vector<bool> > &);
};
diff --git a/moses/src/Scope3Parser/StackLatticeSearcher.h b/moses/src/Scope3Parser/StackLatticeSearcher.h
index ab7ecdc10..98b4825de 100644
--- a/moses/src/Scope3Parser/StackLatticeSearcher.h
+++ b/moses/src/Scope3Parser/StackLatticeSearcher.h
@@ -62,7 +62,7 @@ class StackLatticeSearcher
const std::vector<StackVec> &spanVec = m_lattice[offset][index];
for (size_t j = minSpan; j <= maxSpan; ++j) {
- const HypoList *stack = spanVec[j][(*m_labels)[index]];
+ const ChartCellLabel *stack = spanVec[j][(*m_labels)[index]];
if (!stack) {
continue;
}
diff --git a/moses/src/Sentence.cpp b/moses/src/Sentence.cpp
index b19e2e591..b840281db 100644
--- a/moses/src/Sentence.cpp
+++ b/moses/src/Sentence.cpp
@@ -39,7 +39,7 @@ Sentence::Sentence()
, InputType()
{
const StaticData& staticData = StaticData::Instance();
- if (staticData.GetSearchAlgorithm() == ChartDecoding) {
+ if (staticData.IsChart()) {
m_defaultLabelSet.insert(StaticData::Instance().GetInputDefaultNonTerminal());
}
}
@@ -126,7 +126,7 @@ int Sentence::Read(std::istream& in,const std::vector<FactorType>& factorOrder)
}
Phrase::CreateFromString(factorOrder, line, factorDelimiter);
- if (staticData.GetSearchAlgorithm() == ChartDecoding) {
+ if (staticData.IsChart()) {
InitStartEndWord();
}
diff --git a/moses/src/StackVec.h b/moses/src/StackVec.h
index 4641e69ad..07c508c38 100644
--- a/moses/src/StackVec.h
+++ b/moses/src/StackVec.h
@@ -19,13 +19,13 @@
#pragma once
-#include "HypoList.h"
-
#include <vector>
namespace Moses
{
-typedef std::vector<const HypoList *> StackVec;
+class ChartCellLabel;
+
+typedef std::vector<const ChartCellLabel*> StackVec;
}
diff --git a/moses/src/StaticData.cpp b/moses/src/StaticData.cpp
index 36e8757c7..da9ee54b0 100644
--- a/moses/src/StaticData.cpp
+++ b/moses/src/StaticData.cpp
@@ -137,7 +137,7 @@ bool StaticData::LoadData(Parameter *parameter)
m_searchAlgorithm = (m_parameter->GetParam("search-algorithm").size() > 0) ?
(SearchAlgorithm) Scan<size_t>(m_parameter->GetParam("search-algorithm")[0]) : Normal;
- if (m_searchAlgorithm == ChartDecoding)
+ if (IsChart())
LoadChartDecodingParameters();
else
LoadPhraseBasedParameters();
@@ -613,7 +613,7 @@ bool StaticData::LoadData(Parameter *parameter)
return false;
}
- if (m_searchAlgorithm == ChartDecoding) {
+ if (IsChart()) {
//insert some null distortion score producers
m_distortionScoreProducers.assign(tsConfig.size(), NULL);
} else {
@@ -1533,7 +1533,7 @@ bool StaticData::LoadDecodeGraphs()
CHECK(decodeStep);
if (m_decodeGraphs.size() < decodeGraphInd + 1) {
DecodeGraph *decodeGraph;
- if (m_searchAlgorithm == ChartDecoding) {
+ if (IsChart()) {
size_t maxChartSpan = (decodeGraphInd < maxChartSpans.size()) ? maxChartSpans[decodeGraphInd] : DEFAULT_MAX_CHART_SPAN;
cerr << "max-chart-span: " << maxChartSpans[decodeGraphInd] << endl;
decodeGraph = new DecodeGraph(m_decodeGraphs.size(), maxChartSpan);
diff --git a/moses/src/StaticData.h b/moses/src/StaticData.h
index 4d69bf95d..6391fb995 100644
--- a/moses/src/StaticData.h
+++ b/moses/src/StaticData.h
@@ -498,6 +498,9 @@ public:
SearchAlgorithm GetSearchAlgorithm() const {
return m_searchAlgorithm;
}
+ bool IsChart() const {
+ return m_searchAlgorithm == ChartDecoding || m_searchAlgorithm == ChartIncremental;
+ }
LMList GetLMList() const {
return m_languageModel;
}
diff --git a/moses/src/TypeDef.h b/moses/src/TypeDef.h
index a16f49fc2..450cb410b 100644
--- a/moses/src/TypeDef.h
+++ b/moses/src/TypeDef.h
@@ -173,6 +173,7 @@ enum SearchAlgorithm {
,CubeGrowing = 2
,ChartDecoding= 3
,NormalBatch = 4
+ ,ChartIncremental = 5
};
enum SourceLabelOverlap {
diff --git a/moses/src/Word.cpp b/moses/src/Word.cpp
index 3659fa0e3..c23e8de8c 100644
--- a/moses/src/Word.cpp
+++ b/moses/src/Word.cpp
@@ -25,6 +25,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "Word.h"
#include "TypeDef.h"
#include "StaticData.h" // needed to determine the FactorDelimiter
+#include "util/tokenize_piece.hh"
using namespace std;
@@ -96,24 +97,16 @@ std::string Word::GetString(FactorType factorType) const
void Word::CreateFromString(FactorDirection direction
, const std::vector<FactorType> &factorOrder
- , const std::string &str
+ , const StringPiece &str
, bool isNonTerminal)
{
FactorCollection &factorCollection = FactorCollection::Instance();
- vector<string> wordVec;
- const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter();
- TokenizeMultiCharSeparator(wordVec, str, factorDelimiter);
- //Tokenize(wordVec, str, "|");
- if (!isNonTerminal)
- CHECK(wordVec.size() <= factorOrder.size());
-
- const Factor *factor;
- for (size_t ind = 0; ind < wordVec.size(); ++ind) {
- FactorType factorType = factorOrder[ind];
- factor = factorCollection.AddFactor(direction, factorType, wordVec[ind]);
- m_factorArray[factorType] = factor;
+ util::TokenIter<util::MultiCharacter> fit(str, StaticData::Instance().GetFactorDelimiter());
+ for (size_t ind = 0; ind < factorOrder.size() && fit; ++ind, ++fit) {
+ m_factorArray[factorOrder[ind]] = factorCollection.AddFactor(*fit);
}
+ CHECK(!fit);
// assume term/non-term same for all factors
m_isNonTerminal = isNonTerminal;
diff --git a/moses/src/Word.h b/moses/src/Word.h
index 872b90e13..70875d75c 100644
--- a/moses/src/Word.h
+++ b/moses/src/Word.h
@@ -32,6 +32,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "TypeDef.h"
#include "Factor.h"
#include "Util.h"
+#include "util/string_piece.hh"
namespace Moses
{
@@ -133,7 +134,7 @@ public:
void CreateFromString(FactorDirection direction
, const std::vector<FactorType> &factorOrder
- , const std::string &str
+ , const StringPiece &str
, bool isNonTerminal);
void CreateUnknownWord(const Word &sourceWord);
diff --git a/scripts/generic/trainlm-irst.perl b/scripts/generic/trainlm-irst.perl
index d8c6ce2a5..6fac9767f 100755
--- a/scripts/generic/trainlm-irst.perl
+++ b/scripts/generic/trainlm-irst.perl
@@ -71,11 +71,11 @@ print "extension is $ext\n";
if ($ext eq "gz")
{
- $cmd = "$irstPath/compile-lm $tempPath/iarpa.gz --text yes /dev/stdout | gzip -c > $lmPath";
+ $cmd = "$irstPath/compile-lm --text $tempPath/iarpa.gz /dev/stdout | gzip -c > $lmPath";
}
else
{
- $cmd = "$irstPath/compile-lm $tempPath/iarpa.gz --text yes $lmPath";
+ $cmd = "$irstPath/compile-lm --text $tempPath/iarpa.gz $lmPath";
}
print STDERR "EXECUTING $cmd\n";
diff --git a/search/Jamfile b/search/Jamfile
new file mode 100644
index 000000000..e8b14363d
--- /dev/null
+++ b/search/Jamfile
@@ -0,0 +1,5 @@
+lib search : weights.cc vertex.cc vertex_generator.cc edge_queue.cc edge_generator.cc rule.cc ../lm//kenlm ../util//kenutil /top//boost_system : : : <include>.. ;
+
+import testing ;
+
+unit-test weights_test : weights_test.cc search /top//boost_unit_test_framework ;
diff --git a/search/arity.hh b/search/arity.hh
new file mode 100644
index 000000000..09c2c671d
--- /dev/null
+++ b/search/arity.hh
@@ -0,0 +1,8 @@
+#ifndef SEARCH_ARITY__
+#define SEARCH_ARITY__
+namespace search {
+
+const unsigned int kMaxArity = 2;
+
+} // namespace search
+#endif // SEARCH_ARITY__
diff --git a/search/config.hh b/search/config.hh
new file mode 100644
index 000000000..ef8e2354a
--- /dev/null
+++ b/search/config.hh
@@ -0,0 +1,25 @@
+#ifndef SEARCH_CONFIG__
+#define SEARCH_CONFIG__
+
+#include "search/weights.hh"
+#include "util/string_piece.hh"
+
+namespace search {
+
+class Config {
+ public:
+ Config(const Weights &weights, unsigned int pop_limit) :
+ weights_(weights), pop_limit_(pop_limit) {}
+
+ const Weights &GetWeights() const { return weights_; }
+
+ unsigned int PopLimit() const { return pop_limit_; }
+
+ private:
+ Weights weights_;
+ unsigned int pop_limit_;
+};
+
+} // namespace search
+
+#endif // SEARCH_CONFIG__
diff --git a/search/context.hh b/search/context.hh
new file mode 100644
index 000000000..27940053b
--- /dev/null
+++ b/search/context.hh
@@ -0,0 +1,65 @@
+#ifndef SEARCH_CONTEXT__
+#define SEARCH_CONTEXT__
+
+#include "lm/model.hh"
+#include "search/config.hh"
+#include "search/final.hh"
+#include "search/types.hh"
+#include "search/vertex.hh"
+#include "util/exception.hh"
+
+#include <boost/pool/object_pool.hpp>
+#include <boost/ptr_container/ptr_vector.hpp>
+
+#include <vector>
+
+namespace search {
+
+class Weights;
+
+class ContextBase {
+ public:
+ explicit ContextBase(const Config &config) : pop_limit_(config.PopLimit()), weights_(config.GetWeights()) {}
+
+ Final *NewFinal() {
+ Final *ret = final_pool_.construct();
+ assert(ret);
+ return ret;
+ }
+
+ VertexNode *NewVertexNode() {
+ VertexNode *ret = vertex_node_pool_.construct();
+ assert(ret);
+ return ret;
+ }
+
+ void DeleteVertexNode(VertexNode *node) {
+ vertex_node_pool_.destroy(node);
+ }
+
+ unsigned int PopLimit() const { return pop_limit_; }
+
+ const Weights &GetWeights() const { return weights_; }
+
+ private:
+ boost::object_pool<Final> final_pool_;
+ boost::object_pool<VertexNode> vertex_node_pool_;
+
+ unsigned int pop_limit_;
+
+ const Weights &weights_;
+};
+
+template <class Model> class Context : public ContextBase {
+ public:
+ Context(const Config &config, const Model &model) : ContextBase(config), model_(model) {}
+
+ const Model &LanguageModel() const { return model_; }
+
+ private:
+ const Model &model_;
+};
+
+} // namespace search
+
+#endif // SEARCH_CONTEXT__
diff --git a/search/edge.hh b/search/edge.hh
new file mode 100644
index 000000000..77ab0ade6
--- /dev/null
+++ b/search/edge.hh
@@ -0,0 +1,31 @@
+#ifndef SEARCH_EDGE__
+#define SEARCH_EDGE__
+
+#include "lm/state.hh"
+#include "search/arity.hh"
+#include "search/rule.hh"
+#include "search/types.hh"
+#include "search/vertex.hh"
+
+#include <queue>
+
+namespace search {
+
+struct PartialEdge {
+ Score score;
+ // Terminals
+ lm::ngram::ChartState between[kMaxArity + 1];
+ // Non-terminals
+ PartialVertex nt[kMaxArity];
+
+ const lm::ngram::ChartState &CompletedState() const {
+ return between[0];
+ }
+
+ bool operator<(const PartialEdge &other) const {
+ return score < other.score;
+ }
+};
+
+} // namespace search
+#endif // SEARCH_EDGE__
diff --git a/search/edge_generator.cc b/search/edge_generator.cc
new file mode 100644
index 000000000..56239dfbb
--- /dev/null
+++ b/search/edge_generator.cc
@@ -0,0 +1,120 @@
+#include "search/edge_generator.hh"
+
+#include "lm/left.hh"
+#include "lm/partial.hh"
+#include "search/context.hh"
+#include "search/vertex.hh"
+#include "search/vertex_generator.hh"
+
+#include <numeric>
+
+namespace search {
+
+EdgeGenerator::EdgeGenerator(PartialEdge &root, unsigned char arity, Note note) : arity_(arity), note_(note) {
+/* for (unsigned char i = 0; i < edge.Arity(); ++i) {
+ root.nt[i] = edge.GetVertex(i).RootPartial();
+ }
+ for (unsigned char i = edge.Arity(); i < 2; ++i) {
+ root.nt[i] = kBlankPartialVertex;
+ }*/
+ generate_.push(&root);
+ top_score_ = root.score;
+}
+
+namespace {
+
+template <class Model> float FastScore(const Context<Model> &context, unsigned char victim, unsigned char arity, const PartialEdge &previous, PartialEdge &update) {
+ memcpy(update.between, previous.between, sizeof(lm::ngram::ChartState) * (arity + 1));
+
+ float ret = 0.0;
+ lm::ngram::ChartState *before, *after;
+ if (victim == 0) {
+ before = &update.between[0];
+ after = &update.between[(arity == 2 && previous.nt[1].Complete()) ? 2 : 1];
+ } else {
+ assert(victim == 1);
+ assert(arity == 2);
+ before = &update.between[previous.nt[0].Complete() ? 0 : 1];
+ after = &update.between[2];
+ }
+ const lm::ngram::ChartState &previous_reveal = previous.nt[victim].State();
+ const PartialVertex &update_nt = update.nt[victim];
+ const lm::ngram::ChartState &update_reveal = update_nt.State();
+ float just_after = 0.0;
+ if ((update_reveal.left.length > previous_reveal.left.length) || (update_reveal.left.full && !previous_reveal.left.full)) {
+ just_after += lm::ngram::RevealAfter(context.LanguageModel(), before->left, before->right, update_reveal.left, previous_reveal.left.length);
+ }
+ if ((update_reveal.right.length > previous_reveal.right.length) || (update_nt.RightFull() && !previous.nt[victim].RightFull())) {
+ ret += lm::ngram::RevealBefore(context.LanguageModel(), update_reveal.right, previous_reveal.right.length, update_nt.RightFull(), after->left, after->right);
+ }
+ if (update_nt.Complete()) {
+ if (update_reveal.left.full) {
+ before->left.full = true;
+ } else {
+ assert(update_reveal.left.length == update_reveal.right.length);
+ ret += lm::ngram::Subsume(context.LanguageModel(), before->left, before->right, after->left, after->right, update_reveal.left.length);
+ }
+ if (victim == 0) {
+ update.between[0].right = after->right;
+ } else {
+ update.between[2].left = before->left;
+ }
+ }
+ return previous.score + (ret + just_after) * context.GetWeights().LM();
+}
+
+} // namespace
+
+template <class Model> PartialEdge *EdgeGenerator::Pop(Context<Model> &context, boost::pool<> &partial_edge_pool) {
+ assert(!generate_.empty());
+ PartialEdge &top = *generate_.top();
+ generate_.pop();
+ unsigned int victim = 0;
+ unsigned char lowest_length = 255;
+ for (unsigned char i = 0; i != arity_; ++i) {
+ if (!top.nt[i].Complete() && top.nt[i].Length() < lowest_length) {
+ lowest_length = top.nt[i].Length();
+ victim = i;
+ }
+ }
+ if (lowest_length == 255) {
+ // All states report complete.
+ top.between[0].right = top.between[arity_].right;
+ // Now top.between[0] is the full edge state.
+ top_score_ = generate_.empty() ? -kScoreInf : generate_.top()->score;
+ return &top;
+ }
+
+ unsigned int stay = !victim;
+ PartialEdge &continuation = *static_cast<PartialEdge*>(partial_edge_pool.malloc());
+ float old_bound = top.nt[victim].Bound();
+ // The alternate's score will change because alternate.nt[victim] changes.
+ bool split = top.nt[victim].Split(continuation.nt[victim]);
+ // top is now the alternate.
+
+ continuation.nt[stay] = top.nt[stay];
+ continuation.score = FastScore(context, victim, arity_, top, continuation);
+ // TODO: dedupe?
+ generate_.push(&continuation);
+
+ if (split) {
+ // We have an alternate.
+ top.score += top.nt[victim].Bound() - old_bound;
+ // TODO: dedupe?
+ generate_.push(&top);
+ } else {
+ partial_edge_pool.free(&top);
+ }
+
+ top_score_ = generate_.top()->score;
+ return NULL;
+}
+
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::RestProbingModel> &context, boost::pool<> &partial_edge_pool);
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::ProbingModel> &context, boost::pool<> &partial_edge_pool);
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::TrieModel> &context, boost::pool<> &partial_edge_pool);
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::QuantTrieModel> &context, boost::pool<> &partial_edge_pool);
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::ArrayTrieModel> &context, boost::pool<> &partial_edge_pool);
+template PartialEdge *EdgeGenerator::Pop(Context<lm::ngram::QuantArrayTrieModel> &context, boost::pool<> &partial_edge_pool);
+
+} // namespace search
diff --git a/search/edge_generator.hh b/search/edge_generator.hh
new file mode 100644
index 000000000..875ccc5ea
--- /dev/null
+++ b/search/edge_generator.hh
@@ -0,0 +1,58 @@
+#ifndef SEARCH_EDGE_GENERATOR__
+#define SEARCH_EDGE_GENERATOR__
+
+#include "search/edge.hh"
+#include "search/note.hh"
+
+#include <boost/pool/pool.hpp>
+#include <boost/unordered_map.hpp>
+
+#include <functional>
+#include <queue>
+
+namespace lm {
+namespace ngram {
+class ChartState;
+} // namespace ngram
+} // namespace lm
+
+namespace search {
+
+template <class Model> class Context;
+
+class VertexGenerator;
+
+struct PartialEdgePointerLess : std::binary_function<const PartialEdge *, const PartialEdge *, bool> {
+ bool operator()(const PartialEdge *first, const PartialEdge *second) const {
+ return *first < *second;
+ }
+};
+
+class EdgeGenerator {
+ public:
+ EdgeGenerator(PartialEdge &root, unsigned char arity, Note note);
+
+ Score TopScore() const {
+ return top_score_;
+ }
+
+ Note GetNote() const {
+ return note_;
+ }
+
+ // Pop. If there's a complete hypothesis, return it. Otherwise return NULL.
+ template <class Model> PartialEdge *Pop(Context<Model> &context, boost::pool<> &partial_edge_pool);
+
+ private:
+ Score top_score_;
+
+ unsigned char arity_;
+
+ typedef std::priority_queue<PartialEdge*, std::vector<PartialEdge*>, PartialEdgePointerLess> Generate;
+ Generate generate_;
+
+ Note note_;
+};
+
+} // namespace search
+#endif // SEARCH_EDGE_GENERATOR__
diff --git a/search/edge_queue.cc b/search/edge_queue.cc
new file mode 100644
index 000000000..e3ae6ebf7
--- /dev/null
+++ b/search/edge_queue.cc
@@ -0,0 +1,25 @@
+#include "search/edge_queue.hh"
+
+#include "lm/left.hh"
+#include "search/context.hh"
+
+#include <stdint.h>
+
+namespace search {
+
+EdgeQueue::EdgeQueue(unsigned int pop_limit_hint) : partial_edge_pool_(sizeof(PartialEdge), pop_limit_hint * 2) {
+ take_ = static_cast<PartialEdge*>(partial_edge_pool_.malloc());
+}
+
+/*void EdgeQueue::AddEdge(PartialEdge &root, unsigned char arity, Note note) {
+ // Ignore empty edges.
+ for (unsigned char i = 0; i < edge.Arity(); ++i) {
+ PartialVertex root(edge.GetVertex(i).RootPartial());
+ if (root.Empty()) return;
+ total_score += root.Bound();
+ }
+ PartialEdge &allocated = *static_cast<PartialEdge*>(partial_edge_pool_.malloc());
+ allocated.score = total_score;
+}*/
+
+} // namespace search
diff --git a/search/edge_queue.hh b/search/edge_queue.hh
new file mode 100644
index 000000000..187eaed71
--- /dev/null
+++ b/search/edge_queue.hh
@@ -0,0 +1,73 @@
+#ifndef SEARCH_EDGE_QUEUE__
+#define SEARCH_EDGE_QUEUE__
+
+#include "search/edge.hh"
+#include "search/edge_generator.hh"
+#include "search/note.hh"
+
+#include <boost/pool/pool.hpp>
+#include <boost/pool/object_pool.hpp>
+
+#include <queue>
+
+namespace search {
+
+template <class Model> class Context;
+
+class EdgeQueue {
+ public:
+ explicit EdgeQueue(unsigned int pop_limit_hint);
+
+ PartialEdge &InitializeEdge() {
+ return *take_;
+ }
+
+ void AddEdge(unsigned char arity, Note note) {
+ generate_.push(edge_pool_.construct(*take_, arity, note));
+ take_ = static_cast<PartialEdge*>(partial_edge_pool_.malloc());
+ }
+
+ bool Empty() const { return generate_.empty(); }
+
+ /* Generate hypotheses and send them to output. Normally, output is a
+ * VertexGenerator, but the decoder may want to route edges to different
+ * vertices i.e. if they have different LHS non-terminal labels.
+ */
+ template <class Model, class Output> void Search(Context<Model> &context, Output &output) {
+ int to_pop = context.PopLimit();
+ while (to_pop > 0 && !generate_.empty()) {
+ EdgeGenerator *top = generate_.top();
+ generate_.pop();
+ PartialEdge *ret = top->Pop(context, partial_edge_pool_);
+ if (ret) {
+ output.NewHypothesis(*ret, top->GetNote());
+ --to_pop;
+ if (top->TopScore() != -kScoreInf) {
+ generate_.push(top);
+ }
+ } else {
+ generate_.push(top);
+ }
+ }
+ output.FinishedSearch();
+ }
+
+ private:
+ boost::object_pool<EdgeGenerator> edge_pool_;
+
+ struct LessByTopScore : public std::binary_function<const EdgeGenerator *, const EdgeGenerator *, bool> {
+ bool operator()(const EdgeGenerator *first, const EdgeGenerator *second) const {
+ return first->TopScore() < second->TopScore();
+ }
+ };
+
+ typedef std::priority_queue<EdgeGenerator*, std::vector<EdgeGenerator*>, LessByTopScore> Generate;
+ Generate generate_;
+
+ boost::pool<> partial_edge_pool_;
+
+ PartialEdge *take_;
+};
+
+} // namespace search
+#endif // SEARCH_EDGE_QUEUE__
diff --git a/search/final.hh b/search/final.hh
new file mode 100644
index 000000000..1b3092ac4
--- /dev/null
+++ b/search/final.hh
@@ -0,0 +1,39 @@
+#ifndef SEARCH_FINAL__
+#define SEARCH_FINAL__
+
+#include "search/arity.hh"
+#include "search/note.hh"
+#include "search/types.hh"
+
+#include <boost/array.hpp>
+
+namespace search {
+
+class Final {
+ public:
+ typedef boost::array<const Final*, search::kMaxArity> ChildArray;
+
+ void Reset(Score bound, Note note, const Final &left, const Final &right) {
+ bound_ = bound;
+ note_ = note;
+ children_[0] = &left;
+ children_[1] = &right;
+ }
+
+ const ChildArray &Children() const { return children_; }
+
+ Note GetNote() const { return note_; }
+
+ Score Bound() const { return bound_; }
+
+ private:
+ Score bound_;
+
+ Note note_;
+
+ ChildArray children_;
+};
+
+} // namespace search
+
+#endif // SEARCH_FINAL__
diff --git a/search/note.hh b/search/note.hh
new file mode 100644
index 000000000..50bed06ec
--- /dev/null
+++ b/search/note.hh
@@ -0,0 +1,12 @@
+#ifndef SEARCH_NOTE__
+#define SEARCH_NOTE__
+
+namespace search {
+
+union Note {
+ const void *vp;
+};
+
+} // namespace search
+
+#endif // SEARCH_NOTE__
diff --git a/search/rule.cc b/search/rule.cc
new file mode 100644
index 000000000..5b00207ef
--- /dev/null
+++ b/search/rule.cc
@@ -0,0 +1,43 @@
+#include "search/rule.hh"
+
+#include "search/context.hh"
+#include "search/final.hh"
+
+#include <ostream>
+
+#include <math.h>
+
+namespace search {
+
+template <class Model> float ScoreRule(const Context<Model> &context, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing) {
+ unsigned int oov_count = 0;
+ float prob = 0.0;
+ const Model &model = context.LanguageModel();
+ const lm::WordIndex oov = model.GetVocabulary().NotFound();
+ for (std::vector<lm::WordIndex>::const_iterator word = words.begin(); ; ++word) {
+ lm::ngram::RuleScore<Model> scorer(model, *(writing++));
+ // TODO: optimize
+ if (prepend_bos && (word == words.begin())) {
+ scorer.BeginSentence();
+ }
+ for (; ; ++word) {
+ if (word == words.end()) {
+ prob += scorer.Finish();
+ return static_cast<float>(oov_count) * context.GetWeights().OOV() + prob * context.GetWeights().LM();
+ }
+ if (*word == kNonTerminal) break;
+ if (*word == oov) ++oov_count;
+ scorer.Terminal(*word);
+ }
+ prob += scorer.Finish();
+ }
+}
+
+template float ScoreRule(const Context<lm::ngram::RestProbingModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+template float ScoreRule(const Context<lm::ngram::ProbingModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+template float ScoreRule(const Context<lm::ngram::TrieModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+template float ScoreRule(const Context<lm::ngram::QuantTrieModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+template float ScoreRule(const Context<lm::ngram::ArrayTrieModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+template float ScoreRule(const Context<lm::ngram::QuantArrayTrieModel> &model, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *writing);
+
+} // namespace search
diff --git a/search/rule.hh b/search/rule.hh
new file mode 100644
index 000000000..0ce2794db
--- /dev/null
+++ b/search/rule.hh
@@ -0,0 +1,20 @@
+#ifndef SEARCH_RULE__
+#define SEARCH_RULE__
+
+#include "lm/left.hh"
+#include "lm/word_index.hh"
+#include "search/types.hh"
+
+#include <vector>
+
+namespace search {
+
+template <class Model> class Context;
+
+const lm::WordIndex kNonTerminal = lm::kMaxWordIndex;
+
+template <class Model> float ScoreRule(const Context<Model> &context, const std::vector<lm::WordIndex> &words, bool prepend_bos, lm::ngram::ChartState *state_out);
+
+} // namespace search
+
+#endif // SEARCH_RULE__
diff --git a/search/source.hh b/search/source.hh
new file mode 100644
index 000000000..11839f7bc
--- /dev/null
+++ b/search/source.hh
@@ -0,0 +1,48 @@
+#ifndef SEARCH_SOURCE__
+#define SEARCH_SOURCE__
+
+#include "search/types.hh"
+
+#include <assert.h>
+#include <vector>
+
+namespace search {
+
+template <class Final> class Source {
+ public:
+ Source() : bound_(kScoreInf) {}
+
+ Index Size() const {
+ return final_.size();
+ }
+
+ Score Bound() const {
+ return bound_;
+ }
+
+ const Final &operator[](Index index) const {
+ return *final_[index];
+ }
+
+ Score ScoreOrBound(Index index) const {
+ return Size() > index ? final_[index]->Total() : Bound();
+ }
+
+ protected:
+ void AddFinal(const Final &store) {
+ final_.push_back(&store);
+ }
+
+ void SetBound(Score to) {
+ assert(to <= bound_ + 0.001);
+ bound_ = to;
+ }
+
+ private:
+ std::vector<const Final *> final_;
+
+ Score bound_;
+};
+
+} // namespace search
+#endif // SEARCH_SOURCE__
diff --git a/search/types.hh b/search/types.hh
new file mode 100644
index 000000000..9726379fb
--- /dev/null
+++ b/search/types.hh
@@ -0,0 +1,18 @@
+#ifndef SEARCH_TYPES__
+#define SEARCH_TYPES__
+
+#include <cmath>
+
+namespace search {
+
+typedef float Score;
+const Score kScoreInf = INFINITY;
+
+// This could have been an enum but gcc wants 4 bytes.
+typedef bool ExtendDirection;
+const ExtendDirection kExtendLeft = 0;
+const ExtendDirection kExtendRight = 1;
+
+} // namespace search
+
+#endif // SEARCH_TYPES__
diff --git a/search/vertex.cc b/search/vertex.cc
new file mode 100644
index 000000000..cc53c0dd5
--- /dev/null
+++ b/search/vertex.cc
@@ -0,0 +1,48 @@
+#include "search/vertex.hh"
+
+#include "search/context.hh"
+
+#include <algorithm>
+#include <functional>
+
+#include <assert.h>
+
+namespace search {
+
+namespace {
+
+struct GreaterByBound : public std::binary_function<const VertexNode *, const VertexNode *, bool> {
+ bool operator()(const VertexNode *first, const VertexNode *second) const {
+ return first->Bound() > second->Bound();
+ }
+};
+
+} // namespace
+
+void VertexNode::SortAndSet(ContextBase &context, VertexNode **parent_ptr) {
+ if (Complete()) {
+ assert(end_);
+ assert(extend_.empty());
+ bound_ = end_->Bound();
+ return;
+ }
+ if (extend_.size() == 1 && parent_ptr) {
+ *parent_ptr = extend_[0];
+ extend_[0]->SortAndSet(context, parent_ptr);
+ context.DeleteVertexNode(this);
+ return;
+ }
+ for (std::vector<VertexNode*>::iterator i = extend_.begin(); i != extend_.end(); ++i) {
+ (*i)->SortAndSet(context, &*i);
+ }
+ std::sort(extend_.begin(), extend_.end(), GreaterByBound());
+ bound_ = extend_.front()->Bound();
+}
+
+namespace {
+VertexNode kBlankVertexNode;
+} // namespace
+
+PartialVertex kBlankPartialVertex(kBlankVertexNode);
+
+} // namespace search
diff --git a/search/vertex.hh b/search/vertex.hh
new file mode 100644
index 000000000..e1a9ad113
--- /dev/null
+++ b/search/vertex.hh
@@ -0,0 +1,158 @@
+#ifndef SEARCH_VERTEX__
+#define SEARCH_VERTEX__
+
+#include "lm/left.hh"
+#include "search/final.hh"
+#include "search/types.hh"
+
+#include <boost/unordered_set.hpp>
+
+#include <queue>
+#include <vector>
+
+#include <stdint.h>
+
+namespace search {
+
+class ContextBase;
+
+class VertexNode {
+ public:
+ VertexNode() : end_(NULL) {}
+
+ void InitRoot() {
+ extend_.clear();
+ state_.left.full = false;
+ state_.left.length = 0;
+ state_.right.length = 0;
+ right_full_ = false;
+ bound_ = -kScoreInf;
+ end_ = NULL;
+ }
+
+ lm::ngram::ChartState &MutableState() { return state_; }
+ bool &MutableRightFull() { return right_full_; }
+
+ void AddExtend(VertexNode *next) {
+ extend_.push_back(next);
+ }
+
+ void SetEnd(Final *end) { end_ = end; }
+
+ Final &MutableEnd() { return *end_; }
+
+ void SortAndSet(ContextBase &context, VertexNode **parent_pointer);
+
+ // Should only happen to a root node when the entire vertex is empty.
+ bool Empty() const {
+ return !end_ && extend_.empty();
+ }
+
+ bool Complete() const {
+ return end_;
+ }
+
+ const lm::ngram::ChartState &State() const { return state_; }
+ bool RightFull() const { return right_full_; }
+
+ Score Bound() const {
+ return bound_;
+ }
+
+ unsigned char Length() const {
+ return state_.left.length + state_.right.length;
+ }
+
+ // May be NULL.
+ const Final *End() const { return end_; }
+
+ const VertexNode &operator[](size_t index) const {
+ return *extend_[index];
+ }
+
+ size_t Size() const {
+ return extend_.size();
+ }
+
+ private:
+ std::vector<VertexNode*> extend_;
+
+ lm::ngram::ChartState state_;
+ bool right_full_;
+
+ Score bound_;
+ Final *end_;
+};
+
+class PartialVertex {
+ public:
+ PartialVertex() {}
+
+ explicit PartialVertex(const VertexNode &back) : back_(&back), index_(0) {}
+
+ bool Empty() const { return back_->Empty(); }
+
+ bool Complete() const { return back_->Complete(); }
+
+ const lm::ngram::ChartState &State() const { return back_->State(); }
+ bool RightFull() const { return back_->RightFull(); }
+
+ Score Bound() const { return Complete() ? back_->End()->Bound() : (*back_)[index_].Bound(); }
+
+ unsigned char Length() const { return back_->Length(); }
+
+ bool HasAlternative() const {
+ return index_ + 1 < back_->Size();
+ }
+
+ // Split into continuation and alternative, rendering this the alternative.
+ bool Split(PartialVertex &continuation) {
+ assert(!Complete());
+ continuation.back_ = &((*back_)[index_]);
+ continuation.index_ = 0;
+ if (index_ + 1 < back_->Size()) {
+ ++index_;
+ return true;
+ }
+ return false;
+ }
+
+ const Final &End() const {
+ return *back_->End();
+ }
+
+ private:
+ const VertexNode *back_;
+ unsigned int index_;
+};
+
+extern PartialVertex kBlankPartialVertex;
+
+class Vertex {
+ public:
+ Vertex() {}
+
+ PartialVertex RootPartial() const { return PartialVertex(root_); }
+
+ const Final *BestChild() const {
+ PartialVertex top(RootPartial());
+ if (top.Empty()) {
+ return NULL;
+ } else {
+ PartialVertex continuation;
+ while (!top.Complete()) {
+ top.Split(continuation);
+ top = continuation;
+ }
+ return &top.End();
+ }
+ }
+
+ private:
+ friend class VertexGenerator;
+
+ VertexNode root_;
+};
+
+} // namespace search
+#endif // SEARCH_VERTEX__
diff --git a/search/vertex_generator.cc b/search/vertex_generator.cc
new file mode 100644
index 000000000..d94e6e06e
--- /dev/null
+++ b/search/vertex_generator.cc
@@ -0,0 +1,83 @@
+#include "search/vertex_generator.hh"
+
+#include "lm/left.hh"
+#include "search/context.hh"
+#include "search/edge.hh"
+
+#include <stdint.h>
+
+namespace search {
+
+VertexGenerator::VertexGenerator(ContextBase &context, Vertex &gen) : context_(context), gen_(gen) {
+ gen.root_.InitRoot();
+ root_.under = &gen.root_;
+}
+
+namespace {
+const uint64_t kCompleteAdd = static_cast<uint64_t>(-1);
+} // namespace
+
+void VertexGenerator::NewHypothesis(const PartialEdge &partial, Note note) {
+ const lm::ngram::ChartState &state = partial.CompletedState();
+ std::pair<Existing::iterator, bool> got(existing_.insert(std::pair<uint64_t, Final*>(hash_value(state), NULL)));
+ if (!got.second) {
+ // Found it already.
+ Final &exists = *got.first->second;
+ if (exists.Bound() < partial.score) {
+ exists.Reset(partial.score, note, partial.nt[0].End(), partial.nt[1].End());
+ }
+ return;
+ }
+ unsigned char left = 0, right = 0;
+ Trie *node = &root_;
+ while (true) {
+ if (left == state.left.length) {
+ node = &FindOrInsert(*node, kCompleteAdd - state.left.full, state, left, true, right, false);
+ for (; right < state.right.length; ++right) {
+ node = &FindOrInsert(*node, state.right.words[right], state, left, true, right + 1, false);
+ }
+ break;
+ }
+ node = &FindOrInsert(*node, state.left.pointers[left], state, left + 1, false, right, false);
+ left++;
+ if (right == state.right.length) {
+ node = &FindOrInsert(*node, kCompleteAdd - state.left.full, state, left, false, right, true);
+ for (; left < state.left.length; ++left) {
+ node = &FindOrInsert(*node, state.left.pointers[left], state, left + 1, false, right, true);
+ }
+ break;
+ }
+ node = &FindOrInsert(*node, state.right.words[right], state, left, false, right + 1, false);
+ right++;
+ }
+
+ node = &FindOrInsert(*node, kCompleteAdd - state.left.full, state, state.left.length, true, state.right.length, true);
+ got.first->second = CompleteTransition(*node, state, note, partial);
+}
+
+VertexGenerator::Trie &VertexGenerator::FindOrInsert(VertexGenerator::Trie &node, uint64_t added, const lm::ngram::ChartState &state, unsigned char left, bool left_full, unsigned char right, bool right_full) {
+ VertexGenerator::Trie &next = node.extend[added];
+ if (!next.under) {
+ next.under = context_.NewVertexNode();
+ lm::ngram::ChartState &writing = next.under->MutableState();
+ writing = state;
+ writing.left.full &= left_full && state.left.full;
+ next.under->MutableRightFull() = right_full && state.left.full;
+ writing.left.length = left;
+ writing.right.length = right;
+ node.under->AddExtend(next.under);
+ }
+ return next;
+}
+
+Final *VertexGenerator::CompleteTransition(VertexGenerator::Trie &starter, const lm::ngram::ChartState &state, Note note, const PartialEdge &partial) {
+ VertexNode &node = *starter.under;
+ assert(node.State().left.full == state.left.full);
+ assert(!node.End());
+ Final *final = context_.NewFinal();
+ final->Reset(partial.score, note, partial.nt[0].End(), partial.nt[1].End());
+ node.SetEnd(final);
+ return final;
+}
+
+} // namespace search
diff --git a/search/vertex_generator.hh b/search/vertex_generator.hh
new file mode 100644
index 000000000..6b98da3e3
--- /dev/null
+++ b/search/vertex_generator.hh
@@ -0,0 +1,59 @@
+#ifndef SEARCH_VERTEX_GENERATOR__
+#define SEARCH_VERTEX_GENERATOR__
+
+#include "search/note.hh"
+#include "search/vertex.hh"
+
+#include <boost/unordered_map.hpp>
+
+#include <queue>
+
+namespace lm {
+namespace ngram {
+class ChartState;
+} // namespace ngram
+} // namespace lm
+
+namespace search {
+
+class ContextBase;
+class Final;
+struct PartialEdge;
+
+class VertexGenerator {
+ public:
+ VertexGenerator(ContextBase &context, Vertex &gen);
+
+ void NewHypothesis(const PartialEdge &partial, Note note);
+
+ void FinishedSearch() {
+ root_.under->SortAndSet(context_, NULL);
+ }
+
+ const Vertex &Generating() const { return gen_; }
+
+ private:
+ // Parallel structure to VertexNode.
+ struct Trie {
+ Trie() : under(NULL) {}
+
+ VertexNode *under;
+ boost::unordered_map<uint64_t, Trie> extend;
+ };
+
+ Trie &FindOrInsert(Trie &node, uint64_t added, const lm::ngram::ChartState &state, unsigned char left, bool left_full, unsigned char right, bool right_full);
+
+ Final *CompleteTransition(Trie &node, const lm::ngram::ChartState &state, Note note, const PartialEdge &partial);
+
+ ContextBase &context_;
+
+ Vertex &gen_;
+
+ Trie root_;
+
+ typedef boost::unordered_map<uint64_t, Final*> Existing;
+ Existing existing_;
+};
+
+} // namespace search
+#endif // SEARCH_VERTEX_GENERATOR__
diff --git a/search/weights.cc b/search/weights.cc
new file mode 100644
index 000000000..d65471ad7
--- /dev/null
+++ b/search/weights.cc
@@ -0,0 +1,71 @@
+#include "search/weights.hh"
+#include "util/tokenize_piece.hh"
+
+#include <cstdlib>
+
+namespace search {
+
+namespace {
+struct Insert {
+ void operator()(boost::unordered_map<std::string, search::Score> &map, StringPiece name, search::Score score) const {
+ std::string copy(name.data(), name.size());
+ map[copy] = score;
+ }
+};
+
+struct DotProduct {
+ search::Score total;
+ DotProduct() : total(0.0) {}
+
+ void operator()(const boost::unordered_map<std::string, search::Score> &map, StringPiece name, search::Score score) {
+ boost::unordered_map<std::string, search::Score>::const_iterator i(FindStringPiece(map, name));
+ if (i != map.end())
+ total += score * i->second;
+ }
+};
+
+template <class Map, class Op> void Parse(StringPiece text, Map &map, Op &op) {
+ for (util::TokenIter<util::SingleCharacter, true> spaces(text, ' '); spaces; ++spaces) {
+ util::TokenIter<util::SingleCharacter> equals(*spaces, '=');
+ UTIL_THROW_IF(!equals, WeightParseException, "Bad weight token " << *spaces);
+ StringPiece name(*equals);
+ UTIL_THROW_IF(!++equals, WeightParseException, "Bad weight token " << *spaces);
+ char *end;
+ // Assumes proper termination.
+ double value = std::strtod(equals->data(), &end);
+ UTIL_THROW_IF(end != equals->data() + equals->size(), WeightParseException, "Failed to parse weight" << *equals);
+ UTIL_THROW_IF(++equals, WeightParseException, "Too many equals in " << *spaces);
+ op(map, name, value);
+ }
+}
+
+} // namespace
+
+Weights::Weights(StringPiece text) {
+ Insert op;
+ Parse<Map, Insert>(text, map_, op);
+ lm_ = Steal("LanguageModel");
+ oov_ = Steal("OOV");
+ word_penalty_ = Steal("WordPenalty");
+}
+
+Weights::Weights(Score lm, Score oov, Score word_penalty) : lm_(lm), oov_(oov), word_penalty_(word_penalty) {}
+
+search::Score Weights::DotNoLM(StringPiece text) const {
+ DotProduct dot;
+ Parse<const Map, DotProduct>(text, map_, dot);
+ return dot.total;
+}
+
+float Weights::Steal(const std::string &str) {
+ Map::iterator i(map_.find(str));
+ if (i == map_.end()) {
+ return 0.0;
+ } else {
+ float ret = i->second;
+ map_.erase(i);
+ return ret;
+ }
+}
+
+} // namespace search
diff --git a/search/weights.hh b/search/weights.hh
new file mode 100644
index 000000000..df1c419f0
--- /dev/null
+++ b/search/weights.hh
@@ -0,0 +1,52 @@
+// For now, the individual features are not kept.
+#ifndef SEARCH_WEIGHTS__
+#define SEARCH_WEIGHTS__
+
+#include "search/types.hh"
+#include "util/exception.hh"
+#include "util/string_piece.hh"
+
+#include <boost/unordered_map.hpp>
+
+#include <string>
+
+namespace search {
+
+class WeightParseException : public util::Exception {
+ public:
+ WeightParseException() {}
+ ~WeightParseException() throw() {}
+};
+
+class Weights {
+ public:
+ // Parses weights, sets lm_weight_, removes it from map_.
+ explicit Weights(StringPiece text);
+
+ // Just the three scores we care about adding.
+ Weights(Score lm, Score oov, Score word_penalty);
+
+ Score DotNoLM(StringPiece text) const;
+
+ Score LM() const { return lm_; }
+
+ Score OOV() const { return oov_; }
+
+ Score WordPenalty() const { return word_penalty_; }
+
+ // Mostly for testing.
+ const boost::unordered_map<std::string, Score> &GetMap() const { return map_; }
+
+ private:
+ float Steal(const std::string &str);
+
+ typedef boost::unordered_map<std::string, Score> Map;
+
+ Map map_;
+
+ Score lm_, oov_, word_penalty_;
+};
+
+} // namespace search
+
+#endif // SEARCH_WEIGHTS__
diff --git a/search/weights_test.cc b/search/weights_test.cc
new file mode 100644
index 000000000..4811ff060
--- /dev/null
+++ b/search/weights_test.cc
@@ -0,0 +1,38 @@
+#include "search/weights.hh"
+
+#define BOOST_TEST_MODULE WeightTest
+#include <boost/test/unit_test.hpp>
+#include <boost/test/floating_point_comparison.hpp>
+
+namespace search {
+namespace {
+
+#define CHECK_WEIGHT(value, string) \
+ i = parsed.find(string); \
+ BOOST_REQUIRE(i != parsed.end()); \
+ BOOST_CHECK_CLOSE((value), i->second, 0.001);
+
+BOOST_AUTO_TEST_CASE(parse) {
+ // These are not real feature weights.
+ Weights w("rarity=0 phrase-SGT=0 phrase-TGS=9.45117 lhsGrhs=0 lexical-SGT=2.33833 lexical-TGS=-28.3317 abstract?=0 LanguageModel=3 lexical?=1 glue?=5");
+ const boost::unordered_map<std::string, search::Score> &parsed = w.GetMap();
+ boost::unordered_map<std::string, search::Score>::const_iterator i;
+ CHECK_WEIGHT(0.0, "rarity");
+ CHECK_WEIGHT(0.0, "phrase-SGT");
+ CHECK_WEIGHT(9.45117, "phrase-TGS");
+ CHECK_WEIGHT(2.33833, "lexical-SGT");
+ BOOST_CHECK(parsed.end() == parsed.find("lm"));
+ BOOST_CHECK_CLOSE(3.0, w.LM(), 0.001);
+ CHECK_WEIGHT(-28.3317, "lexical-TGS");
+ CHECK_WEIGHT(5.0, "glue?");
+}
+
+BOOST_AUTO_TEST_CASE(dot) {
+ Weights w("rarity=0 phrase-SGT=0 phrase-TGS=9.45117 lhsGrhs=0 lexical-SGT=2.33833 lexical-TGS=-28.3317 abstract?=0 LanguageModel=3 lexical?=1 glue?=5");
+ BOOST_CHECK_CLOSE(9.45117 * 3.0, w.DotNoLM("phrase-TGS=3.0"), 0.001);
+ BOOST_CHECK_CLOSE(9.45117 * 3.0, w.DotNoLM("phrase-TGS=3.0 LanguageModel=10"), 0.001);
+ BOOST_CHECK_CLOSE(9.45117 * 3.0 + 28.3317 * 17.4, w.DotNoLM("rarity=5 phrase-TGS=3.0 LanguageModel=10 lexical-TGS=-17.4"), 0.001);
+}
+
+} // namespace
+} // namespace search
diff --git a/util/COPYING b/util/COPYING
deleted file mode 100644
index 94a9ed024..000000000
--- a/util/COPYING
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/util/COPYING.LESSER b/util/COPYING.LESSER
deleted file mode 100644
index cca7fc278..000000000
--- a/util/COPYING.LESSER
+++ /dev/null
@@ -1,165 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-
- This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
- 0. Additional Definitions.
-
- As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
- "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
- An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
- A "Combined Work" is a work produced by combining or linking an
-Application with the Library. The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
- The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
- The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
- 1. Exception to Section 3 of the GNU GPL.
-
- You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
- 2. Conveying Modified Versions.
-
- If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
- a) under this License, provided that you make a good faith effort to
- ensure that, in the event an Application does not supply the
- function or data, the facility still operates, and performs
- whatever part of its purpose remains meaningful, or
-
- b) under the GNU GPL, with none of the additional permissions of
- this License applicable to that copy.
-
- 3. Object Code Incorporating Material from Library Header Files.
-
- The object code form of an Application may incorporate material from
-a header file that is part of the Library. You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
- a) Give prominent notice with each copy of the object code that the
- Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the object code with a copy of the GNU GPL and this license
- document.
-
- 4. Combined Works.
-
- You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
- a) Give prominent notice with each copy of the Combined Work that
- the Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
- document.
-
- c) For a Combined Work that displays copyright notices during
- execution, include the copyright notice for the Library among
- these notices, as well as a reference directing the user to the
- copies of the GNU GPL and this license document.
-
- d) Do one of the following:
-
- 0) Convey the Minimal Corresponding Source under the terms of this
- License, and the Corresponding Application Code in a form
- suitable for, and under terms that permit, the user to
- recombine or relink the Application with a modified version of
- the Linked Version to produce a modified Combined Work, in the
- manner specified by section 6 of the GNU GPL for conveying
- Corresponding Source.
-
- 1) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (a) uses at run time
- a copy of the Library already present on the user's computer
- system, and (b) will operate properly with a modified version
- of the Library that is interface-compatible with the Linked
- Version.
-
- e) Provide Installation Information, but only if you would otherwise
- be required to provide such information under section 6 of the
- GNU GPL, and only to the extent that such information is
- necessary to install and execute a modified version of the
- Combined Work produced by recombining or relinking the
- Application with a modified version of the Linked Version. (If
- you use option 4d0, the Installation Information must accompany
- the Minimal Corresponding Source and Corresponding Application
- Code. If you use option 4d1, you must provide the Installation
- Information in the manner specified by section 6 of the GNU GPL
- for conveying Corresponding Source.)
-
- 5. Combined Libraries.
-
- You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
- a) Accompany the combined library with a copy of the same work based
- on the Library, uncombined with any other library facilities,
- conveyed under the terms of this License.
-
- b) Give prominent notice with the combined library that part of it
- is a work based on the Library, and explaining where to find the
- accompanying uncombined form of the same work.
-
- 6. Revised Versions of the GNU Lesser General Public License.
-
- The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
- If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
-Library.
diff --git a/util/Jamfile b/util/Jamfile
index e555488fd..2b76b2b1b 100644
--- a/util/Jamfile
+++ b/util/Jamfile
@@ -1,10 +1,10 @@
-lib kenutil : bit_packing.cc ersatz_progress.cc exception.cc file.cc file_piece.cc mmap.cc murmur_hash.cc usage.cc ..//z : <include>.. : : <include>.. ;
+lib kenutil : bit_packing.cc ersatz_progress.cc exception.cc file.cc file_piece.cc mmap.cc murmur_hash.cc string_piece.cc usage.cc /top//z : <include>.. : : <include>.. ;
import testing ;
-unit-test bit_packing_test : bit_packing_test.cc kenutil ..//boost_unit_test_framework ;
-run file_piece_test.cc kenutil ..//boost_unit_test_framework : : file_piece.cc ;
-unit-test joint_sort_test : joint_sort_test.cc kenutil ..//boost_unit_test_framework ;
-unit-test probing_hash_table_test : probing_hash_table_test.cc kenutil ..//boost_unit_test_framework ;
-unit-test sorted_uniform_test : sorted_uniform_test.cc kenutil ..//boost_unit_test_framework ;
-unit-test tokenize_piece_test : tokenize_piece_test.cc kenutil ..//boost_unit_test_framework ;
+unit-test bit_packing_test : bit_packing_test.cc kenutil /top//boost_unit_test_framework ;
+run file_piece_test.cc kenutil /top//boost_unit_test_framework : : file_piece.cc ;
+unit-test joint_sort_test : joint_sort_test.cc kenutil /top//boost_unit_test_framework ;
+unit-test probing_hash_table_test : probing_hash_table_test.cc kenutil /top//boost_unit_test_framework ;
+unit-test sorted_uniform_test : sorted_uniform_test.cc kenutil /top//boost_unit_test_framework ;
+unit-test tokenize_piece_test : tokenize_piece_test.cc kenutil /top//boost_unit_test_framework ;
diff --git a/util/LICENSE b/util/LICENSE
deleted file mode 100644
index 0ba079e30..000000000
--- a/util/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Most of the code here is licensed under the LGPL. There are exceptions which have their own licenses, listed below. See comments in those files for more details.
-
-murmur_hash.cc is under the MIT license.
-string_piece.hh and util/string_piece.cc are Google code and contains its own license.
-file.cc contains a modified implementation of mkstemp under the LGPL.
-
-For the rest:
-
- Avenue code is free software: you can redistribute it and/or modify
- it under the terms of the GNU Lesser General Public License as published
- by the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Avenue code is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with Avenue code. If not, see <http://www.gnu.org/licenses/>.
diff --git a/util/have.hh b/util/have.hh
index 1d76a7fcf..b8181e999 100644
--- a/util/have.hh
+++ b/util/have.hh
@@ -13,7 +13,7 @@
#endif
#ifndef HAVE_BOOST
-//#define HAVE_BOOST
+#define HAVE_BOOST
#endif
#ifndef HAVE_THREADS
diff --git a/util/string_piece.cc b/util/string_piece.cc
new file mode 100644
index 000000000..b422cefc9
--- /dev/null
+++ b/util/string_piece.cc
@@ -0,0 +1,192 @@
+// Copyright 2004 The RE2 Authors. All Rights Reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in string_piece.hh.
+
+#include "util/string_piece.hh"
+
+#include <algorithm>
+
+#include <limits.h>
+
+#ifndef HAVE_ICU
+
+typedef StringPiece::size_type size_type;
+
+void StringPiece::CopyToString(std::string* target) const {
+ target->assign(ptr_, length_);
+}
+
+size_type StringPiece::find(const StringPiece& s, size_type pos) const {
+ if (length_ < 0 || pos > static_cast<size_type>(length_))
+ return npos;
+
+ const char* result = std::search(ptr_ + pos, ptr_ + length_,
+ s.ptr_, s.ptr_ + s.length_);
+ const size_type xpos = result - ptr_;
+ return xpos + s.length_ <= length_ ? xpos : npos;
+}
+
+size_type StringPiece::find(char c, size_type pos) const {
+ if (length_ <= 0 || pos >= static_cast<size_type>(length_)) {
+ return npos;
+ }
+ const char* result = std::find(ptr_ + pos, ptr_ + length_, c);
+ return result != ptr_ + length_ ? result - ptr_ : npos;
+}
+
+size_type StringPiece::rfind(const StringPiece& s, size_type pos) const {
+ if (length_ < s.length_) return npos;
+ const size_t ulen = length_;
+ if (s.length_ == 0) return std::min(ulen, pos);
+
+ const char* last = ptr_ + std::min(ulen - s.length_, pos) + s.length_;
+ const char* result = std::find_end(ptr_, last, s.ptr_, s.ptr_ + s.length_);
+ return result != last ? result - ptr_ : npos;
+}
+
+size_type StringPiece::rfind(char c, size_type pos) const {
+ if (length_ <= 0) return npos;
+ for (int i = std::min(pos, static_cast<size_type>(length_ - 1));
+ i >= 0; --i) {
+ if (ptr_[i] == c) {
+ return i;
+ }
+ }
+ return npos;
+}
+
+// For each character in characters_wanted, sets the index corresponding
+// to the ASCII code of that character to 1 in table. This is used by
+// the find_.*_of methods below to tell whether or not a character is in
+// the lookup table in constant time.
+// The argument `table' must be an array that is large enough to hold all
+// the possible values of an unsigned char. Thus it should be be declared
+// as follows:
+// bool table[UCHAR_MAX + 1]
+static inline void BuildLookupTable(const StringPiece& characters_wanted,
+ bool* table) {
+ const size_type length = characters_wanted.length();
+ const char* const data = characters_wanted.data();
+ for (size_type i = 0; i < length; ++i) {
+ table[static_cast<unsigned char>(data[i])] = true;
+ }
+}
+
+size_type StringPiece::find_first_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0 || s.length_ == 0)
+ return npos;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1)
+ return find_first_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = { false };
+ BuildLookupTable(s, lookup);
+ for (size_type i = pos; i < length_; ++i) {
+ if (lookup[static_cast<unsigned char>(ptr_[i])]) {
+ return i;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_first_not_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0)
+ return npos;
+
+ if (s.length_ == 0)
+ return 0;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1)
+ return find_first_not_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = { false };
+ BuildLookupTable(s, lookup);
+ for (size_type i = pos; i < length_; ++i) {
+ if (!lookup[static_cast<unsigned char>(ptr_[i])]) {
+ return i;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_first_not_of(char c, size_type pos) const {
+ if (length_ == 0)
+ return npos;
+
+ for (; pos < length_; ++pos) {
+ if (ptr_[pos] != c) {
+ return pos;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_of(const StringPiece& s, size_type pos) const {
+ if (length_ == 0 || s.length_ == 0)
+ return npos;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1)
+ return find_last_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = { false };
+ BuildLookupTable(s, lookup);
+ for (size_type i = std::min(pos, length_ - 1); ; --i) {
+ if (lookup[static_cast<unsigned char>(ptr_[i])])
+ return i;
+ if (i == 0)
+ break;
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_not_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0)
+ return npos;
+
+ size_type i = std::min(pos, length_ - 1);
+ if (s.length_ == 0)
+ return i;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1)
+ return find_last_not_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = { false };
+ BuildLookupTable(s, lookup);
+ for (; ; --i) {
+ if (!lookup[static_cast<unsigned char>(ptr_[i])])
+ return i;
+ if (i == 0)
+ break;
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_not_of(char c, size_type pos) const {
+ if (length_ == 0)
+ return npos;
+
+ for (size_type i = std::min(pos, length_ - 1); ; --i) {
+ if (ptr_[i] != c)
+ return i;
+ if (i == 0)
+ break;
+ }
+ return npos;
+}
+
+StringPiece StringPiece::substr(size_type pos, size_type n) const {
+ if (pos > length_) pos = length_;
+ if (n > length_ - pos) n = length_ - pos;
+ return StringPiece(ptr_ + pos, n);
+}
+
+const size_type StringPiece::npos = size_type(-1);
+
+#endif // !HAVE_ICU
diff --git a/util/util.xcodeproj/project.pbxproj b/util/util.xcodeproj/project.pbxproj
deleted file mode 100644
index 5183f7a88..000000000
--- a/util/util.xcodeproj/project.pbxproj
+++ /dev/null
@@ -1,297 +0,0 @@
-// !$*UTF8*$!
-{
- archiveVersion = 1;
- classes = {
- };
- objectVersion = 46;
- objects = {
-
-/* Begin PBXBuildFile section */
- 1EE8C2A41476A2E9002496F2 /* bit_packing.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C27C1476A2E9002496F2 /* bit_packing.cc */; };
- 1EE8C2A51476A2EA002496F2 /* bit_packing.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C27D1476A2E9002496F2 /* bit_packing.hh */; };
- 1EE8C2A61476A2EA002496F2 /* check.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C27E1476A2E9002496F2 /* check.hh */; };
- 1EE8C2A71476A2EA002496F2 /* ersatz_progress.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2811476A2E9002496F2 /* ersatz_progress.cc */; };
- 1EE8C2A81476A2EA002496F2 /* ersatz_progress.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2821476A2E9002496F2 /* ersatz_progress.hh */; };
- 1EE8C2A91476A2EA002496F2 /* exception.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2831476A2E9002496F2 /* exception.cc */; };
- 1EE8C2AA1476A2EA002496F2 /* exception.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2841476A2E9002496F2 /* exception.hh */; };
- 1EE8C2AC1476A2EA002496F2 /* file_piece.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2861476A2E9002496F2 /* file_piece.cc */; };
- 1EE8C2AD1476A2EA002496F2 /* file_piece.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2871476A2E9002496F2 /* file_piece.hh */; };
- 1EE8C2AE1476A2EA002496F2 /* file.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2881476A2E9002496F2 /* file.cc */; };
- 1EE8C2AF1476A2EA002496F2 /* file.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2891476A2E9002496F2 /* file.hh */; };
- 1EE8C2B01476A2EA002496F2 /* getopt.c in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C28A1476A2E9002496F2 /* getopt.c */; };
- 1EE8C2B11476A2EA002496F2 /* getopt.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C28B1476A2E9002496F2 /* getopt.hh */; };
- 1EE8C2B21476A2EA002496F2 /* have.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C28C1476A2E9002496F2 /* have.hh */; };
- 1EE8C2B41476A2EA002496F2 /* joint_sort.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C28E1476A2E9002496F2 /* joint_sort.hh */; };
- 1EE8C2B81476A2EA002496F2 /* mmap.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2951476A2E9002496F2 /* mmap.cc */; };
- 1EE8C2B91476A2EA002496F2 /* mmap.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2961476A2E9002496F2 /* mmap.hh */; };
- 1EE8C2BA1476A2EA002496F2 /* murmur_hash.cc in Sources */ = {isa = PBXBuildFile; fileRef = 1EE8C2971476A2E9002496F2 /* murmur_hash.cc */; };
- 1EE8C2BB1476A2EA002496F2 /* murmur_hash.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2981476A2E9002496F2 /* murmur_hash.hh */; };
- 1EE8C2BD1476A2EA002496F2 /* probing_hash_table.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C29A1476A2E9002496F2 /* probing_hash_table.hh */; };
- 1EE8C2BE1476A2EA002496F2 /* proxy_iterator.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C29B1476A2E9002496F2 /* proxy_iterator.hh */; };
- 1EE8C2BF1476A2EA002496F2 /* scoped.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C29C1476A2E9002496F2 /* scoped.hh */; };
- 1EE8C2C01476A2EA002496F2 /* sized_iterator.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C29D1476A2E9002496F2 /* sized_iterator.hh */; };
- 1EE8C2C21476A2EA002496F2 /* sorted_uniform.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C29F1476A2E9002496F2 /* sorted_uniform.hh */; };
- 1EE8C2C31476A2EA002496F2 /* string_piece.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2A01476A2E9002496F2 /* string_piece.hh */; };
- 1EE8C2C51476A2EA002496F2 /* tokenize_piece.hh in Headers */ = {isa = PBXBuildFile; fileRef = 1EE8C2A21476A2E9002496F2 /* tokenize_piece.hh */; };
-/* End PBXBuildFile section */
-
-/* Begin PBXFileReference section */
- 1EE8C2711476A262002496F2 /* libutil.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libutil.a; sourceTree = BUILT_PRODUCTS_DIR; };
- 1EE8C27C1476A2E9002496F2 /* bit_packing.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = bit_packing.cc; sourceTree = "<group>"; };
- 1EE8C27D1476A2E9002496F2 /* bit_packing.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = bit_packing.hh; sourceTree = "<group>"; };
- 1EE8C27E1476A2E9002496F2 /* check.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = check.hh; sourceTree = "<group>"; };
- 1EE8C2811476A2E9002496F2 /* ersatz_progress.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ersatz_progress.cc; sourceTree = "<group>"; };
- 1EE8C2821476A2E9002496F2 /* ersatz_progress.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = ersatz_progress.hh; sourceTree = "<group>"; };
- 1EE8C2831476A2E9002496F2 /* exception.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = exception.cc; sourceTree = "<group>"; };
- 1EE8C2841476A2E9002496F2 /* exception.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = exception.hh; sourceTree = "<group>"; };
- 1EE8C2861476A2E9002496F2 /* file_piece.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = file_piece.cc; sourceTree = "<group>"; };
- 1EE8C2871476A2E9002496F2 /* file_piece.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = file_piece.hh; sourceTree = "<group>"; };
- 1EE8C2881476A2E9002496F2 /* file.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = file.cc; sourceTree = "<group>"; };
- 1EE8C2891476A2E9002496F2 /* file.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = file.hh; sourceTree = "<group>"; };
- 1EE8C28A1476A2E9002496F2 /* getopt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getopt.c; sourceTree = "<group>"; };
- 1EE8C28B1476A2E9002496F2 /* getopt.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = getopt.hh; sourceTree = "<group>"; };
- 1EE8C28C1476A2E9002496F2 /* have.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = have.hh; sourceTree = "<group>"; };
- 1EE8C28E1476A2E9002496F2 /* joint_sort.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = joint_sort.hh; sourceTree = "<group>"; };
- 1EE8C2951476A2E9002496F2 /* mmap.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = mmap.cc; sourceTree = "<group>"; };
- 1EE8C2961476A2E9002496F2 /* mmap.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = mmap.hh; sourceTree = "<group>"; };
- 1EE8C2971476A2E9002496F2 /* murmur_hash.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = murmur_hash.cc; sourceTree = "<group>"; };
- 1EE8C2981476A2E9002496F2 /* murmur_hash.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = murmur_hash.hh; sourceTree = "<group>"; };
- 1EE8C29A1476A2E9002496F2 /* probing_hash_table.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = probing_hash_table.hh; sourceTree = "<group>"; };
- 1EE8C29B1476A2E9002496F2 /* proxy_iterator.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = proxy_iterator.hh; sourceTree = "<group>"; };
- 1EE8C29C1476A2E9002496F2 /* scoped.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = scoped.hh; sourceTree = "<group>"; };
- 1EE8C29D1476A2E9002496F2 /* sized_iterator.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = sized_iterator.hh; sourceTree = "<group>"; };
- 1EE8C29F1476A2E9002496F2 /* sorted_uniform.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = sorted_uniform.hh; sourceTree = "<group>"; };
- 1EE8C2A01476A2E9002496F2 /* string_piece.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = string_piece.hh; sourceTree = "<group>"; };
- 1EE8C2A21476A2E9002496F2 /* tokenize_piece.hh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = tokenize_piece.hh; sourceTree = "<group>"; };
-/* End PBXFileReference section */
-
-/* Begin PBXFrameworksBuildPhase section */
- 1EE8C26E1476A262002496F2 /* Frameworks */ = {
- isa = PBXFrameworksBuildPhase;
- buildActionMask = 2147483647;
- files = (
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXFrameworksBuildPhase section */
-
-/* Begin PBXGroup section */
- 1EE8C2661476A262002496F2 = {
- isa = PBXGroup;
- children = (
- 1EE8C27C1476A2E9002496F2 /* bit_packing.cc */,
- 1EE8C27D1476A2E9002496F2 /* bit_packing.hh */,
- 1EE8C27E1476A2E9002496F2 /* check.hh */,
- 1EE8C2811476A2E9002496F2 /* ersatz_progress.cc */,
- 1EE8C2821476A2E9002496F2 /* ersatz_progress.hh */,
- 1EE8C2831476A2E9002496F2 /* exception.cc */,
- 1EE8C2841476A2E9002496F2 /* exception.hh */,
- 1EE8C2861476A2E9002496F2 /* file_piece.cc */,
- 1EE8C2871476A2E9002496F2 /* file_piece.hh */,
- 1EE8C2881476A2E9002496F2 /* file.cc */,
- 1EE8C2891476A2E9002496F2 /* file.hh */,
- 1EE8C28A1476A2E9002496F2 /* getopt.c */,
- 1EE8C28B1476A2E9002496F2 /* getopt.hh */,
- 1EE8C28C1476A2E9002496F2 /* have.hh */,
- 1EE8C28E1476A2E9002496F2 /* joint_sort.hh */,
- 1EE8C2951476A2E9002496F2 /* mmap.cc */,
- 1EE8C2961476A2E9002496F2 /* mmap.hh */,
- 1EE8C2971476A2E9002496F2 /* murmur_hash.cc */,
- 1EE8C2981476A2E9002496F2 /* murmur_hash.hh */,
- 1EE8C29A1476A2E9002496F2 /* probing_hash_table.hh */,
- 1EE8C29B1476A2E9002496F2 /* proxy_iterator.hh */,
- 1EE8C29C1476A2E9002496F2 /* scoped.hh */,
- 1EE8C29D1476A2E9002496F2 /* sized_iterator.hh */,
- 1EE8C29F1476A2E9002496F2 /* sorted_uniform.hh */,
- 1EE8C2A01476A2E9002496F2 /* string_piece.hh */,
- 1EE8C2A21476A2E9002496F2 /* tokenize_piece.hh */,
- 1EE8C2721476A262002496F2 /* Products */,
- );
- sourceTree = "<group>";
- };
- 1EE8C2721476A262002496F2 /* Products */ = {
- isa = PBXGroup;
- children = (
- 1EE8C2711476A262002496F2 /* libutil.a */,
- );
- name = Products;
- sourceTree = "<group>";
- };
-/* End PBXGroup section */
-
-/* Begin PBXHeadersBuildPhase section */
- 1EE8C26F1476A262002496F2 /* Headers */ = {
- isa = PBXHeadersBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 1EE8C2A51476A2EA002496F2 /* bit_packing.hh in Headers */,
- 1EE8C2A61476A2EA002496F2 /* check.hh in Headers */,
- 1EE8C2A81476A2EA002496F2 /* ersatz_progress.hh in Headers */,
- 1EE8C2AA1476A2EA002496F2 /* exception.hh in Headers */,
- 1EE8C2AD1476A2EA002496F2 /* file_piece.hh in Headers */,
- 1EE8C2AF1476A2EA002496F2 /* file.hh in Headers */,
- 1EE8C2B11476A2EA002496F2 /* getopt.hh in Headers */,
- 1EE8C2B21476A2EA002496F2 /* have.hh in Headers */,
- 1EE8C2B41476A2EA002496F2 /* joint_sort.hh in Headers */,
- 1EE8C2B91476A2EA002496F2 /* mmap.hh in Headers */,
- 1EE8C2BB1476A2EA002496F2 /* murmur_hash.hh in Headers */,
- 1EE8C2BD1476A2EA002496F2 /* probing_hash_table.hh in Headers */,
- 1EE8C2BE1476A2EA002496F2 /* proxy_iterator.hh in Headers */,
- 1EE8C2BF1476A2EA002496F2 /* scoped.hh in Headers */,
- 1EE8C2C01476A2EA002496F2 /* sized_iterator.hh in Headers */,
- 1EE8C2C21476A2EA002496F2 /* sorted_uniform.hh in Headers */,
- 1EE8C2C31476A2EA002496F2 /* string_piece.hh in Headers */,
- 1EE8C2C51476A2EA002496F2 /* tokenize_piece.hh in Headers */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXHeadersBuildPhase section */
-
-/* Begin PBXNativeTarget section */
- 1EE8C2701476A262002496F2 /* util */ = {
- isa = PBXNativeTarget;
- buildConfigurationList = 1EE8C2751476A262002496F2 /* Build configuration list for PBXNativeTarget "util" */;
- buildPhases = (
- 1EE8C26D1476A262002496F2 /* Sources */,
- 1EE8C26E1476A262002496F2 /* Frameworks */,
- 1EE8C26F1476A262002496F2 /* Headers */,
- );
- buildRules = (
- );
- dependencies = (
- );
- name = util;
- productName = util;
- productReference = 1EE8C2711476A262002496F2 /* libutil.a */;
- productType = "com.apple.product-type.library.static";
- };
-/* End PBXNativeTarget section */
-
-/* Begin PBXProject section */
- 1EE8C2681476A262002496F2 /* Project object */ = {
- isa = PBXProject;
- attributes = {
- LastUpgradeCheck = 0420;
- };
- buildConfigurationList = 1EE8C26B1476A262002496F2 /* Build configuration list for PBXProject "util" */;
- compatibilityVersion = "Xcode 3.2";
- developmentRegion = English;
- hasScannedForEncodings = 0;
- knownRegions = (
- en,
- );
- mainGroup = 1EE8C2661476A262002496F2;
- productRefGroup = 1EE8C2721476A262002496F2 /* Products */;
- projectDirPath = "";
- projectRoot = "";
- targets = (
- 1EE8C2701476A262002496F2 /* util */,
- );
- };
-/* End PBXProject section */
-
-/* Begin PBXSourcesBuildPhase section */
- 1EE8C26D1476A262002496F2 /* Sources */ = {
- isa = PBXSourcesBuildPhase;
- buildActionMask = 2147483647;
- files = (
- 1EE8C2A41476A2E9002496F2 /* bit_packing.cc in Sources */,
- 1EE8C2A71476A2EA002496F2 /* ersatz_progress.cc in Sources */,
- 1EE8C2A91476A2EA002496F2 /* exception.cc in Sources */,
- 1EE8C2AC1476A2EA002496F2 /* file_piece.cc in Sources */,
- 1EE8C2AE1476A2EA002496F2 /* file.cc in Sources */,
- 1EE8C2B01476A2EA002496F2 /* getopt.c in Sources */,
- 1EE8C2B81476A2EA002496F2 /* mmap.cc in Sources */,
- 1EE8C2BA1476A2EA002496F2 /* murmur_hash.cc in Sources */,
- );
- runOnlyForDeploymentPostprocessing = 0;
- };
-/* End PBXSourcesBuildPhase section */
-
-/* Begin XCBuildConfiguration section */
- 1EE8C2731476A262002496F2 /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
- ARCHS = "$(ARCHS_STANDARD_64_BIT)";
- COPY_PHASE_STRIP = NO;
- GCC_C_LANGUAGE_STANDARD = gnu99;
- GCC_DYNAMIC_NO_PIC = NO;
- GCC_ENABLE_OBJC_EXCEPTIONS = YES;
- GCC_OPTIMIZATION_LEVEL = 0;
- GCC_PREPROCESSOR_DEFINITIONS = (
- "DEBUG=1",
- "$(inherited)",
- );
- GCC_SYMBOLS_PRIVATE_EXTERN = NO;
- GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
- GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
- GCC_WARN_ABOUT_RETURN_TYPE = YES;
- GCC_WARN_UNUSED_VARIABLE = YES;
- MACOSX_DEPLOYMENT_TARGET = 10.7;
- ONLY_ACTIVE_ARCH = YES;
- SDKROOT = macosx;
- };
- name = Debug;
- };
- 1EE8C2741476A262002496F2 /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- ALWAYS_SEARCH_USER_PATHS = NO;
- ARCHS = "$(ARCHS_STANDARD_64_BIT)";
- COPY_PHASE_STRIP = YES;
- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
- GCC_C_LANGUAGE_STANDARD = gnu99;
- GCC_ENABLE_OBJC_EXCEPTIONS = YES;
- GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
- GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
- GCC_WARN_ABOUT_RETURN_TYPE = YES;
- GCC_WARN_UNUSED_VARIABLE = YES;
- MACOSX_DEPLOYMENT_TARGET = 10.7;
- SDKROOT = macosx;
- };
- name = Release;
- };
- 1EE8C2761476A262002496F2 /* Debug */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- EXECUTABLE_PREFIX = lib;
- PRODUCT_NAME = "$(TARGET_NAME)";
- };
- name = Debug;
- };
- 1EE8C2771476A262002496F2 /* Release */ = {
- isa = XCBuildConfiguration;
- buildSettings = {
- EXECUTABLE_PREFIX = lib;
- PRODUCT_NAME = "$(TARGET_NAME)";
- };
- name = Release;
- };
-/* End XCBuildConfiguration section */
-
-/* Begin XCConfigurationList section */
- 1EE8C26B1476A262002496F2 /* Build configuration list for PBXProject "util" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- 1EE8C2731476A262002496F2 /* Debug */,
- 1EE8C2741476A262002496F2 /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
- 1EE8C2751476A262002496F2 /* Build configuration list for PBXNativeTarget "util" */ = {
- isa = XCConfigurationList;
- buildConfigurations = (
- 1EE8C2761476A262002496F2 /* Debug */,
- 1EE8C2771476A262002496F2 /* Release */,
- );
- defaultConfigurationIsVisible = 0;
- defaultConfigurationName = Release;
- };
-/* End XCConfigurationList section */
- };
- rootObject = 1EE8C2681476A262002496F2 /* Project object */;
-}