update to recent ProbLog.

This commit is contained in:
Vitor Santos Costa 2011-06-26 23:13:43 +01:00
parent 8f8e62ea63
commit be345a0387
34 changed files with 9801 additions and 129 deletions

View File

@ -30,6 +30,7 @@ BIBTEX=bibtex
PROGRAMS= \
$(srcdir)/problog.yap \
$(srcdir)/problog_lfi.yap \
$(srcdir)/dtproblog.yap \
$(srcdir)/problog_learning.yap
@ -54,9 +55,13 @@ PROBLOG_PROGRAMS= \
$(srcdir)/problog/nestedtries.yap \
$(srcdir)/problog/utils.yap \
$(srcdir)/problog/ad_converter.yap \
$(srcdir)/problog/termhandling.yap \
$(srcdir)/problog/completion.yap \
$(srcdir)/problog/discrete.yap \
$(srcdir)/problog/variables.yap
PROBLOG_EXAMPLES = \
$(srcdir)/problog_examples/alarm.pl \
$(srcdir)/problog_examples/graph.pl \
$(srcdir)/problog_examples/graph_tabled.pl \
$(srcdir)/problog_examples/learn_graph.pl \

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2011-01-16 19:24:10 +0100 (Sun, 16 Jan 2011) $
% $Revision: 5260 $
% $Date: 2011-04-08 19:30:08 +0200 (Fri, 08 Apr 2011) $
% $Revision: 5887 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -284,6 +284,7 @@
reset_non_ground_facts/0,
'::'/2,
probabilistic_fact/3,
continuous_fact/3,
init_problog/1,
problog_call/1,
problog_infer_forest_supported/0,
@ -302,7 +303,7 @@
% general yap modules
:- use_module(library(lists), [append/3,member/2,memberchk/2,reverse/2,select/3,nth1/3,nth1/4,nth0/4]).
:- use_module(library(terms), [variable_in_term/2] ).
:- use_module(library(terms), [variable_in_term/2,variant/2] ).
:- use_module(library(random), [random/1]).
:- use_module(library(system), [tmpnam/1,shell/2,delete_file/1,delete_file/2]).
:- use_module(library(ordsets), [list_to_ord_set/2, ord_insert/3, ord_union/3]).
@ -590,8 +591,8 @@ generate_atoms(N, A):-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% converts annotated disjunctions
term_expansion_intern(A, Module, C):-
term_expansion_intern_ad(A, Module, C).
term_expansion_intern((Head<--Body), Module, C):-
term_expansion_intern_ad((Head<--Body), Module,inference, C).
% converts ?:: prefix to ? :: infix, as handled by other clause
term_expansion_intern((Annotation::Fact), Module, ExpandedClause) :-
@ -836,17 +837,50 @@ problog_continuous_predicate(Name, Arity, ContinuousArgumentPosition, ProblogNam
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
in_interval(ID,Low,High) :-
number(Low),
number(High),
var(ID),
throw(error(instantiation_error,in_interval(ID,Low,High))).
in_interval(ID,Low,High) :-
var(Low),
throw(error(instantiation_error,in_interval(ID,Low,High))).
in_interval(ID,Low,High) :-
var(High),
throw(error(instantiation_error,in_interval(ID,Low,High))).
in_interval(ID,Low,High) :-
\+ number(Low),
throw(error(type_error(number,Low),in_interval(ID,Low,High))).
in_interval(ID,Low,High) :-
\+ number(High),
throw(error(type_error(number,High),in_interval(ID,Low,High))).
in_interval(ID,Low,High) :-
Low<High,
interval_merge(ID,interval(Low,High)).
below(ID,X) :-
var(ID),
throw(error(instantiation_error,below(ID,X))).
below(ID,X) :-
var(X),
throw(error(instantiation_error,below(ID,X))).
below(ID,X) :-
\+ number(X),
throw(error(type_error(number,X),below(ID,X))).
below(ID,X) :-
number(X),
interval_merge(ID,below(X)).
above(ID,X) :-
var(ID),
throw(error(instantiation_error,above(ID,X))).
above(ID,X) :-
var(X),
throw(error(instantiation_error,above(ID,X))).
above(ID,X) :-
\+ number(X),
throw(error(type_error(number,X),above(ID,X))).
above(ID,X) :-
number(X),
interval_merge(ID,above(X)).
interval_merge((_ID,GroundID,_Type),Interval) :-
atomic_concat([interval,'_',GroundID],Key),
b_getval(Key,OldInterval),
@ -1015,7 +1049,10 @@ probclause_id(ID) :-
% backtrack over all probabilistic facts
% must come before term_expansion
Prob::Goal :-
probabilistic_fact(Prob,Goal,_).
probabilistic_fact(Prob,Goal,_ID).
(V,Distribution)::Goal :-
continuous_fact((V,Distribution),Goal,_ID).
% backtrack over all probabilistic facts
probabilistic_fact(Prob,Goal,ID) :-
@ -1044,15 +1081,36 @@ probabilistic_fact(Prob,Goal,ID) :-
Prob is exp(LProb)
).
% generates unique IDs for proofs
continuous_fact((V,Distribution),Goal,ID) :-
get_internal_continuous_fact(ID,ProblogTerm,ProblogName,_ProblogArity,ContinuousPos),
% strip away problog_continuous
ProblogTerm=..[ProblogName,ID|Arguments],
nth1(ContinuousPos,Arguments,Distribution,Rest),
nth1(ContinuousPos,Arguments2,V,Rest),
atomic_concat(problogcontinuous_,Name,ProblogName),
% Build final term
Goal=..[Name|Arguments2].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% proof_id(-ID) generates a new ID for a proof
% reset_proof_id resets the ID counter to 0
%
% this ID is used by Hybrid ProbLog to identify proofs
% and later for disjoining them
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
proof_id(ID) :-
nb_getval(problog_proof_id,ID),
ID2 is ID+1,
nb_setval(problog_proof_id,ID2).
reset_problog_proof_id :-
reset_proof_id :-
nb_setval(problog_proof_id,0).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% access/update the probability of ID's fact
% hardware-access version: naively scan all problog-predicates (except if prob is recorded in static database),
@ -1094,8 +1152,10 @@ get_fact_probability(ID,Prob) :-
arg(ProblogArity,ProblogTerm,Log),
(Log = '?' ->
throw(error('Why do you want to know the probability of a decision?')) %fail
;
; ground(Log) ->
Prob is exp(Log)
;
Prob = p
).
get_fact_log_probability(ID,Prob) :-
@ -1167,9 +1227,28 @@ set_continuous_fact_parameters(ID,Parameters) :-
export_facts(Filename) :-
open(Filename,'write',Handle),
forall(P::Goal,
format(Handle,'~10f :: ~q.~n',[P,Goal])),
%compiled ADs
forall((current_predicate(user:ad_intern/3),user:ad_intern(Original,ID,Facts)),
print_ad_intern(Handle,Original,ID,Facts)
),
nl(Handle),
% probabilistic facts
% but comment out auxiliary facts stemmig from
% compiled ADs
forall(P::Goal,
(
is_mvs_aux_fact(Goal)
->
format(Handle,'% ~10f :: ~q.~n',[P,Goal]);
format(Handle,'~10f :: ~q.~n',[P,Goal])
)
),
nl(Handle),
% continuous facts (Hybrid ProbLog)
forall(continuous_fact(ID),
(
get_continuous_fact_parameters(ID,Param),
@ -1179,6 +1258,30 @@ export_facts(Filename) :-
close(Handle).
is_mvs_aux_fact(A) :-
functor(A,B,_),
atomic_concat(mvs_fact_,_,B).
% code for printing the compiled ADs
print_ad_intern(Handle,(Head<--Body),_ID,Facts) :-
print_ad_intern(Head,Facts,0.0,Handle),
format(Handle,' <-- ~q.~n',[Body]).
print_ad_intern((A1;B1),[A2|B2],Mass,Handle) :-
once(print_ad_intern_one(A1,A2,Mass,NewMass,Handle)),
format(Handle,'; ',[]),
print_ad_intern(B1,B2,NewMass,Handle).
print_ad_intern(_::Fact,[],Mass,Handle) :-
P2 is 1.0 - Mass,
format(Handle,'~10f :: ~q',[P2,Fact]).
print_ad_intern_one(_::Fact,_::AuxFact,Mass,NewMass,Handle) :-
% ask problog to get the fact_id
once(probabilistic_fact(P,AuxFact,_FactID)),
P2 is P * (1-Mass),
NewMass is Mass+P2,
format(Handle,'~10f :: ~q',[P2,Fact]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% recover fact for given id
% list version not exported (yet?)
@ -1244,7 +1347,7 @@ add_to_proof(ID, LogProb) :-
% check whether negation of this fact is already used in proof
\+ open_end_memberchk(not(ID),IDs),
( % check whether this fact is already used in proof
( % check whether this fact is already used in proof
open_end_memberchk(ID, IDs)
->
true;
@ -1410,7 +1513,7 @@ upper_bound(List) :-
% to set up environment for proving
% it resets control flags, method specific values to be set afterwards!
init_problog(Threshold) :-
reset_problog_proof_id,
reset_proof_id,
reset_non_ground_facts,
reset_control,
LT is log(Threshold),
@ -2795,44 +2898,40 @@ build_trie(K-best, Goal, Trie) :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
write_bdd_struct_script(Trie,BDDFile,Variables) :-
% Check whether we use Hybrid ProbLog
(
hybrid_proof(_,_,_)
->
( % Yes! run the disjoining stuff
retractall(hybrid_proof_disjoint(_,_,_,_)),
disjoin_hybrid_proofs,
(
hybrid_proof(_,_,_) % Check whether we use Hybrid ProbLog
->
(
% Yes! run the disjoining stuff
retractall(hybrid_proof_disjoint(_,_,_,_)),
disjoin_hybrid_proofs,
init_ptree(OriTrie), % use this as tmp ptree
%%%%%%%%%%%%%%%%%%%%%
( % go over all stored proofs
enum_member_ptree(List,OriTrie1),
(
List=[_|_]
->
Proof=List;
Proof=[List]
),
(
select(continuous(ProofID),Proof,Rest)
->
(
% this proof is using continuous facts
all_hybrid_subproofs(ProofID,List2),
append(Rest,List2,NewProof),
insert_ptree(NewProof,OriTrie)
);
insert_ptree(Proof,OriTrie)
),
fail;
true
)
%%%%%%%%%%%%%%%%%%%%%
) ;
% Nope, just pass on the Trie
OriTrie=OriTrie1
),
init_ptree(OriTrie), % use this as tmp ptree
forall(enum_member_ptree(List,OriTrie1), % go over all stored proofs
(
(
List=[_|_]
->
Proof=List;
Proof=[List]
),
(
select(continuous(ProofID),Proof,Rest)
->
(
% this proof is using continuous facts
all_hybrid_subproofs(ProofID,List2),
append(Rest,List2,NewProof),
insert_ptree(NewProof,OriTrie)
);
insert_ptree(Proof,OriTrie)
)
)
)
);
% Nope, just pass on the Trie
OriTrie=OriTrie1
),
((problog_flag(variable_elimination, true), nb_getval(problog_nested_tries, false)) ->
statistics(walltime, _),

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-13 18:15:14 +0100 (Mon, 13 Dec 2010) $
% $Revision: 5125 $
% $Date: 2011-04-26 15:48:52 +0200 (Tue, 26 Apr 2011) $
% $Revision: 6371 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -204,24 +204,20 @@
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module(ad_converter,[compile_annotated_disjunction/5,
compile_tunable_annotated_disjunction/5,
proper_annotated_disjunction/1,
proper_tunable_annotated_disjunction/1,
term_expansion_intern_ad/3,
:- module(ad_converter,[term_expansion_intern_ad/4,
op(1149, yfx, <-- ),
op( 550, yfx, :: )
]).
% general yap modules
:- use_module(library(lists),[reverse/2,member/2,append/3]).
:- use_module(library(lists),[reverse/2,member/2,memberchk/2,append/3]).
:- use_module(flags).
:- style_check(all).
:- yap_flag(unknown,error).
:- discontiguous user:ad_intern/2.
:- discontiguous user:(<--)/2, problog:(<--)/2.
:- op( 550, yfx, :: ).
@ -230,29 +226,43 @@
:- initialization(problog_define_flag(show_ad_compilation,problog_flag_validate_boolean,'show compiled code for ADs',false,annotated_disjunctions)).
:- initialization(problog_define_flag(ad_cpl_semantics,problog_flag_validate_boolean,'use CP-logics semantics for ADs',true,annotated_disjunctions)).
:- initialization(problog_define_flag(ad_sumto1_learning,problog_flag_validate_boolean,'make p_i sum to 1 for learning',true,annotated_disjunctions)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
term_expansion_intern_ad( (Head<--Body),Module,ad_intern((Head<--Body),ID)) :-
term_expansion_intern_ad( (Head<--Body),Module,Mode,Result) :-
problog_flag(ad_cpl_semantics,AD_CPL_Semantics),
(
proper_tunable_annotated_disjunction(Head)
->
compile_tunable_annotated_disjunction(Head,Body,Facts,Bodies,ID,AD_CPL_Semantics);
compile_tunable_annotated_disjunction(Head,Body,Facts,Bodies,ID,AD_CPL_Semantics,Mode);
(
proper_annotated_disjunction(Head),
compile_annotated_disjunction(Head,Body,Facts,Bodies,ID,AD_CPL_Semantics)
proper_annotated_disjunction(Head,Sum_of_P_in_Head)
->
compile_annotated_disjunction(Head,Body,Facts,Bodies,ID,AD_CPL_Semantics,Mode,Sum_of_P_in_Head);
throw(error(invalid_annotated_disjunction,(Head<--Body)))
)
),
forall(member(F,Facts),(once(problog:term_expansion_intern(F,Module,Atom)),
assertz(problog:Atom))),
forall(member(B,Bodies),assertz(Module:B)),
findall(problog:Atom,(
member(F,Facts),
once(problog:term_expansion_intern(F,Module,Atom))
),Result_Atoms),
(
Mode==lfi_learning
->
findall(Module:myclause(H,B),member((H:-B),Bodies),Result_Bodies);
findall(Module:B,member(B,Bodies),Result_Bodies)
),
append(Result_Atoms,Result_Bodies,Result),
problog_flag(show_ad_compilation,Show_AD_compilation),
(
Show_AD_compilation==true
->
@ -289,7 +299,7 @@ get_next_unique_id(ID) :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
proper_annotated_disjunction(AD) :-
proper_annotated_disjunction(AD,Sum) :-
proper_annotated_disjunction(AD,0.0,Sum),
Sum=<1.
@ -316,7 +326,7 @@ proper_tunable_annotated_disjunction((X;Y)) :-
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
compile_tunable_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_Semantics) :-
compile_tunable_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_Semantics,Mode) :-
get_next_unique_id(Extra_ID),
(
@ -325,16 +335,28 @@ compile_tunable_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_S
term_variables(Body,Body_Vars);
Body_Vars=[]
),
convert_a_tunable(Head,Extra_ID,[],Facts,Body_Vars),
convert_b(Head,Body,_NewBody,Extra_ID,[],Bodies,Body_Vars),
reverse(Facts,Facts2),
convert_a_tunable(Head,Extra_ID,[],Facts0,Body_Vars),
problog_flag(ad_sumto1_learning,AD_SumTo1_Learning),
(
AD_SumTo1_Learning==true
->
Facts0=[_|Facts1];
Facts1=Facts0
),
reverse(Facts1,Facts2),
convert_b(Head,Body,_NewBody,Extra_ID,[],Bodies,Body_Vars,Mode,Facts2),
reverse(Bodies,Bodies2).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
compile_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_Semantics) :-
compile_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_Semantics,Mode,ProbSum) :-
get_next_unique_id(Extra_ID),
(
@ -344,10 +366,20 @@ compile_annotated_disjunction(Head,Body,Facts2,Bodies2,Extra_ID,AD_CPL_Semantics
Body_Vars=[]
),
convert_a(Head,0.0,_Acc,Extra_ID,[],Facts,Body_Vars),
convert_b(Head,Body,_NewBody,Extra_ID,[],Bodies,Body_Vars),
convert_a(Head,0.0,_Acc,Extra_ID,[],Facts0,Body_Vars),
(
abs(ProbSum-1.0) < 0.0000001
->
Facts0=[_|Facts1];
Facts1=Facts0
),
reverse(Facts1,Facts2),
convert_b(Head,Body,_NewBody,Extra_ID,[],Bodies,Body_Vars,Mode,Facts2),
reverse(Facts,Facts2),
reverse(Bodies,Bodies2).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -365,15 +397,10 @@ convert_a(P::Atom,OldAcc,NewAcc,Extra_ID,OldFacts,[P1::ProbFact|OldFacts],Body_V
ProbFact =.. [NewAtom|NewAllArguments],
(
P=:=0
(P=:=0; OldAcc=:=0)
->
P1 is 0.0 ;
(
OldAcc=:=0
->
P1 is P;
P1 is P/(1-OldAcc)
)
P1 is min(P/(1-OldAcc),1.0)
),
NewAcc is OldAcc+P.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -382,7 +409,7 @@ convert_a(P::Atom,OldAcc,NewAcc,Extra_ID,OldFacts,[P1::ProbFact|OldFacts],Body_V
convert_a_tunable((X;Y),Extra_ID,OldFacts,Facts,Body_Vars) :-
convert_a_tunable(X,Extra_ID,OldFacts,NewFacts,Body_Vars),
convert_a_tunable(Y,Extra_ID,NewFacts,Facts,Body_Vars).
convert_a_tunable(P::Atom,Extra_ID,OldFacts,[P::ProbFact|OldFacts],Body_Vars) :-
convert_a_tunable(t(_)::Atom,Extra_ID,OldFacts,[t(_)::ProbFact|OldFacts],Body_Vars) :-
Atom =.. [Functor|AllArguments],
append(AllArguments,Body_Vars,NewAllArguments),
length(AllArguments,Arity),
@ -393,10 +420,10 @@ convert_a_tunable(P::Atom,Extra_ID,OldFacts,[P::ProbFact|OldFacts],Body_Vars) :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
convert_b((X;Y),OldBody,Body,ExtraID,OldBodies,Bodies,Body_Vars) :-
convert_b(X,OldBody,NewBody,ExtraID,OldBodies,NewBodies,Body_Vars),
convert_b(Y,NewBody,Body,ExtraID,NewBodies,Bodies,Body_Vars).
convert_b(_::Atom,OldBody,NewBody,Extra_ID,OldBodies,[(Atom:-ThisBody)|OldBodies],Body_Vars) :-
convert_b((X;Y),OldBody,Body,ExtraID,OldBodies,Bodies,Body_Vars,Mode,Facts) :-
convert_b(X,OldBody,NewBody,ExtraID,OldBodies,NewBodies,Body_Vars,Mode,Facts),
convert_b(Y,NewBody,Body,ExtraID,NewBodies,Bodies,Body_Vars,Mode,Facts).
convert_b(_::Atom,OldBody,NewBody,Extra_ID,OldBodies,[(Atom:-ThisBody)|OldBodies],Body_Vars,Mode,Facts) :-
Atom =.. [Functor|AllArguments],
append(AllArguments,Body_Vars,NewAllArguments),
@ -404,8 +431,19 @@ convert_b(_::Atom,OldBody,NewBody,Extra_ID,OldBodies,[(Atom:-ThisBody)|OldBodies
atomic_concat([mvs_fact_,Functor,'_',Arity,'_',Extra_ID],NewFunctor),
ProbFact =.. [NewFunctor|NewAllArguments],
tuple_append(OldBody,ProbFact,ThisBody),
tuple_append(OldBody,problog_not(ProbFact),NewBody).
(
memberchk(_::ProbFact,Facts)
->
tuple_append(OldBody,ProbFact,ThisBody);
ThisBody=OldBody
),
(
Mode==lfi_learning
->
tuple_append(OldBody,\+ProbFact,NewBody);
tuple_append(OldBody,problog_not(ProbFact),NewBody)
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,417 @@
%%% -*- Mode: Prolog; -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-02 15:20:15 +0100 (Thu, 02 Dec 2010) $
% $Revision: 5043 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
%
% ProbLog was developed at Katholieke Universiteit Leuven
%
% Copyright 2009
% Angelika Kimmig, Vitor Santos Costa, Bernd Gutmann
%
% Main authors of this file:
% Bernd Gutmann
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Artistic License 2.0
%
% Copyright (c) 2000-2006, The Perl Foundation.
%
% Everyone is permitted to copy and distribute verbatim copies of this
% license document, but changing it is not allowed. Preamble
%
% This license establishes the terms under which a given free software
% Package may be copied, modified, distributed, and/or
% redistributed. The intent is that the Copyright Holder maintains some
% artistic control over the development of that Package while still
% keeping the Package available as open source and free software.
%
% You are always permitted to make arrangements wholly outside of this
% license directly with the Copyright Holder of a given Package. If the
% terms of this license do not permit the full use that you propose to
% make of the Package, you should contact the Copyright Holder and seek
% a different licensing arrangement. Definitions
%
% "Copyright Holder" means the individual(s) or organization(s) named in
% the copyright notice for the entire Package.
%
% "Contributor" means any party that has contributed code or other
% material to the Package, in accordance with the Copyright Holder's
% procedures.
%
% "You" and "your" means any person who would like to copy, distribute,
% or modify the Package.
%
% "Package" means the collection of files distributed by the Copyright
% Holder, and derivatives of that collection and/or of those files. A
% given Package may consist of either the Standard Version, or a
% Modified Version.
%
% "Distribute" means providing a copy of the Package or making it
% accessible to anyone else, or in the case of a company or
% organization, to others outside of your company or organization.
%
% "Distributor Fee" means any fee that you charge for Distributing this
% Package or providing support for this Package to another party. It
% does not mean licensing fees.
%
% "Standard Version" refers to the Package if it has not been modified,
% or has been modified only in ways explicitly requested by the
% Copyright Holder.
%
% "Modified Version" means the Package, if it has been changed, and such
% changes were not explicitly requested by the Copyright Holder.
%
% "Original License" means this Artistic License as Distributed with the
% Standard Version of the Package, in its current version or as it may
% be modified by The Perl Foundation in the future.
%
% "Source" form means the source code, documentation source, and
% configuration files for the Package.
%
% "Compiled" form means the compiled bytecode, object code, binary, or
% any other form resulting from mechanical transformation or translation
% of the Source form.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permission for Use and Modification Without Distribution
%
% (1) You are permitted to use the Standard Version and create and use
% Modified Versions for any purpose without restriction, provided that
% you do not Distribute the Modified Version.
%
% Permissions for Redistribution of the Standard Version
%
% (2) You may Distribute verbatim copies of the Source form of the
% Standard Version of this Package in any medium without restriction,
% either gratis or for a Distributor Fee, provided that you duplicate
% all of the original copyright notices and associated disclaimers. At
% your discretion, such verbatim copies may or may not include a
% Compiled form of the Package.
%
% (3) You may apply any bug fixes, portability changes, and other
% modifications made available from the Copyright Holder. The resulting
% Package will still be considered the Standard Version, and as such
% will be subject to the Original License.
%
% Distribution of Modified Versions of the Package as Source
%
% (4) You may Distribute your Modified Version as Source (either gratis
% or for a Distributor Fee, and with or without a Compiled form of the
% Modified Version) provided that you clearly document how it differs
% from the Standard Version, including, but not limited to, documenting
% any non-standard features, executables, or modules, and provided that
% you do at least ONE of the following:
%
% (a) make the Modified Version available to the Copyright Holder of the
% Standard Version, under the Original License, so that the Copyright
% Holder may include your modifications in the Standard Version. (b)
% ensure that installation of your Modified Version does not prevent the
% user installing or running the Standard Version. In addition, the
% modified Version must bear a name that is different from the name of
% the Standard Version. (c) allow anyone who receives a copy of the
% Modified Version to make the Source form of the Modified Version
% available to others under (i) the Original License or (ii) a license
% that permits the licensee to freely copy, modify and redistribute the
% Modified Version using the same licensing terms that apply to the copy
% that the licensee received, and requires that the Source form of the
% Modified Version, and of any works derived from it, be made freely
% available in that license fees are prohibited but Distributor Fees are
% allowed.
%
% Distribution of Compiled Forms of the Standard Version or
% Modified Versions without the Source
%
% (5) You may Distribute Compiled forms of the Standard Version without
% the Source, provided that you include complete instructions on how to
% get the Source of the Standard Version. Such instructions must be
% valid at the time of your distribution. If these instructions, at any
% time while you are carrying out such distribution, become invalid, you
% must provide new instructions on demand or cease further
% distribution. If you provide valid instructions or cease distribution
% within thirty days after you become aware that the instructions are
% invalid, then you do not forfeit any of your rights under this
% license.
%
% (6) You may Distribute a Modified Version in Compiled form without the
% Source, provided that you comply with Section 4 with respect to the
% Source of the Modified Version.
%
% Aggregating or Linking the Package
%
% (7) You may aggregate the Package (either the Standard Version or
% Modified Version) with other packages and Distribute the resulting
% aggregation provided that you do not charge a licensing fee for the
% Package. Distributor Fees are permitted, and licensing fees for other
% components in the aggregation are permitted. The terms of this license
% apply to the use and Distribution of the Standard or Modified Versions
% as included in the aggregation.
%
% (8) You are permitted to link Modified and Standard Versions with
% other works, to embed the Package in a larger work of your own, or to
% build stand-alone binary or bytecode versions of applications that
% include the Package, and Distribute the result without restriction,
% provided the result does not expose a direct interface to the Package.
%
% Items That are Not Considered Part of a Modified Version
%
% (9) Works (including, but not limited to, modules and scripts) that
% merely extend or make use of the Package, do not, by themselves, cause
% the Package to be a Modified Version. In addition, such works are not
% considered parts of the Package itself, and are not subject to the
% terms of this license.
%
% General Provisions
%
% (10) Any use, modification, and distribution of the Standard or
% Modified Versions is governed by this Artistic License. By using,
% modifying or distributing the Package, you accept this license. Do not
% use, modify, or distribute the Package, if you do not accept this
% license.
%
% (11) If your Modified Version has been derived from a Modified Version
% made by someone other than you, you are nevertheless required to
% ensure that your Modified Version complies with the requirements of
% this license.
%
% (12) This license does not grant you the right to use any trademark,
% service mark, tradename, or logo of the Copyright Holder.
%
% (13) This license includes the non-exclusive, worldwide,
% free-of-charge patent license to make, have made, use, offer to sell,
% sell, import and otherwise transfer the Package with respect to any
% patent claims licensable by the Copyright Holder that are necessarily
% infringed by the Package. If you institute patent litigation
% (including a cross-claim or counterclaim) against any party alleging
% that the Package constitutes direct or contributory patent
% infringement, then this Artistic License to you shall terminate on the
% date that such litigation is filed.
%
% (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT
% HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED
% WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
% PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT
% PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT
% HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT,
% INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
% OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Discrete probability distributions for ProbLog
%
% this file contains predicates to emulate discrete distributions in ProbLog
%
% uniform(I,N,ID)
% emulates a uniform discrete distribution
% P(I) = 1/N for I in {1,2,...,N}
% If I is a variable, the predicate backtracks over all
% possible values for I
% ID has to be ground, it is an identifier which - if in the same proof -
% reused, will always return the same value
%
% binomial(K,N,P,ID)
% emulates a binomial distribution
% P(K) = (N over K) x P^K x (1-P)^(N-K) for K in {0,1,...,N}
% If K is a variable, the predicate backtracks over all
% possible values for K
% ID has to be ground, it is an identifier which - if in the same proof -
% reused, will always return the same value
%
% poisson(K,Lambda,ID)
% emulates a Poisson distribution
% P(K) = Lamda^K / K! x exp(-Lambda) for K in {0,1,2, ....}
% If K is a variable, the predicate backtracks over all
% possible values for K
% ID has to be ground, it is an identifier which - if in the same proof -
% reused, will always return the same value
%
%
% Author : Bernd Gutmann, bernd.gutmann@cs.kuleuven.be
% Version : January 14, 2009
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module(discrete, [uniform/3,binomial/4,poisson/3]).
:- use_module('../problog').
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A distribution over 1,2, ..., N
% where P(I) := 1/N
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Prob::p_uniform(_I,_N,_ID,Prob).
uniform(I,N,ID) :-
integer(N),
N>0,
( var(I) ; integer(I), I>0, I=<N),
uniform(1,I,true,N,ID).
uniform(I,I,Old,N,ID) :-
I=<N,
FactProb is 1/(N-I+1),
call(Old),
p_uniform(I,N,ID,FactProb).
uniform(I,I2,Old,N,ID) :-
I<N,
FactProb is 1/(N-I+1),
NextI is I+1,
uniform(NextI,I2,(problog_not(p_uniform(I,N,ID,FactProb)),Old),N,ID).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Binomial Distribution
% K in { 0,1,2,3, ... }
% Lambda >= 0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Prob::p_binomial(_K,_N,_P,_ID,Prob).
binomial(K,N,P,ID) :-
number(P),
P >= 0,
P =< 1,
integer(N),
N>=0,
( var(K) ; integer(K),K>=0,K=<N),
binomial(0,K,N,P,true,0.0,ID).
binomial(K,KResult,N,P,Old,ProbAcc,ID) :-
% KResult is a number, make sure, not to go over it
% safes some time
(
number(KResult)
->
K=<KResult;
true
),
binomial_coefficient(N,K,BinomCoeff),
Prob is BinomCoeff * (P ** K) * ((1-P) ** (N-K)),
FactProb is Prob / (1-ProbAcc),
% this check stops the derivation, if the floating-point-based
% rounding errors get too big
FactProb > 0.0,
FactProb =< 1.0,
(
(
call(Old),
p_binomial(K,N,P,ID,FactProb),
KResult=K
); (
K<N,
NextK is K+1,
NextProbAcc is ProbAcc+Prob,
binomial(NextK,KResult,N,P,(problog_not(p_binomial(K,N,P,ID,FactProb)),Old),NextProbAcc,ID)
)
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Poisson Distribution
% K in { 0,1,2,3, ... } or var(K)
% Lambda >= 0
% ID has to be ground
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
P :: p_poisson(_K,_Lambda,_ID,P).
poisson(K,Lambda,ID) :-
( var(K); integer(K),K>=0 ),
number(Lambda),
Lambda>=0,
ground(ID),
poisson(0,K,true,Lambda,0.0,ID).
poisson(K,K2,Old,Lambda,ProbAcc,ID) :-
% KResult is a number, make sure, not to go over it
% safes some time
(
integer(K2)
->
K=<K2;
true
),
power_over_factorial(K,Lambda,Part1),
% Prob is P(K) for a Poisson distribution with Lambda
Prob is Part1 * exp(-Lambda),
% now we have to determine the fact probability
% conditioned on the aggregated probabilities so far
FactProb is Prob/(1-ProbAcc),
% this check stops the derivation, if the floating-point-based
% rounding errors get too big
FactProb > 0.0,
FactProb =< 1.0,
(
(
call(Old),
p_poisson(K,Lambda,ID,FactProb),
K2=K
); (
NextK is K+1,
NextProbAcc is ProbAcc+Prob,
poisson(NextK,K2,(problog_not(p_poisson(K,Lambda,ID,FactProb)),Old),Lambda,NextProbAcc,ID)
)
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% calculates (Lambda ** N) / N!
power_over_factorial(N,Lambda,Result) :-
integer(N),
N>=0,
power_over_factorial(N,Lambda,1.0,Result).
power_over_factorial(N,Lambda,Old,Result) :-
(
N>0
->
(
N2 is N-1,
New is Old * Lambda/N,
power_over_factorial(N2,Lambda,New,Result)
); Result=Old
).
% calculates (N \over K) = N!/(K! * (N-K)!)
binomial_coefficient(N,K,Result) :-
integer(K),
K >= 0,
binomial_coefficient(K,N,1,Result).
binomial_coefficient(I,N,Product,Result) :-
(
I=0
->
Result=Product;
(
I2 is I-1,
Product2 is Product * (N+1-I)/I,
binomial_coefficient(I2,N,Product2,Result)
)
).

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-02 15:20:15 +0100 (Thu, 02 Dec 2010) $
% $Revision: 5043 $
% $Date: 2011-02-08 16:00:57 +0100 (Tue, 08 Feb 2011) $
% $Revision: 5614 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-02 15:20:15 +0100 (Thu, 02 Dec 2010) $
% $Revision: 5043 $
% $Date: 2011-04-21 14:18:59 +0200 (Thu, 21 Apr 2011) $
% $Revision: 6364 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -207,11 +207,12 @@
%%%%%%%%
% Collected OS depended instructions
%%%%%%%%
:- module(print_learning, [format_learning/3]).
:- module(print_learning, [format_learning/3,format_learning_rule/3]).
% load our own modules
:- use_module(flags).
:- use_module(termhandling).
:- initialization(problog_define_flag(verbosity_learning, problog_flag_validate_0to5,'How much output shall be given (0=nothing,5=all)',5, learning_general)).
@ -230,3 +231,42 @@ format_learning(Level,String,Arguments) :-
flush_output(user).
format_learning(_,_,_) :-
true.
%========================================================================
%=
%=
%=
%========================================================================
format_learning_rule(D,'$atom'(A)):-
format_learning(D,'~q',[A]).
format_learning_rule(D,\+A):-
format_learning(D,'\+',[]),
format_learning_rule(D,A).
format_learning_rule(D,'true'):-
format_learning(D,'true',[]).
format_learning_rule(D,'false'):-
format_learning(D,'false',[]).
format_learning_rule(D,(First<=>Second)):-
format_learning_rule(D,First),
format_learning(D,'<==>',[]),
format_learning_rule(D,Second)
.
format_learning_rule(D,(First;Second)):-
format_learning(D,'(',[]),
format_learning_rule(D,First),
format_learning(D,';',[]),
format_learning_rule(D,Second),
format_learning(D,')',[])
.
format_learning_rule(D,(First,Second)):-
format_learning_rule(D,First),
format_learning(D,',',[]),
format_learning_rule(D,Second)
.
format_learning_rule(D,R,Key):-
(format_learning_rule(D,R) ; (format('~q ',[flr(D,R,Key)]),throw(ball))),
format_learning(D,' (~q)~n',[Key]).

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2011-01-16 19:24:10 +0100 (Sun, 16 Jan 2011) $
% $Revision: 5260 $
% $Date: 2011-04-11 17:23:11 +0200 (Mon, 11 Apr 2011) $
% $Revision: 5920 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -679,6 +679,10 @@ writemap([Name|Names],[Fact|Facts]):-
writemap(Names, Facts).
bdd_vars_script([], []).
bdd_vars_script([false|T], Names):-
bdd_vars_script(T, Names).
bdd_vars_script([true|T], Names):-
bdd_vars_script(T, Names).
bdd_vars_script([not(A)|B], Names) :-
!, bdd_vars_script([A|B], Names).
bdd_vars_script([A|B], [NameA|Names]) :-

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-13 16:29:18 +0100 (Mon, 13 Dec 2010) $
% $Revision: 5122 $
% $Date: 2011-04-11 17:23:11 +0200 (Mon, 11 Apr 2011) $
% $Revision: 5920 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -305,21 +305,21 @@ problog_table(P) :-
problog_table(P, M).
problog_table(M:P, _) :-
problog_table(P, M).
problog_table(P, M).
problog_table((P1, P2), M) :-
problog_table(P1, M),
problog_table(P2, M).
problog_table(P1, M),
problog_table(P2, M).
problog_table(Name/Arity, Module) :-
length(Args,Arity),
Head =.. [Name|Args],
\+ predicate_property(Module:Head, dynamic), !,
throw(error('problog_table: Problog tabling currently requires the predicate to be declared dynamic and compiles it to static.')).
length(Args,Arity),
Head =.. [Name|Args],
\+ predicate_property(Module:Head, dynamic), !,
throw(error('problog_table: Problog tabling currently requires the predicate to be declared dynamic and compiles it to static.')).
problog_table(Name/Arity, Module) :-
length(Args,Arity),
Head =.. [Name|Args],
atom_concat(['problog_', Name, '_original'], OriginalName),
atom_concat(['problog_', Name, '_mctabled'], MCName),
atom_concat(['problog_', Name, '_tabled'], ExactName),
length(Args,Arity),
Head =.. [Name|Args],
atom_concat(['problog_', Name, '_original'], OriginalName),
atom_concat(['problog_', Name, '_mctabled'], MCName),
atom_concat(['problog_', Name, '_tabled'], ExactName),
% Monte carlo tabling
catch((table(Module:MCName/Arity),

View File

@ -0,0 +1,454 @@
%%% -*- Mode: Prolog; -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2011-04-09 12:00:00 +0200 (Sat, 09 Apr 2011) $
% $Revision: 5890 $
%
% Main authors of this file:
% Bernd Gutmann
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Artistic License 2.0
%
% Copyright (c) 2000-2006, The Perl Foundation.
%
% Everyone is permitted to copy and distribute verbatim copies of this
% license document, but changing it is not allowed. Preamble
%
% This license establishes the terms under which a given free software
% Package may be copied, modified, distributed, and/or
% redistributed. The intent is that the Copyright Holder maintains some
% artistic control over the development of that Package while still
% keeping the Package available as open source and free software.
%
% You are always permitted to make arrangements wholly outside of this
% license directly with the Copyright Holder of a given Package. If the
% terms of this license do not permit the full use that you propose to
% make of the Package, you should contact the Copyright Holder and seek
% a different licensing arrangement. Definitions
%
% "Copyright Holder" means the individual(s) or organization(s) named in
% the copyright notice for the entire Package.
%
% "Contributor" means any party that has contributed code or other
% material to the Package, in accordance with the Copyright Holder's
% procedures.
%
% "You" and "your" means any person who would like to copy, distribute,
% or modify the Package.
%
% "Package" means the collection of files distributed by the Copyright
% Holder, and derivatives of that collection and/or of those files. A
% given Package may consist of either the Standard Version, or a
% Modified Version.
%
% "Distribute" means providing a copy of the Package or making it
% accessible to anyone else, or in the case of a company or
% organization, to others outside of your company or organization.
%
% "Distributor Fee" means any fee that you charge for Distributing this
% Package or providing support for this Package to another party. It
% does not mean licensing fees.
%
% "Standard Version" refers to the Package if it has not been modified,
% or has been modified only in ways explicitly requested by the
% Copyright Holder.
%
% "Modified Version" means the Package, if it has been changed, and such
% changes were not explicitly requested by the Copyright Holder.
%
% "Original License" means this Artistic License as Distributed with the
% Standard Version of the Package, in its current version or as it may
% be modified by The Perl Foundation in the future.
%
% "Source" form means the source code, documentation source, and
% configuration files for the Package.
%
% "Compiled" form means the compiled bytecode, object code, binary, or
% any other form resulting from mechanical transformation or translation
% of the Source form.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permission for Use and Modification Without Distribution
%
% (1) You are permitted to use the Standard Version and create and use
% Modified Versions for any purpose without restriction, provided that
% you do not Distribute the Modified Version.
%
% Permissions for Redistribution of the Standard Version
%
% (2) You may Distribute verbatim copies of the Source form of the
% Standard Version of this Package in any medium without restriction,
% either gratis or for a Distributor Fee, provided that you duplicate
% all of the original copyright notices and associated disclaimers. At
% your discretion, such verbatim copies may or may not include a
% Compiled form of the Package.
%
% (3) You may apply any bug fixes, portability changes, and other
% modifications made available from the Copyright Holder. The resulting
% Package will still be considered the Standard Version, and as such
% will be subject to the Original License.
%
% Distribution of Modified Versions of the Package as Source
%
% (4) You may Distribute your Modified Version as Source (either gratis
% or for a Distributor Fee, and with or without a Compiled form of the
% Modified Version) provided that you clearly document how it differs
% from the Standard Version, including, but not limited to, documenting
% any non-standard features, executables, or modules, and provided that
% you do at least ONE of the following:
%
% (a) make the Modified Version available to the Copyright Holder of the
% Standard Version, under the Original License, so that the Copyright
% Holder may include your modifications in the Standard Version. (b)
% ensure that installation of your Modified Version does not prevent the
% user installing or running the Standard Version. In addition, the
% modified Version must bear a name that is different from the name of
% the Standard Version. (c) allow anyone who receives a copy of the
% Modified Version to make the Source form of the Modified Version
% available to others under (i) the Original License or (ii) a license
% that permits the licensee to freely copy, modify and redistribute the
% Modified Version using the same licensing terms that apply to the copy
% that the licensee received, and requires that the Source form of the
% Modified Version, and of any works derived from it, be made freely
% available in that license fees are prohibited but Distributor Fees are
% allowed.
%
% Distribution of Compiled Forms of the Standard Version or
% Modified Versions without the Source
%
% (5) You may Distribute Compiled forms of the Standard Version without
% the Source, provided that you include complete instructions on how to
% get the Source of the Standard Version. Such instructions must be
% valid at the time of your distribution. If these instructions, at any
% time while you are carrying out such distribution, become invalid, you
% must provide new instructions on demand or cease further
% distribution. If you provide valid instructions or cease distribution
% within thirty days after you become aware that the instructions are
% invalid, then you do not forfeit any of your rights under this
% license.
%
% (6) You may Distribute a Modified Version in Compiled form without the
% Source, provided that you comply with Section 4 with respect to the
% Source of the Modified Version.
%
% Aggregating or Linking the Package
%
% (7) You may aggregate the Package (either the Standard Version or
% Modified Version) with other packages and Distribute the resulting
% aggregation provided that you do not charge a licensing fee for the
% Package. Distributor Fees are permitted, and licensing fees for other
% components in the aggregation are permitted. The terms of this license
% apply to the use and Distribution of the Standard or Modified Versions
% as included in the aggregation.
%
% (8) You are permitted to link Modified and Standard Versions with
% other works, to embed the Package in a larger work of your own, or to
% build stand-alone binary or bytecode versions of applications that
% include the Package, and Distribute the result without restriction,
% provided the result does not expose a direct interface to the Package.
%
% Items That are Not Considered Part of a Modified Version
%
% (9) Works (including, but not limited to, modules and scripts) that
% merely extend or make use of the Package, do not, by themselves, cause
% the Package to be a Modified Version. In addition, such works are not
% considered parts of the Package itself, and are not subject to the
% terms of this license.
%
% General Provisions
%
% (10) Any use, modification, and distribution of the Standard or
% Modified Versions is governed by this Artistic License. By using,
% modifying or distributing the Package, you accept this license. Do not
% use, modify, or distribute the Package, if you do not accept this
% license.
%
% (11) If your Modified Version has been derived from a Modified Version
% made by someone other than you, you are nevertheless required to
% ensure that your Modified Version complies with the requirements of
% this license.
%
% (12) This license does not grant you the right to use any trademark,
% service mark, tradename, or logo of the Copyright Holder.
%
% (13) This license includes the non-exclusive, worldwide,
% free-of-charge patent license to make, have made, use, offer to sell,
% sell, import and otherwise transfer the Package with respect to any
% patent claims licensable by the Copyright Holder that are necessarily
% infringed by the Package. If you institute patent litigation
% (including a cross-claim or counterclaim) against any party alleging
% that the Package constitutes direct or contributory patent
% infringement, then this Artistic License to you shall terminate on the
% date that such litigation is filed.
%
% (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT
% HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED
% WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
% PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT
% PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT
% HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT,
% INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
% OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module(termhandling, [term_element/2,
propagate/5,
propagate_interpretation/3,
simplify/3,
list_to_disjunction/2,
list_to_conjunction/2,
op( 551, yfx, <=> ),
not/2]).
% propagate( +OldTerm, +AtomToReplace, +ReplacementTermForAtom, -NewTerm, -ReplaceHasHappend).
% simplify(+OldTerm,-NewTerm,-SimplificationHasHappend).
% list_to_disjunction(+list,-Disjunction).
% list_to_conjunction(+list,+Conjunction).
:- op( 551, yfx, <=> ).
:- style_check(all).
:- yap_flag(unknown,error).
%========================================================================
%=
%=
%= term_element(+GroundTerm, ?Atom)
%========================================================================
term_element((X,Y),Z) :-
(term_element(X,Z);term_element(Y,Z)).
term_element((X;Y),Z) :-
(term_element(X,Z);term_element(Y,Z)).
term_element((X <=> Y),Z) :-
(term_element(X,Z);term_element(Y,Z)).
term_element(\+ X,Z) :-
term_element(X,Z).
term_element('$atom'(X),'$atom'(X)) :-
X \== true,
X \== false.
% or(+Boolean,+Boolean,-Boolean)
or(true,_,true).
or(false,X,X).
% not(+Boolean,-Boolean)
not(true,false).
not(false,true).
%========================================================================
%=
%=
%= propagate_interpretation(+GroundTerm, +ID, -GroundTerm)
%========================================================================
propagate_interpretation((X,Y),ID,(X2,Y2)) :-
propagate_interpretation(X,ID,X2),
propagate_interpretation(Y,ID,Y2).
propagate_interpretation((X;Y),ID,(X2;Y2)) :-
propagate_interpretation(X,ID,X2),
propagate_interpretation(Y,ID,Y2).
propagate_interpretation((X <=> Y),ID,(X2 <=> Y2)) :-
propagate_interpretation(X,ID,X2),
propagate_interpretation(Y,ID,Y2).
propagate_interpretation((\+ X), ID,\+ X2) :-
propagate_interpretation(X,ID,X2).
propagate_interpretation('$atom'(X),ID,Value) :-
(
user:known(ID,X,Value)
->
true;
Value='$atom'(X)
).
%========================================================================
%=
%=
%=
%========================================================================
propagate((X,Y),A,AValue,(X2,Y2),Result) :-
propagate(X,A,AValue,X2,Result1),
propagate(Y,A,AValue,Y2,Result2),
or(Result1,Result2,Result).
propagate((X;Y),A,AValue,(X2;Y2),Result) :-
propagate(X,A,AValue,X2,Result1),
propagate(Y,A,AValue,Y2,Result2),
or(Result1,Result2,Result).
propagate((X <=> Y),A,AValue,(X2 <=> Y2),Result) :-
propagate(X,A,AValue,X2,Result1),
propagate(Y,A,AValue,Y2,Result2),
or(Result1,Result2,Result).
propagate((\+ X), A, AValue,\+ X2,Result) :-
propagate(X,A,AValue,X2,Result).
propagate('$atom'(X),'$atom'(A),AValue,X2,Result) :-
(
X==A
->
(
X2=AValue,
Result=true
);
(
X2=X,
Result=false
)
).
propagate(true,_,_,true,false).
propagate(false,_,_,false,false).
%========================================================================
%=
%=
%=
%========================================================================
negate_atom(\+ '$atom'(X), '$atom'(X)).
negate_atom( '$atom'(X),\+ '$atom'(X)).
occurs_check_and((X,_), A) :-
occurs_check_and(X,A),
!.
occurs_check_and((_,Y), A) :-
occurs_check_and(Y,A).
occurs_check_and( '$atom'(X), '$atom'(X)).
occurs_check_or((X;_), A) :-
occurs_check_or(X,A),
!.
occurs_check_or((_;Y), A) :-
occurs_check_and(Y,A).
occurs_check_or( '$atom'(X), '$atom'(X) ).
%========================================================================
%=
%= Tries to simplify Term. If succeeded Status=true and SimplifiedTerm
%= is bound to the simplified term. If not succeeded Status=false and
%= SimplifiedTerm=Term.
%=
%= Only works for ground terms! If non-ground terms are used, the
%= the result is undefined!!!
%=
%= simplify(+Term, -SimplifiedTerm, -Status)
%=
%========================================================================
simplify(Term,Term3,true) :-
simplify_intern(Term,Term2,Result),
Result==true,
!,
simplify(Term2,Term3,_).
simplify(Term,Term,false).
%-----------
simplify_intern( (X<=>Y), NewTerm, Result) :-
simplify_intern_implication(X,Y,NewTerm,Result).
simplify_intern((\+ X), NewTerm,Result) :-
simplify_intern_negation(X,NewTerm,Result).
simplify_intern( (X;Y), NewTerm, Result) :-
simplify_intern_or(X,Y,NewTerm,Result).
simplify_intern( (X,Y), NewTerm, Result) :-
simplify_intern_and(X,Y,NewTerm,Result).
simplify_intern('$atom'(X),'$atom'(X),false).
simplify_intern(true,true,false).
simplify_intern(false,false,false).
%-----------
simplify_intern_or( true,_,true,true) :-
!.
simplify_intern_or( false,X,X,true) :-
!.
simplify_intern_or(_,true,true,true) :-
!.
simplify_intern_or(X,false,X,true) :-
!.
% quite expensive
% simplify_intern_or(X,Y,true,true) :-
% negate_atom(X,X2),
% occurs_check_or(Y,X2),
% !.
simplify_intern_or(X,Y,(X2;Y2),Result) :-
!,
simplify_intern(X,X2,Result1),
simplify_intern(Y,Y2,Result2),
or(Result1,Result2,Result).
%-----------
simplify_intern_and( true,X,X,true) :-
!.
simplify_intern_and( false,_,false,true) :-
!.
simplify_intern_and(X,true,X,true) :-
!.
simplify_intern_and(_,false,false,true) :-
!.
% quite expensive
% simplify_intern_and(X,Y,false,true) :-
% negate_atom(X,X2),
% occurs_check_and(Y,X2),
% !.
simplify_intern_and(X,Y,(X2,Y2),Result) :-
!,
simplify_intern(X,X2,Result1),
simplify_intern(Y,Y2,Result2),
or(Result1,Result2,Result).
%-----------
simplify_intern_implication(true,Y,Y,true) :-
!.
simplify_intern_implication(false,Y,(\+ Y),true) :-
!.
simplify_intern_implication(X,true,X,true) :-
!.
simplify_intern_implication(X,false,(\+ X),true) :-
!.
simplify_intern_implication(X,Y,(X <=> Y2), Result) :-
!,
simplify_intern(Y,Y2,Result).
%-----------
simplify_intern_negation(true,false,true).
simplify_intern_negation(false,true,true).
simplify_intern_negation((\+ X),X,true).
simplify_intern_negation((A,B),Term,true) :-
simplify_intern_or( (\+ A), (\+ B), Term, _).
simplify_intern_negation((A;B),Term,true) :-
simplify_intern_and( (\+ A), (\+ B), Term, _).
simplify_intern_negation('$atom'(X),(\+ '$atom'(X)),false).
%========================================================================
%=
%=
%= list_to_disjunction(+List,-Disjunction)
%========================================================================
list_to_disjunction([A,B|T],(A;T2)) :-
!,
list_to_disjunction([B|T],T2).
list_to_disjunction([A],A).
list_to_disjunction([],false).
%========================================================================
%=
%=
%= list_to_conjunction(+List,(A,T2)-Conjunction) :-
%========================================================================
list_to_conjunction([A,B|T],(A,T2)) :-
!,
list_to_conjunction([B|T],T2).
list_to_conjunction([A],A).
list_to_conjunction([],true).

View File

@ -0,0 +1,67 @@
%%% -*- Mode: Prolog; -*-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ProbLog program describing modelling a simplified version of the ALARM network
% (running example used in the paper [Gutmann et. al, ECML 2011])
% $Id: alarm.pl 6416 2011-06-10 14:38:44Z bernd $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% example for parameter learning with LFI-ProbLog
%
% training examples are included at the end of the file
% query ?- do_learning(20).
% will run 20 iterations of learning with default settings
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- use_module('../problog').
:- use_module('../problog_lfi').
% uncomment to see what is happening
:- set_problog_flag(verbosity_learning,5).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Probabilistic Facts %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the t(_) identifies them as tunable, that is,
% the probabilities are to be learned
t(_) :: burglary.
t(_) :: earthquake.
t(_) :: hears_alarm(_Person).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Background Knowledge %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the background knowledge, read as myclause(Head,Body)
% clauses are assumed to be range-restricted
myclause(person(mary), true).
myclause(person(john), true).
myclause(alarm, burglary).
myclause(alarm, earthquake).
myclause(calls(Person), (person(Person),alarm,hears_alarm(Person))).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Training examples %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
example(1).
example(2).
%%%% Example 1
known(1,alarm,true).
%%%% Example 2
known(2,earthquake,false).
known(2,calls(mary),true).

View File

@ -2,8 +2,8 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Date: 2010-12-15 15:05:44 +0100 (Wed, 15 Dec 2010) $
% $Revision: 5142 $
% $Date: 2011-04-21 14:18:59 +0200 (Thu, 21 Apr 2011) $
% $Revision: 6364 $
%
% This file is part of ProbLog
% http://dtai.cs.kuleuven.be/problog
@ -529,7 +529,7 @@ init_learning :-
),
succeeds_n_times(user:example(_,_,_,_),TestExampleCount),
succeeds_n_times(user:test_example(_,_,_,_),TestExampleCount),
format_learning(3,'~q test examples~n',[TestExampleCount]),
succeeds_n_times(user:example(_,_,_,_),TrainingExampleCount),
@ -555,8 +555,8 @@ init_learning :-
->
set_problog_flag(alpha,1.0);
(
succeed_n_times((user:example(_,_,P,=),P=:=1.0),Pos_Count),
succeed_n_times((user:example(_,_,P,=),P=:=0.0),Neg_Count),
succeeds_n_times((user:example(_,_,P,=),P=:=1.0),Pos_Count),
succeeds_n_times((user:example(_,_,P,=),P=:=0.0),Neg_Count),
Alpha is Pos_Count/Neg_Count,
set_problog_flag(alpha,Alpha)
)
@ -671,11 +671,17 @@ update_values :-
forall(get_fact_probability(ID,Prob),
(
inv_sigmoid(Prob,Value),
(
non_ground_fact(ID)
->
format(Handle,'@x~q_*~n~10f~n',[ID,Value]);
(problog:dynamic_probability_fact(ID) ->
get_fact(ID, Term),
forall(grounding_is_known(Term, GID), (
problog:dynamic_probability_fact_extract(Term, Prob2),
inv_sigmoid(Prob2,Value),
format(Handle, '@x~q_~q~n~10f~n', [ID,GID, Value])))
; non_ground_fact(ID) ->
inv_sigmoid(Prob,Value),
format(Handle,'@x~q_*~n~10f~n',[ID,Value])
;
inv_sigmoid(Prob,Value),
format(Handle,'@x~q~n~10f~n',[ID,Value])
)
)),

File diff suppressed because it is too large Load Diff

View File

@ -7,8 +7,8 @@
* *
* Author: Theofrastos Mantadelis *
* File: simplecudd.c *
* $Date:: 2010-12-17 12:21:58 +0100 (Fri, 17 Dec 2010) $ *
* $Revision:: 5159 $ *
* $Date:: 2011-04-11 17:23:11 +0200 (Mon, 11 Apr 2011) $ *
* $Revision:: 5920 $ *
* *
********************************************************************************
* *
@ -1240,7 +1240,7 @@ DdNode* LineParser(DdManager *manager, namedvars varmap, DdNode **inter, int max
iconst = 1;
} else if (strcmp(term + inegvar, "FALSE") == 0) {
iconst = 1;
inegvar = 1;
inegvar = !inegvar;
} else {
iconst = 0;
ivar = AddNamedVar(varmap, term + inegvar);

View File

@ -0,0 +1,345 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright Katholieke Universiteit Leuven 2008 *
* *
* Author: Theofrastos Mantadelis *
* File: Example.c *
* *
********************************************************************************
* *
* Artistic License 2.0 *
* *
* Copyright (c) 2000-2006, The Perl Foundation. *
* *
* Everyone is permitted to copy and distribute verbatim copies of this license *
* document, but changing it is not allowed. *
* *
* Preamble *
* *
* This license establishes the terms under which a given free software Package *
* may be copied, modified, distributed, and/or redistributed. The intent is *
* that the Copyright Holder maintains some artistic control over the *
* development of that Package while still keeping the Package available as *
* open source and free software. *
* *
* You are always permitted to make arrangements wholly outside of this license *
* directly with the Copyright Holder of a given Package. If the terms of this *
* license do not permit the full use that you propose to make of the Package, *
* you should contact the Copyright Holder and seek a different licensing *
* arrangement. *
* Definitions *
* *
* "Copyright Holder" means the individual(s) or organization(s) named in the *
* copyright notice for the entire Package. *
* *
* "Contributor" means any party that has contributed code or other material to *
* the Package, in accordance with the Copyright Holder's procedures. *
* *
* "You" and "your" means any person who would like to copy, distribute, or *
* modify the Package. *
* *
* "Package" means the collection of files distributed by the Copyright Holder, *
* and derivatives of that collection and/or of those files. A given Package *
* may consist of either the Standard Version, or a Modified Version. *
* *
* "Distribute" means providing a copy of the Package or making it accessible *
* to anyone else, or in the case of a company or organization, to others *
* outside of your company or organization. *
* *
* "Distributor Fee" means any fee that you charge for Distributing this *
* Package or providing support for this Package to another party. It does not *
* mean licensing fees. *
* *
* "Standard Version" refers to the Package if it has not been modified, or has *
* been modified only in ways explicitly requested by the Copyright Holder. *
* *
* "Modified Version" means the Package, if it has been changed, and such *
* changes were not explicitly requested by the Copyright Holder. *
* *
* "Original License" means this Artistic License as Distributed with the *
* Standard Version of the Package, in its current version or as it may be *
* modified by The Perl Foundation in the future. *
* *
* "Source" form means the source code, documentation source, and configuration *
* files for the Package. *
* *
* "Compiled" form means the compiled bytecode, object code, binary, or any *
* other form resulting from mechanical transformation or translation of the *
* Source form. *
* Permission for Use and Modification Without Distribution *
* *
* (1) You are permitted to use the Standard Version and create and use *
* Modified Versions for any purpose without restriction, provided that you do *
* not Distribute the Modified Version. *
* Permissions for Redistribution of the Standard Version *
* *
* (2) You may Distribute verbatim copies of the Source form of the Standard *
* Version of this Package in any medium without restriction, either gratis or *
* for a Distributor Fee, provided that you duplicate all of the original *
* copyright notices and associated disclaimers. At your discretion, such *
* verbatim copies may or may not include a Compiled form of the Package. *
* *
* (3) You may apply any bug fixes, portability changes, and other *
* modifications made available from the Copyright Holder. The resulting *
* Package will still be considered the Standard Version, and as such will be *
* subject to the Original License. *
* Distribution of Modified Versions of the Package as Source *
* *
* (4) You may Distribute your Modified Version as Source (either gratis or for *
* a Distributor Fee, and with or without a Compiled form of the Modified *
* Version) provided that you clearly document how it differs from the Standard *
* Version, including, but not limited to, documenting any non-standard *
* features, executables, or modules, and provided that you do at least ONE of *
* the following: *
* *
* (a) make the Modified Version available to the Copyright Holder of the *
* Standard Version, under the Original License, so that the Copyright Holder *
* may include your modifications in the Standard Version. *
* (b) ensure that installation of your Modified Version does not prevent the *
* user installing or running the Standard Version. In addition, the Modified *
* Version must bear a name that is different from the name of the Standard *
* Version. *
* (c) allow anyone who receives a copy of the Modified Version to make the *
* Source form of the Modified Version available to others under *
* (i) the Original License or *
* (ii) a license that permits the licensee to freely copy, modify and *
* redistribute the Modified Version using the same licensing terms that apply *
* to the copy that the licensee received, and requires that the Source form of *
* the Modified Version, and of any works derived from it, be made freely *
* available in that license fees are prohibited but Distributor Fees are *
* allowed. *
* Distribution of Compiled Forms of the Standard Version or Modified Versions *
* without the Source *
* *
* (5) You may Distribute Compiled forms of the Standard Version without the *
* Source, provided that you include complete instructions on how to get the *
* Source of the Standard Version. Such instructions must be valid at the time *
* of your distribution. If these instructions, at any time while you are *
* carrying out such distribution, become invalid, you must provide new *
* instructions on demand or cease further distribution. If you provide valid *
* instructions or cease distribution within thirty days after you become aware *
* that the instructions are invalid, then you do not forfeit any of your *
* rights under this license. *
* *
* (6) You may Distribute a Modified Version in Compiled form without the *
* Source, provided that you comply with Section 4 with respect to the Source *
* of the Modified Version. *
* Aggregating or Linking the Package *
* *
* (7) You may aggregate the Package (either the Standard Version or Modified *
* Version) with other packages and Distribute the resulting aggregation *
* provided that you do not charge a licensing fee for the Package. Distributor *
* Fees are permitted, and licensing fees for other components in the *
* aggregation are permitted. The terms of this license apply to the use and *
* Distribution of the Standard or Modified Versions as included in the *
* aggregation. *
* *
* (8) You are permitted to link Modified and Standard Versions with other *
* works, to embed the Package in a larger work of your own, or to build *
* stand-alone binary or bytecode versions of applications that include the *
* Package, and Distribute the result without restriction, provided the result *
* does not expose a direct interface to the Package. *
* Items That are Not Considered Part of a Modified Version *
* *
* (9) Works (including, but not limited to, modules and scripts) that merely *
* extend or make use of the Package, do not, by themselves, cause the Package *
* to be a Modified Version. In addition, such works are not considered parts *
* of the Package itself, and are not subject to the terms of this license. *
* General Provisions *
* *
* (10) Any use, modification, and distribution of the Standard or Modified *
* Versions is governed by this Artistic License. By using, modifying or *
* distributing the Package, you accept this license. Do not use, modify, or *
* distribute the Package, if you do not accept this license. *
* *
* (11) If your Modified Version has been derived from a Modified Version made *
* by someone other than you, you are nevertheless required to ensure that your *
* Modified Version complies with the requirements of this license. *
* *
* (12) This license does not grant you the right to use any trademark, service *
* mark, tradename, or logo of the Copyright Holder. *
* *
* (13) This license includes the non-exclusive, worldwide, free-of-charge *
* patent license to make, have made, use, offer to sell, sell, import and *
* otherwise transfer the Package with respect to any patent claims licensable *
* by the Copyright Holder that are necessarily infringed by the Package. If *
* you institute patent litigation (including a cross-claim or counterclaim) *
* against any party alleging that the Package constitutes direct or *
* contributory patent infringement, then this Artistic License to you shall *
* terminate on the date that such litigation is filed. *
* *
* (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER *
* AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR *
* NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. *
* UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN *
* ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
* The End *
* *
\******************************************************************************/
#include "simplecudd.h"
typedef struct _extmanager {
DdManager *manager;
DdNode *t, *f;
hisqueue *his;
namedvars varmap;
} extmanager;
void DFS(extmanager MyManager, DdNode *Current);
int compexpand(extmanager MyManager, DdNode *Current, extmanager MyManager2, DdNode *Current2);
int bufstrcat(char *targetstr, int targetmem, const char *srcstr);
void getalltruepaths(extmanager MyManager, DdNode *Current, const char *startpath, const char *prevvar);
int main(int argc, char **arg) {
extmanager MyManager;
DdNode *bdd, **forest;
bddfileheader fileheader;
int code;
char yn;
code = -1;
if (argc != 2) {
fprintf(stderr, "\nUsage: %s [filename]\nGenerates and traverses a BDD from file\n", arg[0]);
fprintf(stderr, "\nUsage: %s -online\nGenerates and traverses a BDD online mode\n", arg[0]);
return code;
}
RAPIDLOADON;
if (strcmp("-online", arg[1]) == 0) {
MyManager.manager = simpleBDDinit(0);
MyManager.t = HIGH(MyManager.manager);
MyManager.f = LOW(MyManager.manager);
MyManager.varmap = InitNamedVars(1, 0);
bdd = OnlineGenerateBDD(MyManager.manager, &MyManager.varmap);
} else {
fileheader = ReadFileHeader(arg[1]);
switch(fileheader.filetype) {
case BDDFILE_SCRIPT:
MyManager.manager = simpleBDDinit(fileheader.varcnt);
MyManager.t = HIGH(MyManager.manager);
MyManager.f = LOW(MyManager.manager);
MyManager.varmap = InitNamedVars(fileheader.varcnt, fileheader.varstart);
if (fileheader.version > 1) {
forest = FileGenerateBDDForest(MyManager.manager, MyManager.varmap, fileheader);
bdd = forest[0];
} else {
forest = NULL;
bdd = FileGenerateBDD(MyManager.manager, MyManager.varmap, fileheader);
}
break;
case BDDFILE_NODEDUMP:
MyManager.manager = simpleBDDinit(fileheader.varcnt);
MyManager.t = HIGH(MyManager.manager);
MyManager.f = LOW(MyManager.manager);
MyManager.varmap = InitNamedVars(fileheader.varcnt, fileheader.varstart);
bdd = LoadNodeDump(MyManager.manager, MyManager.varmap, fileheader.inputfile);
break;
default:
fprintf(stderr, "Error: not a valid file format to load.\n");
return code;
break;
}
}
int nextbdd = 0;
while (bdd != NULL) {
printf("Do you want to load parameter values from testdata.txt [y]? "); yn = getchar(); getchar();
if (yn == 'y') {
printf("yo\n");
LoadVariableData(MyManager.varmap, "testdata.txt");
printf("yo\n");
char **a;
a = GetVariableOrder("testdata.txt", MyManager.varmap.varcnt);
int aa;
for (aa = 0; aa < MyManager.varmap.varcnt; aa++)
printf("%s\n", a[aa]);
ImposeOrder(MyManager.manager, MyManager.varmap, a);
}
code = 0;
MyManager.his = InitHistory(GetVarCount(MyManager.manager));
if (strcmp("-online", arg[1]) != 0) {
DFS(MyManager, bdd);
printf("Do you need an export [y]? "); yn = getchar(); getchar();
if (yn == 'y') simpleNamedBDDtoDot(MyManager.manager, MyManager.varmap, bdd, "SimpleCUDDExport.dot");
printf("Do you want a save [y]? "); yn = getchar(); getchar();
if (yn == 'y') SaveNodeDump(MyManager.manager, MyManager.varmap, bdd, "SimpleCUDDSave.sav");
printf("Do you want to see all true paths [y]? "); yn = getchar(); getchar();
if (yn == 'y') {
ReInitHistory(MyManager.his, GetVarCount(MyManager.manager));
getalltruepaths(MyManager, bdd, "", "");
}
} else {
onlinetraverse(MyManager.manager, MyManager.varmap, MyManager.his, bdd);
}
nextbdd++;
if (forest != NULL) bdd = forest[nextbdd]; else bdd = NULL;
}
if (MyManager.manager != NULL) KillBDD(MyManager.manager);
return code;
}
void DFS(extmanager MyManager, DdNode *Current) {
DdNode *h, *l;
hisnode *Found;
char *curnode;
curnode = GetNodeVarNameDisp(MyManager.manager, MyManager.varmap, Current);
if (GetIndex(Current) < MyManager.varmap.varcnt) {
printf("%s(%f,%i,%s)\n", curnode, MyManager.varmap.dvalue[GetIndex(Current)], MyManager.varmap.ivalue[GetIndex(Current)], (char *) MyManager.varmap.dynvalue[GetIndex(Current)]);
} else {
printf("%s\n", curnode);
}
if ((Current != MyManager.t) && (Current != MyManager.f) &&
((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) == NULL)) {
l = LowNodeOf(MyManager.manager, Current);
h = HighNodeOf(MyManager.manager, Current);
printf("l(%s)->", curnode);
DFS(MyManager, l);
printf("h(%s)->", curnode);
DFS(MyManager, h);
AddNode(MyManager.his, MyManager.varmap.varstart, Current, 0.0, 0, NULL);
}
}
void getalltruepaths(extmanager MyManager, DdNode *Current, const char *startpath, const char *prevvar) {
DdNode *h, *l;
char *curnode, *curpath;
int pathmaxsize = 1024;
curpath = (char *) malloc(sizeof(char) * pathmaxsize);
curpath[0] = '\0';
pathmaxsize = bufstrcat(curpath, pathmaxsize, startpath);
pathmaxsize = bufstrcat(curpath, pathmaxsize, prevvar);
pathmaxsize = bufstrcat(curpath, pathmaxsize, "*");
curnode = GetNodeVarNameDisp(MyManager.manager, MyManager.varmap, Current);
if (Current == MyManager.t) {
printf("%s\n", curpath);
} else if (Current != MyManager.f) {
h = HighNodeOf(MyManager.manager, Current);
if (h != MyManager.f) {
getalltruepaths(MyManager, h, curpath, curnode);
}
l = LowNodeOf(MyManager.manager, Current);
if (l != MyManager.f) {
pathmaxsize = bufstrcat(curpath, pathmaxsize, "~");
getalltruepaths(MyManager, l, curpath, curnode);
}
}
free(curpath);
}
int bufstrcat(char *targetstr, int targetmem, const char *srcstr) {
int strinc = strlen(srcstr), strsize = strlen(targetstr);
while ((strsize + strinc) > (targetmem - 1)) {
targetmem *= 2;
targetstr = (char *) realloc(targetstr, sizeof(char) * targetmem);
}
strcat(targetstr, srcstr);
return targetmem;
}

View File

@ -0,0 +1,62 @@
#
# default base directory for YAP installation
# (EROOT for architecture-dependent files)
#
prefix = @prefix@
exec_prefix = @exec_prefix@
ROOTDIR = $(prefix)
EROOTDIR = @exec_prefix@
abs_top_builddir = @abs_top_builddir@
#
# where the binary should be
#
BINDIR = $(EROOTDIR)/bin
#
# where YAP should look for libraries
#
LIBDIR=@libdir@
YAPLIBDIR=@libdir@/Yap
#
# where YAP should look for architecture-independent Prolog libraries
#
SHAREDIR=$(ROOTDIR)/share
#
#
CC=@CC@
#
#
# You shouldn't need to change what follows.
#
INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@
SHELL=/bin/sh
RANLIB=@RANLIB@
srcdir=@srcdir@
SO=@SO@
#4.1VPATH=@srcdir@:@srcdir@/OPTYap
CWD=$(PWD)
#
DYNAMIC =
CFLAGS = @CFLAGS@
INCLUDE = @CUDD_CPPFLAGS@
LINKFLAGS = -lm
LINKLIBS = @CUDD_LDFLAGS@
default: problogbdd_lfi
problogbdd_lfi: problogbdd_lfi.o simplecudd.o general.o problogmath.o pqueue.o allocate.o iqueue.o adterror.o allocate.o
@echo Making problogbdd_lfi...
@echo Copyright Katholieke Universiteit Leuven 2008
@echo Authors: T. Mantadelis, A. Kimmig, B. Gutmann, I. Thon, G. Van den Broeck
$(CC) problogbdd_lfi.o simplecudd.o general.o problogmath.o pqueue.o iqueue.o adterror.o allocate.o $(LINKLIBS) $(LINKFLAGS) -o problogbdd_lfi
%.o : $(srcdir)/%.c
$(CC) $(CFLAGS) $(INCLUDE) $(DYNAMIC) -c $<
clean:
rm -f *.o problogbdd_lfi
install: default
$(INSTALL_PROGRAM) problogbdd_lfi $(DESTDIR)$(SHAREDIR)/Yap

View File

@ -0,0 +1,47 @@
/******************************************************************
**
** ADTERROR.C:
**
** ADT Error Handler
**
** This file is part of Apt Abstrct Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
******************************************************************/
#include "adterror.h"
//#include "gprintf.h"
//PUBLIC
//#ifdef __ANSI_C__
void ADTError(char *name, ADTErrorCodes error, char *proc)
//#else
//void ADTError(name,error,proc)
//char *name;
//ADTErrorCodes error;
//char *proc;
//#endif
{
fprintf(stderr,"ADT Error: ");
fprintf(stderr," Module: %s\n",name);
fprintf(stderr," Procedure: %s\n",proc);
fprintf(stderr," Error Code: %s\n",error);
exit(1);
}
//PUBLIC
//#ifdef __ANSI_C__
void ADTWarning(char *name, ADTWarningCodes warning, char *proc)
//#else
//void ADTWarning(name,warning,proc)
//char *name;
//ADTWarningCodes warning;
//char *proc;
//#endif
{
fprintf(stderr,"ADT Warning: ");
fprintf(stderr," Module: %s\n",name);
fprintf(stderr," Procedure: %s\n",proc);
fprintf(stderr," Warning Code: %s\n",warning);
}

View File

@ -0,0 +1,75 @@
/******************************************************************
**
** ADTERROR.H:
**
** ADT Error Handler
**
** This file is part of Apt Abstrct Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
******************************************************************/
#ifndef ADTERROR_H
#define ADTERROR_H
//#include "cheaders.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ADT Names */
#define ADT_AStack "Array Stack"
#define ADT_AStackIter "Array Stack Iterator"
#define ADT_Buffer "Buffer"
#define ADT_BufferIO "Buffered I/O"
#define ADT_Deque "Deque"
#define ADT_DequeIter "Deque Iterator"
#define ADT_HashTable "Hash Table"
#define ADT_HashTableIter "Hash Table Iterator"
#define ADT_Queue "Queue"
#define ADT_QueueIter "Queue Iterator"
#define ADT_Stack "Stack"
#define ADT_StackIter "Stack Iterator"
#define ADT_Table "AVL Table"
#define ADT_TableIter "AVL Table Iterator"
#define ADT_Tree "AVL Tree"
#define ADT_TreeIter "AVL Tree Iterator"
/* ADT Error Codes */
typedef enum _ADTErrorCodes {
E_Allocation,
E_NullQueue,
E_NullQueueIter,
E_Seek,
E_SeekOverflow,
E_SeekUnderflow,
/* Added HashTable errors 03/22/2005 pma */
E_NullHashTable,
E_NullHashTableIter,
/* Added AVLTable errors 04/04/2005 pma */
E_NullAVLTable,
E_NullAVLTableIter,
E_Undefined
} ADTErrorCodes;
typedef enum _ADTWarningCodes {
W_Undefined
} ADTWarningCodes;
/* ADT Error Handler */
#ifdef __ANSI_C__
void ADTError(char *name, ADTErrorCodes error, char *proc);
void ADTWarning(char *name, ADTWarningCodes warning, char *proc);
#else
void ADTError();
void ADTWarning();
#endif
#endif

View File

@ -0,0 +1,59 @@
/******************************************************************
**
** ALLOCATE.C:
**
** Allocation Routines
**
** This file is part of Apt Computing Tools (ACT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
/* ---------- C Headers */
//#include "cheaders.h"
/* ---------- Headers */
#include "apt.h"
#include "allocate.h"
/* ---------- Private Globals */
PRIVATE int bytesAllocated = 0;
/* ---------- Functions */
/*
**
** Allocate
**
*/
PUBLIC
#ifdef __ANSI_C__
void *Allocate(int bytes)
#else
void *Allocate(bytes)
int bytes;
#endif
{
bytesAllocated += bytes;
return (void *)calloc(1,bytes);
}
/*
**
** Free
**
*/
PUBLIC
#ifdef __ANSI_C__
void Free(void *memory)
#else
void Free(memory)
void *memory;
#endif
{
free(memory);
}

View File

@ -0,0 +1,30 @@
/******************************************************************
**
** ALLOCATE.H:
**
** Allocation Routines
**
** This file is part of Apt Computing Tools (ACT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
#ifndef ALLOCATE_H
#define ALLOCATE_H
/* ----------- Headers */
#include "apt.h"
/* ----------- Exported Function Prototypes */
#ifdef __ANSI_C__
void *Allocate(int);
void Free(void*);
#else
void *Allocate();
void Free();
#endif /* __ANSI_C__ */
#endif /* ALLOCATE_H */

View File

@ -0,0 +1,67 @@
/******************************************************************
**
** APT.H:
**
** Definitions and Types for all APT modules
**
** This file is part of Apt Computing Tools (ACT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
#ifndef APT_H
#define APT_H
/* ---------- Defines */
#ifndef ERROR
#define ERROR -1
#endif
#ifndef EXTERN
#define EXTERN extern
#endif
#ifndef FAILURE
#define FAILURE -1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef INFINITY
#define INFINITY 32768L
#endif
#ifndef PRIVATE
#define PRIVATE static
#endif
#ifndef PUBLIC
#define PUBLIC
#endif
#ifndef SUCCESS
#define SUCCESS 1
#endif
#ifndef TRUE
#define TRUE 1
#endif
/* ---------- Types */
#define __ANSI_C__
typedef void (*ApplyFunction)(void*);
typedef void (*ApplyFunction1)(void*,void*);
typedef void (*ApplyFunction2)(void*,void*,void*);
typedef void (*ApplyFunction3)(void*,void*,void*,void*);
typedef int (*ComparisonFunction)(void*, void*);
typedef void (*DisposeFunction)(void*);
typedef void (*ApplyFunctionGeneric)(void* target, void* args[]);
#endif /* APT_H */

View File

@ -0,0 +1,50 @@
/*
* cheaders.h : A unified headers file for APT. It does slow down compile
* time somewhat, but this allows us to ensure consistent usage
* of header files and replace missing ones easily.
*/
#ifndef APT_CHEADERS_H
#define APT_CHEADERS_H
#include "apt_config.h"
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#else
#error Your C compiler is very old (ctype.h missing). Time to upgrade. Sorry
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#else
#error Your C compiler is very old (string.h missing). Time to upgrade. Sorry
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#else
#error Your C compiler is very old (stdio.h missing). Time to upgrade. Sorry
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#else
#error Your C compiler is not ANSI C (stdlib.h missing). Time to upgrade. Sorry
#endif
#if HAVE_STDARG_H
# include <stdarg.h>
# define VA_START(a, f) va_start(a, f)
#else
# if HAVE_VARARGS_H
# include <varargs.h>
# define VA_START(a, f) va_start(a)
# endif
#endif
#ifndef VA_START
#error Your C compiler has no support for variable argument functions. Time to upgrade. Sorry.
#endif
#endif

View File

@ -0,0 +1,277 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright Katholieke Universiteit Leuven 2008 *
* *
* Author: Theofrastos Mantadelis *
* File: general.c *
* *
********************************************************************************
* *
* Artistic License 2.0 *
* *
* Copyright (c) 2000-2006, The Perl Foundation. *
* *
* Everyone is permitted to copy and distribute verbatim copies of this license *
* document, but changing it is not allowed. *
* *
* Preamble *
* *
* This license establishes the terms under which a given free software Package *
* may be copied, modified, distributed, and/or redistributed. The intent is *
* that the Copyright Holder maintains some artistic control over the *
* development of that Package while still keeping the Package available as *
* open source and free software. *
* *
* You are always permitted to make arrangements wholly outside of this license *
* directly with the Copyright Holder of a given Package. If the terms of this *
* license do not permit the full use that you propose to make of the Package, *
* you should contact the Copyright Holder and seek a different licensing *
* arrangement. *
* Definitions *
* *
* "Copyright Holder" means the individual(s) or organization(s) named in the *
* copyright notice for the entire Package. *
* *
* "Contributor" means any party that has contributed code or other material to *
* the Package, in accordance with the Copyright Holder's procedures. *
* *
* "You" and "your" means any person who would like to copy, distribute, or *
* modify the Package. *
* *
* "Package" means the collection of files distributed by the Copyright Holder, *
* and derivatives of that collection and/or of those files. A given Package *
* may consist of either the Standard Version, or a Modified Version. *
* *
* "Distribute" means providing a copy of the Package or making it accessible *
* to anyone else, or in the case of a company or organization, to others *
* outside of your company or organization. *
* *
* "Distributor Fee" means any fee that you charge for Distributing this *
* Package or providing support for this Package to another party. It does not *
* mean licensing fees. *
* *
* "Standard Version" refers to the Package if it has not been modified, or has *
* been modified only in ways explicitly requested by the Copyright Holder. *
* *
* "Modified Version" means the Package, if it has been changed, and such *
* changes were not explicitly requested by the Copyright Holder. *
* *
* "Original License" means this Artistic License as Distributed with the *
* Standard Version of the Package, in its current version or as it may be *
* modified by The Perl Foundation in the future. *
* *
* "Source" form means the source code, documentation source, and configuration *
* files for the Package. *
* *
* "Compiled" form means the compiled bytecode, object code, binary, or any *
* other form resulting from mechanical transformation or translation of the *
* Source form. *
* Permission for Use and Modification Without Distribution *
* *
* (1) You are permitted to use the Standard Version and create and use *
* Modified Versions for any purpose without restriction, provided that you do *
* not Distribute the Modified Version. *
* Permissions for Redistribution of the Standard Version *
* *
* (2) You may Distribute verbatim copies of the Source form of the Standard *
* Version of this Package in any medium without restriction, either gratis or *
* for a Distributor Fee, provided that you duplicate all of the original *
* copyright notices and associated disclaimers. At your discretion, such *
* verbatim copies may or may not include a Compiled form of the Package. *
* *
* (3) You may apply any bug fixes, portability changes, and other *
* modifications made available from the Copyright Holder. The resulting *
* Package will still be considered the Standard Version, and as such will be *
* subject to the Original License. *
* Distribution of Modified Versions of the Package as Source *
* *
* (4) You may Distribute your Modified Version as Source (either gratis or for *
* a Distributor Fee, and with or without a Compiled form of the Modified *
* Version) provided that you clearly document how it differs from the Standard *
* Version, including, but not limited to, documenting any non-standard *
* features, executables, or modules, and provided that you do at least ONE of *
* the following: *
* *
* (a) make the Modified Version available to the Copyright Holder of the *
* Standard Version, under the Original License, so that the Copyright Holder *
* may include your modifications in the Standard Version. *
* (b) ensure that installation of your Modified Version does not prevent the *
* user installing or running the Standard Version. In addition, the Modified *
* Version must bear a name that is different from the name of the Standard *
* Version. *
* (c) allow anyone who receives a copy of the Modified Version to make the *
* Source form of the Modified Version available to others under *
* (i) the Original License or *
* (ii) a license that permits the licensee to freely copy, modify and *
* redistribute the Modified Version using the same licensing terms that apply *
* to the copy that the licensee received, and requires that the Source form of *
* the Modified Version, and of any works derived from it, be made freely *
* available in that license fees are prohibited but Distributor Fees are *
* allowed. *
* Distribution of Compiled Forms of the Standard Version or Modified Versions *
* without the Source *
* *
* (5) You may Distribute Compiled forms of the Standard Version without the *
* Source, provided that you include complete instructions on how to get the *
* Source of the Standard Version. Such instructions must be valid at the time *
* of your distribution. If these instructions, at any time while you are *
* carrying out such distribution, become invalid, you must provide new *
* instructions on demand or cease further distribution. If you provide valid *
* instructions or cease distribution within thirty days after you become aware *
* that the instructions are invalid, then you do not forfeit any of your *
* rights under this license. *
* *
* (6) You may Distribute a Modified Version in Compiled form without the *
* Source, provided that you comply with Section 4 with respect to the Source *
* of the Modified Version. *
* Aggregating or Linking the Package *
* *
* (7) You may aggregate the Package (either the Standard Version or Modified *
* Version) with other packages and Distribute the resulting aggregation *
* provided that you do not charge a licensing fee for the Package. Distributor *
* Fees are permitted, and licensing fees for other components in the *
* aggregation are permitted. The terms of this license apply to the use and *
* Distribution of the Standard or Modified Versions as included in the *
* aggregation. *
* *
* (8) You are permitted to link Modified and Standard Versions with other *
* works, to embed the Package in a larger work of your own, or to build *
* stand-alone binary or bytecode versions of applications that include the *
* Package, and Distribute the result without restriction, provided the result *
* does not expose a direct interface to the Package. *
* Items That are Not Considered Part of a Modified Version *
* *
* (9) Works (including, but not limited to, modules and scripts) that merely *
* extend or make use of the Package, do not, by themselves, cause the Package *
* to be a Modified Version. In addition, such works are not considered parts *
* of the Package itself, and are not subject to the terms of this license. *
* General Provisions *
* *
* (10) Any use, modification, and distribution of the Standard or Modified *
* Versions is governed by this Artistic License. By using, modifying or *
* distributing the Package, you accept this license. Do not use, modify, or *
* distribute the Package, if you do not accept this license. *
* *
* (11) If your Modified Version has been derived from a Modified Version made *
* by someone other than you, you are nevertheless required to ensure that your *
* Modified Version complies with the requirements of this license. *
* *
* (12) This license does not grant you the right to use any trademark, service *
* mark, tradename, or logo of the Copyright Holder. *
* *
* (13) This license includes the non-exclusive, worldwide, free-of-charge *
* patent license to make, have made, use, offer to sell, sell, import and *
* otherwise transfer the Package with respect to any patent claims licensable *
* by the Copyright Holder that are necessarily infringed by the Package. If *
* you institute patent litigation (including a cross-claim or counterclaim) *
* against any party alleging that the Package constitutes direct or *
* contributory patent infringement, then this Artistic License to you shall *
* terminate on the date that such litigation is filed. *
* *
* (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER *
* AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR *
* NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. *
* UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN *
* ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
* The End *
* *
\******************************************************************************/
#include "general.h"
/* Number Handling */
int IsRealNumber(char *c) {
int i, l;
l = strlen(c);
if (l <= 0) return 0;
if (l == 1) return IsNumberDigit(c[0]);
for(i = 1; i < strlen(c); i++) {
if (c[i] == '.') return IsPosNumber(&c[i + 1]);
if (!IsNumberDigit(c[i])) return 0;
}
return (IsNumberDigit(c[0]) || IsSignDigit(c[0]));
}
int IsPosNumber(const char *c) {
int i, l;
l = strlen(c);
if (l <= 0) return 0;
for(i = 0; i < strlen(c); i++) {
if (!IsNumberDigit(c[i])) return 0;
}
return 1;
}
int IsNumber(const char *c) {
int i, l;
l = strlen(c);
if (l <= 0) return 0;
if (l == 1) return IsNumberDigit(c[0]);
for(i = 1; i < strlen(c); i++) {
if (!IsNumberDigit(c[i])) return 0;
}
return (IsNumberDigit(c[0]) || IsSignDigit(c[0]));
}
/* File Handling */
char * freadstr(FILE *fd, const char *separators) {
char *str;
int buf, icur = 0, max = 10;
str = (char *) malloc(sizeof(char) * max);
str[0] = '\0';
do {
if ((buf = fgetc(fd)) != EOF) {
if (icur == (max - 1)) {
max = max * 2;
str = (char *) realloc(str, sizeof(char) * max);
}
if (!CharIn((char) buf, separators)) {
str[icur] = (char) buf;
icur++;
str[icur] = '\0';
}
}
} while(!CharIn(buf, separators) && !feof(fd));
return str;
}
int CharIn(const char c, const char *in) {
int i;
for (i = 0; i < strlen(in); i++)
if (c == in[i]) return 1;
return 0;
}
/* string handling */
int patternmatch(char *pattern, char *thestr) {
int i, j = -1, pl = strlen(pattern), sl = strlen(thestr);
for(i = 0; i < pl; i++) {
if (pattern[i] == '*') {
do {
i++;
if (i == pl) return 1;
} while(pattern[i] == '*');
do {
j++;
if (j >= sl) return 0;
if ((thestr[j] == pattern[i]) && patternmatch(pattern + i, thestr + j)) return 1;
} while(1);
} else {
j++;
if (j >= sl) return 0;
if (pattern[i] != thestr[j]) return 0;
}
}
return (pl == sl);
}

View File

@ -0,0 +1,202 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright Katholieke Universiteit Leuven 2008 *
* *
* Author: Theofrastos Mantadelis *
* File: general.h *
* *
********************************************************************************
* *
* Artistic License 2.0 *
* *
* Copyright (c) 2000-2006, The Perl Foundation. *
* *
* Everyone is permitted to copy and distribute verbatim copies of this license *
* document, but changing it is not allowed. *
* *
* Preamble *
* *
* This license establishes the terms under which a given free software Package *
* may be copied, modified, distributed, and/or redistributed. The intent is *
* that the Copyright Holder maintains some artistic control over the *
* development of that Package while still keeping the Package available as *
* open source and free software. *
* *
* You are always permitted to make arrangements wholly outside of this license *
* directly with the Copyright Holder of a given Package. If the terms of this *
* license do not permit the full use that you propose to make of the Package, *
* you should contact the Copyright Holder and seek a different licensing *
* arrangement. *
* Definitions *
* *
* "Copyright Holder" means the individual(s) or organization(s) named in the *
* copyright notice for the entire Package. *
* *
* "Contributor" means any party that has contributed code or other material to *
* the Package, in accordance with the Copyright Holder's procedures. *
* *
* "You" and "your" means any person who would like to copy, distribute, or *
* modify the Package. *
* *
* "Package" means the collection of files distributed by the Copyright Holder, *
* and derivatives of that collection and/or of those files. A given Package *
* may consist of either the Standard Version, or a Modified Version. *
* *
* "Distribute" means providing a copy of the Package or making it accessible *
* to anyone else, or in the case of a company or organization, to others *
* outside of your company or organization. *
* *
* "Distributor Fee" means any fee that you charge for Distributing this *
* Package or providing support for this Package to another party. It does not *
* mean licensing fees. *
* *
* "Standard Version" refers to the Package if it has not been modified, or has *
* been modified only in ways explicitly requested by the Copyright Holder. *
* *
* "Modified Version" means the Package, if it has been changed, and such *
* changes were not explicitly requested by the Copyright Holder. *
* *
* "Original License" means this Artistic License as Distributed with the *
* Standard Version of the Package, in its current version or as it may be *
* modified by The Perl Foundation in the future. *
* *
* "Source" form means the source code, documentation source, and configuration *
* files for the Package. *
* *
* "Compiled" form means the compiled bytecode, object code, binary, or any *
* other form resulting from mechanical transformation or translation of the *
* Source form. *
* Permission for Use and Modification Without Distribution *
* *
* (1) You are permitted to use the Standard Version and create and use *
* Modified Versions for any purpose without restriction, provided that you do *
* not Distribute the Modified Version. *
* Permissions for Redistribution of the Standard Version *
* *
* (2) You may Distribute verbatim copies of the Source form of the Standard *
* Version of this Package in any medium without restriction, either gratis or *
* for a Distributor Fee, provided that you duplicate all of the original *
* copyright notices and associated disclaimers. At your discretion, such *
* verbatim copies may or may not include a Compiled form of the Package. *
* *
* (3) You may apply any bug fixes, portability changes, and other *
* modifications made available from the Copyright Holder. The resulting *
* Package will still be considered the Standard Version, and as such will be *
* subject to the Original License. *
* Distribution of Modified Versions of the Package as Source *
* *
* (4) You may Distribute your Modified Version as Source (either gratis or for *
* a Distributor Fee, and with or without a Compiled form of the Modified *
* Version) provided that you clearly document how it differs from the Standard *
* Version, including, but not limited to, documenting any non-standard *
* features, executables, or modules, and provided that you do at least ONE of *
* the following: *
* *
* (a) make the Modified Version available to the Copyright Holder of the *
* Standard Version, under the Original License, so that the Copyright Holder *
* may include your modifications in the Standard Version. *
* (b) ensure that installation of your Modified Version does not prevent the *
* user installing or running the Standard Version. In addition, the Modified *
* Version must bear a name that is different from the name of the Standard *
* Version. *
* (c) allow anyone who receives a copy of the Modified Version to make the *
* Source form of the Modified Version available to others under *
* (i) the Original License or *
* (ii) a license that permits the licensee to freely copy, modify and *
* redistribute the Modified Version using the same licensing terms that apply *
* to the copy that the licensee received, and requires that the Source form of *
* the Modified Version, and of any works derived from it, be made freely *
* available in that license fees are prohibited but Distributor Fees are *
* allowed. *
* Distribution of Compiled Forms of the Standard Version or Modified Versions *
* without the Source *
* *
* (5) You may Distribute Compiled forms of the Standard Version without the *
* Source, provided that you include complete instructions on how to get the *
* Source of the Standard Version. Such instructions must be valid at the time *
* of your distribution. If these instructions, at any time while you are *
* carrying out such distribution, become invalid, you must provide new *
* instructions on demand or cease further distribution. If you provide valid *
* instructions or cease distribution within thirty days after you become aware *
* that the instructions are invalid, then you do not forfeit any of your *
* rights under this license. *
* *
* (6) You may Distribute a Modified Version in Compiled form without the *
* Source, provided that you comply with Section 4 with respect to the Source *
* of the Modified Version. *
* Aggregating or Linking the Package *
* *
* (7) You may aggregate the Package (either the Standard Version or Modified *
* Version) with other packages and Distribute the resulting aggregation *
* provided that you do not charge a licensing fee for the Package. Distributor *
* Fees are permitted, and licensing fees for other components in the *
* aggregation are permitted. The terms of this license apply to the use and *
* Distribution of the Standard or Modified Versions as included in the *
* aggregation. *
* *
* (8) You are permitted to link Modified and Standard Versions with other *
* works, to embed the Package in a larger work of your own, or to build *
* stand-alone binary or bytecode versions of applications that include the *
* Package, and Distribute the result without restriction, provided the result *
* does not expose a direct interface to the Package. *
* Items That are Not Considered Part of a Modified Version *
* *
* (9) Works (including, but not limited to, modules and scripts) that merely *
* extend or make use of the Package, do not, by themselves, cause the Package *
* to be a Modified Version. In addition, such works are not considered parts *
* of the Package itself, and are not subject to the terms of this license. *
* General Provisions *
* *
* (10) Any use, modification, and distribution of the Standard or Modified *
* Versions is governed by this Artistic License. By using, modifying or *
* distributing the Package, you accept this license. Do not use, modify, or *
* distribute the Package, if you do not accept this license. *
* *
* (11) If your Modified Version has been derived from a Modified Version made *
* by someone other than you, you are nevertheless required to ensure that your *
* Modified Version complies with the requirements of this license. *
* *
* (12) This license does not grant you the right to use any trademark, service *
* mark, tradename, or logo of the Copyright Holder. *
* *
* (13) This license includes the non-exclusive, worldwide, free-of-charge *
* patent license to make, have made, use, offer to sell, sell, import and *
* otherwise transfer the Package with respect to any patent claims licensable *
* by the Copyright Holder that are necessarily infringed by the Package. If *
* you institute patent litigation (including a cross-claim or counterclaim) *
* against any party alleging that the Package constitutes direct or *
* contributory patent infringement, then this Artistic License to you shall *
* terminate on the date that such litigation is filed. *
* *
* (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER *
* AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR *
* NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. *
* UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN *
* ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
* The End *
* *
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IsNumberDigit(c) ('0' <= c && c <= '9')
#define IsSignDigit(c) (c == '+' || c == '-')
#define isOperator(x) (x == '+' || x == '*' || x == '#' || x == '=')
#define freadline(fd) freadstr(fd, "\n");
int IsRealNumber(char *c);
int IsPosNumber(const char *c);
int IsNumber(const char *c);
char * freadstr(FILE *fd, const char *separators);
int CharIn(const char c, const char *in);
int patternmatch(char *pattern, char *thestr);

View File

@ -0,0 +1,275 @@
/******************************************************************
**
** IQUEUE.C:
**
** ADT Queue Iterator Implementation
**
** This file is part of Apt Abstrct Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
** The concept of an iterator for an Abstract Data Type is derived
** from research on Smalltalk.
******************************************************************/
/* ---------- C Headers */
//#include "cheaders.h"
/* ---------- Headers */
#include "adterror.h"
#include "allocate.h"
#include "iqueue.h"
/* ---------- Private Function Prototypes */
#ifdef __ANSI_C__
#else
#endif
/* ---------- Functions */
/*
**
** QueueIteratorDispose
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueIteratorDispose(QueueIterator qi)
#else
void QueueIteratorDispose(qi)
QueueIterator qi;
#endif
{
free(qi);
}
/*
**
** QueueIteratorNew
**
*/
PUBLIC
#ifdef __ANSI_C__
QueueIterator QueueIteratorNew(Queue q, int start)
#else
QueueIterator QueueIteratorNew(q,start)
Queue q;
int start;
#endif
{
QueueIterator qi;
if (q)
qi = ((QueueIterator)Allocate(sizeof(_QueueIterator)));
else
ADTError(ADT_QueueIter, E_NullQueue, "QueueIteratorNew");
if (qi) {
qi->queue = q;
QueueIteratorAbsoluteSeek(qi, start);
} else
ADTError(ADT_QueueIter, E_Allocation, "QueueIteratorNew");
return (qi);
}
/*
**
** QueueIteratorAtTop
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueIteratorAtTop(QueueIterator qi)
#else
int QueueIteratorAtTop(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorAtTop");
return QueueIteratorAtPosition(qi,1);
}
/*
**
** QueueIteratorAtBottom
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueIteratorAtBottom(QueueIterator qi)
#else
int QueueIteratorAtBottom(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorAtBottom");
return QueueIteratorAtPosition(qi,0);
}
/*
**
** QueueIteratorAtPosition
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueIteratorAtPosition(QueueIterator qi, int position)
#else
int QueueIteratorAtPosition(qi,position)
QueueIterator qi;
int position;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorAtPosition");
if (position <= 0)
position += (QueueSize(qi->queue) + 1);
return qi->position == position;
}
/*
**
** QueueIteratorPosition
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueIteratorPosition(QueueIterator qi)
#else
int QueueIteratorPosition(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorPosition");
return qi->position;
}
/*
**
** QueueIteratorCurrentData
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueIteratorCurrentData(QueueIterator qi)
#else
void *QueueIteratorCurrentData(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorCurrentData");
return QueueItemElement(qi->currentItem);
}
/*
**
** QueueIteratorPreviousData
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueIteratorPreviousData(QueueIterator qi)
#else
void *QueueIteratorPreviousData(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorPreviousData");
return QueueItemElement(qi->previousItem);
}
/*
**
** QueueIteratorAdvance
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueIteratorAdvance(QueueIterator qi)
#else
void QueueIteratorAdvance(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorAdvance");
qi->previousItem = qi->currentItem;
qi->currentItem = QueueNext(qi->previousItem);
if (qi->previousItem) qi->position++;
}
/*
**
** QueueIteratorBackup
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueIteratorBackup(QueueIterator qi)
#else
void QueueIteratorBackup(qi)
QueueIterator qi;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorBackup");
QueueIteratorRelativeSeek(qi, -1);
}
/*
**
** QueueIteratorAbsoluteSeek
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueIteratorAbsoluteSeek(QueueIterator qi, int position)
#else
void QueueIteratorAbsoluteSeek(qi,position)
QueueIterator qi;
int position;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorAbsoluteSeek");
if (position <= 0)
position += (QueueSize(qi->queue) + 1);
if (position <= 0)
ADTError(ADT_QueueIter, E_Seek, "QueueIteratorAbsoluteSeek");
/* Here, we know position is positive */
if (position > QueueSize(qi->queue) + 1)
qi->position = QueueSize(qi->queue) + 1;
else
qi->position = position;
qi->previousItem = QueueSeek(qi->queue,position-1);
if (qi->previousItem)
qi->currentItem = QueueNext(qi->previousItem);
else
qi->currentItem = QueueSeek(qi->queue,position);
}
/*
**
** QueueIteratorRelativeSeek
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueIteratorRelativeSeek(QueueIterator qi,int disp)
#else
void QueueIteratorRelativeSeek(qi,disp)
QueueIterator qi;
int disp;
#endif
{
if (!qi)
ADTError(ADT_QueueIter, E_NullQueueIter, "QueueIteratorRelativeSeek");
QueueIteratorAbsoluteSeek(qi,qi->position+disp);
}

View File

@ -0,0 +1,66 @@
/******************************************************************
**
** IQUEUE.H:
**
** ADT Queue Iterator Implementation
**
** This file is part of Apt Abstract Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
#ifndef IQUEUE_H
#define IQUEUE_H
/* ---------- Headers */
#include "pqueue.h"
/* ---------- Types */
typedef struct _QueueIterator {
int position;
Queue queue;
QueueItem currentItem, previousItem;
} _QueueIterator, *QueueIterator;
/* ---------- Exported Function Prototypes */
#ifdef __ANSI_C__
QueueIterator QueueIteratorNew(Queue,int);
void QueueIteratorDispose(QueueIterator);
int QueueIteratorAtTop(QueueIterator);
int QueueIteratorAtBottom(QueueIterator);
int QueueIteratorAtPosition(QueueIterator,int);
int QueueIteratorPosition(QueueIterator);
void *QueueIteratorCurrentData(QueueIterator);
void *QueueIteratorPreviousData(QueueIterator);
void QueueIteratorAdvance(QueueIterator);
void QueueIteratorBackup(QueueIterator);
void QueueIteratorAbsoluteSeek(QueueIterator,int);
void QueueIteratorRelativeSeek(QueueIterator,int);
#else
QueueIterator QueueIteratorNew();
void QueueIteratorDispose();
int QueueIteratorAtTop();
int QueueIteratorAtBottom();
int QueueIteratorAtPosition();
int QueueIteratorPosition();
void *QueueIteratorCurrentData();
void *QueueIteratorPreviousData();
void QueueIteratorAdvance();
void QueueIteratorBackup();
void QueueIteratorAbsoluteSeek();
void QueueIteratorRelativeSeek();
#endif /* __ANSI_C__ */
#endif /* QUEUE_H */

View File

@ -0,0 +1,715 @@
/******************************************************************
**
** QUEUE.C:
**
** ADT Queue Implementation
**
** This file is part of Apt Abstrct Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
/* ---------- C Headers */
//#include "cheaders.h"
/* ---------- Headers */
#include "apt.h"
#include "allocate.h"
#include "pqueue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ---------- Private Function Prototypes */
#ifdef __ANSI_C__
PRIVATE void QueueDisposeItem(QueueItem, DisposeFunction);
PRIVATE QueueItem QueueGetItem(Queue);
PRIVATE QueueItem QueueNewItem(void*, int);
PRIVATE void QueuePutItem(Queue, QueueItem);
PRIVATE QueueItem QueueRemoveItem(Queue, QueueItem);
PRIVATE int QueueCompareEqual(void *, void *);
#else
PRIVATE void QueueDisposeItem();
PRIVATE QueueItem QueueGetItem();
PRIVATE QueueItem QueueNewItem();
PRIVATE void QueuePutItem();
PRIVATE QueueItem QueueRemoveItem();
PRIVATE int QueueCompareEqual();
#endif
/* ---------- Functions */
/*
**
** QueueApply
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueApply(Queue q, ApplyFunction f)
#else
void QueueApply(q,f)
Queue q;
ApplyFunction f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
(*f)(item->element);
}
}
/*
**
** QueueApply1
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueApply1(Queue q, void *p1, ApplyFunction1 f)
#else
void QueueApply1(q,p1,f)
Queue q;
void *p1;
ApplyFunction1 f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
(*f)(item->element,p1);
}
}
/*
**
** QueueApply2
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueApply2(Queue q, void *p1, void *p2, ApplyFunction2 f)
#else
void QueueApply2(q,p1,p2,f)
Queue q;
void *p1;
void *p2;
ApplyFunction2 f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
(*f)(item->element,p1,p2);
}
}
/*
**
** QueueApply3
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueApply3(Queue q, void *p1, void* p2, void *p3, ApplyFunction3 f)
#else
void QueueApply3(q,p1,p2,p3,f)
Queue q;
void *p1;
void *p2;
void *p3;
ApplyFunction3 f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
(*f)(item->element,p1,p2,p3);
}
}
/*
**
** QueueCAR
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueCAR(Queue q)
#else
void *QueueCAR(q)
Queue q;
#endif
{
if (q != NULL && q->head != NULL)
return QueueItemElement(q->head);
return NULL;
}
/*
**
** QueueCDR
**
*/
PUBLIC
#ifdef __ANSI_C__
Queue QueueCDR(Queue q)
#else
Queue QueueCDR(q)
Queue q;
#endif
{
if (q != NULL && q->head != NULL) {
Queue new = QueueNew();
new->head = q->head->next;
new->tail = new->head != NULL ? q->tail : NULL;
new->size = q->size-1;
return new;
} else
return NULL;
}
/*
**
** QueueDispose
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueueDispose(Queue q, DisposeFunction f)
#else
void QueueDispose(q,f)
Queue q;
DisposeFunction f;
#endif
{
QueueItem item;
QueueItem next = NULL;
for (item = q->head; item != NULL; item = next) {
next = item->next;
QueueDisposeItem(item,f);
}
free(q);
}
/*
**
** QueueDisposeItem
**
*/
PRIVATE
#ifdef __ANSI_C__
void QueueDisposeItem(QueueItem item, DisposeFunction f)
#else
void QueueDisposeItem(item,f)
QueueItem item;
DisposeFunction f;
#endif
{
if (f) (*f)(item->element);
free(item);
}
/*
**
** QueueFind
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueFind(Queue q, void *element, ComparisonFunction f)
#else
void *QueueFind(q,element,f)
Queue q;
void *element;
ComparisonFunction f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
if ((*f)(element,item->element) == 0) break;
}
return (item != NULL ? item->element : NULL);
}
/*
**
** QueueFindAndRemove
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueFindAndRemove(Queue q, void *element,
ComparisonFunction f)
#else
void *QueueFindAndRemove(q, element, f)
Queue q;
void *element;
ComparisonFunction f;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
if ((*f)(element,item->element) == 0) break;
}
item = QueueRemoveItem(q,item);
return (item != NULL ? item->element : NULL);
}
/*
**
** QueueFindAndRemoveType
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueFindAndRemoveType(Queue q, void *element,
ComparisonFunction f, int type)
#else
void *QueueFindAndRemoveType(q, element, f, type)
Queue q;
void *element;
ComparisonFunction f;
int type;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
if ((*f)(element,item->element) == 0 && item->type == type) break;
}
item = QueueRemoveItem(q,item);
return (item != NULL ? item->element : NULL);
}
/*
**
** QueueFindType
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueFindType(Queue q, int type)
#else
void *QueueFindType(q,type)
Queue q;
int type;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
if (item->type == type) break;
}
return (item != NULL ? item->element : NULL);
}
/*
**
** QueueFindTypeAndRemove
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueFindTypeAndRemove(Queue q, int type)
#else
void *QueueFindTypeAndRemove(q,type)
Queue q;
int type;
#endif
{
QueueItem item;
for (item = q->head; item != NULL; item = item->next) {
if (item->type == type) break;
}
return (QueueRemoveItem(q,item));
}
/*
**
** QueueGet
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueGet(Queue q)
#else
void *QueueGet(q)
Queue q;
#endif
{
void *element;
QueueItem item;
item = QueueGetItem(q);
if (item) {
element = item->element;
QueueDisposeItem(item,NULL);
}
else element = NULL;
return (element);
}
/*
**
** QueueGetItem
**
*/
PRIVATE
#ifdef __ANSI_C__
QueueItem QueueGetItem(Queue q)
#else
QueueItem QueueGetItem(q)
Queue q;
#endif
{
QueueItem item;
if (q->head) {
item = q->head;
q->head = q->head->next;
q->size--;
}
else item = NULL;
return (item);
}
/*
**
** QueueHead
**
*/
PUBLIC
#ifdef __ANSI_C__
QueueItem QueueHead(Queue q)
#else
QueueItem QueueHead(q)
Queue q;
#endif
{
return q != NULL ? q->head : NULL;
}
/*
**
** QueueItemElement
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueItemElement(QueueItem item)
#else
void *QueueItemElement(item)
QueueItem item;
#endif
{
return (item->element);
}
/*
**
** QueueItemType
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueItemType(QueueItem item)
#else
int QueueItemType(item)
QueueItem item;
#endif
{
return (item->type);
}
/*
**
** QueueLook
**
*/
PUBLIC
#ifdef __ANSI_C__
void *QueueLook(Queue q)
#else
void *QueueLook(q)
Queue q;
#endif
{
QueueItem item;
item = q->head;
return (item != NULL ? item->element : NULL);
}
/*
**
** QueueNew
**
*/
PUBLIC
#ifdef __ANSI_C__
Queue QueueNew(void)
#else
Queue QueueNew()
#endif
{
Queue q;
q = ((Queue)Allocate(sizeof(_Queue)));
if (q) {
q->head = q->tail = NULL;
q->size = 0;
}
return (q);
}
/*
**
** QueueNewItem
**
*/
PRIVATE
#ifdef __ANSI_C__
QueueItem QueueNewItem(void *element, int type)
#else
QueueItem QueueNewItem(element,type)
void *element;
int type;
#endif
{
QueueItem item;
item = ((QueueItem)Allocate(sizeof(_QueueItem)));
if (item) {
item->element = element;
item->type = type;
item->next = NULL;
}
return (item);
}
/*
**
** QueueNext
**
*/
PUBLIC
#ifdef __ANSI_C__
QueueItem QueueNext(QueueItem item)
#else
QueueItem QueueNext(item)
QueueItem item;
#endif
{
return item != NULL ? item->next : NULL;
}
/*
**
** QueuePut
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueuePut(Queue q, void *element, int type)
#else
void QueuePut(q,element,type)
Queue q;
void *element;
int type;
#endif
{
QueueItem item;
item = QueueNewItem(element,type);
QueuePutItem(q,item);
}
/*
**
** QueuePutItem
**
*/
PRIVATE
#ifdef __ANSI_C__
void QueuePutItem(Queue q, QueueItem item)
#else
void QueuePutItem(q,item)
Queue q;
QueueItem item;
#endif
{
if (q->head == NULL) {
q->head = q->tail = item;
} else {
q->tail->next = item;
q->tail = q->tail->next;
}
q->size++;
}
/*
**
** QueuePutOnPriority
**
*/
PUBLIC
#ifdef __ANSI_C__
void QueuePutOnPriority(Queue q, void *element, int type,
ComparisonFunction f)
#else
void QueuePutOnPriority(q,element,type,f)
Queue q;
void *element;
int type;
ComparisonFunction f;
#endif
{
QueueItem item;
item = QueueNewItem(element,type);
//fprintf(stderr,"searching for location using %p.\n",f);
if (f == NULL){
//fprintf(stderr,"comparing function is null %f \n",f);
exit(1);
QueuePutItem(q,item);
}else {
if (q->head == NULL) QueuePutItem(q,item);
else {
QueueItem p, lastp = NULL;
for (p = q->head; p != NULL; p = p->next) {
int cval =(*f)(element,p->element);
if (cval<0){
// fprintf(stderr,"%i <=> %i == %i\n",*((int *) element),*((int *)(p->element)),
// cval);
break;
}
lastp = p;
}
if (p == q->head) {
item->next = q->head;
q->head = item;
} else if (p == NULL) {
q->tail->next = item;
q->tail = q->tail->next;
} else {
item->next = p;
lastp->next = item;
}
q->size++;
}
}
}
/*
**
** QueueRemoveItem
**
*/
PRIVATE
#ifdef __ANSI_C__
QueueItem QueueRemoveItem(Queue q, QueueItem item)
#else
QueueItem QueueRemoveItem(q,item)
Queue q;
QueueItem item;
#endif
{
QueueItem this, prev = NULL;
if (q == NULL) return (NULL);
if (item == NULL) return (NULL);
this = q->head;
while (this && this != item) {
prev = this; this = this->next;
}
if (this == NULL) return (NULL);
if (this == q->head) q->head = item->next;
if (this == q->tail) q->tail = prev;
if (prev) prev->next = this->next;
q->size--;
return (item);
}
/*
**
** QueueSeek
**
*/
PUBLIC
#ifdef __ANSI_C__
QueueItem QueueSeek(Queue q, int position)
#else
QueueItem QueueSeek(q,position)
Queue q;
int position;
#endif
{
QueueItem item;
#if 0
/* Allow single-level negative addressing of queue items */
if (position <= 0)
position += QueueSize(q);
#endif
/* Seeks which fail will result in NULL, not error conditions */
if (position <= 0 || position > QueueSize(q))
return NULL;
item = QueueHead(q);
while (--position > 0)
item = QueueNext(item);
return item;
}
/*
**
** QueueSize
**
*/
PUBLIC
#ifdef __ANSI_C__
int QueueSize(Queue q)
#else
int QueueSize(q)
Queue q;
#endif
{
return q != NULL ? q->size : 0;
}
/*
**
** QueueTail
**
*/
PUBLIC
#ifdef __ANSI_C__
QueueItem QueueTail(Queue q)
#else
QueueItem QueueTail(q)
Queue q;
#endif
{
return q != NULL ? q->tail : NULL;
}
PRIVATE
#ifdef __ANSI_C__
int QueueCompareEqual(void *x, void *y)
#else
int QueueCompareEqual(x,y)
void *x, *y;
#endif
{
return 0;
}

View File

@ -0,0 +1,94 @@
/******************************************************************
**
** QUEUE.H:
**
** ADT Queue Implementation
**
** This file is part of Apt Abstract Data Types (ADT)
** Copyright (c) 1991 -- Apt Technologies
** All rights reserved
**
******************************************************************/
//http://www.koders.com/c/fid7B82D8DDECE4EDC672F17D970458033C4079A615.aspx?s=queue
/*
** This ADT, originally written in 1989, provides a general queue
** implementation--in C--which is the equivalent of the Java Vector.
*/
#ifndef QUEUE_H
#define QUEUE_H
/* ---------- Headers */
#include "apt.h"
/* ---------- Types */
typedef struct _QueueItem {
void *element;
int type;
struct _QueueItem *next;
} _QueueItem, *QueueItem;
typedef struct _Queue {
struct _QueueItem *head;
struct _QueueItem *tail;
int size;
} _Queue, *Queue;
/* ---------- Exported Function Prototypes */
#ifdef __ANSI_C__
void QueueApply(Queue, ApplyFunction);
void QueueApply1(Queue, void*, ApplyFunction1);
void QueueApply2(Queue, void*, void*, ApplyFunction2);
void QueueApply3(Queue, void*, void*, void*, ApplyFunction3);
void *QueueCAR(Queue);
Queue QueueCDR(Queue);
void QueueDispose(Queue, DisposeFunction);
void *QueueFind(Queue, void*, ComparisonFunction);
void *QueueFindAndRemove(Queue, void*, ComparisonFunction);
void *QueueFindAndRemoveType(Queue, void*, ComparisonFunction, int);
void *QueueFindType(Queue, int);
void *QueueFindTypeAndRemove(Queue, int);
void *QueueGet(Queue);
QueueItem QueueHead(Queue);
void *QueueItemElement(QueueItem);
int QueueItemType(QueueItem);
void *QueueLook(Queue);
Queue QueueNew(void);
QueueItem QueueNext(QueueItem);
void QueuePut(Queue, void*, int);
void QueuePutOnPriority(Queue, void*, int, ComparisonFunction);
QueueItem QueueSeek(Queue,int);
int QueueSize(Queue);
QueueItem QueueTail(Queue);
#else
void QueueApply();
void QueueApply1();
void QueueApply2();
void QueueApply3();
void *QueueCAR();
Queue QueueCDR();
void QueueDispose();
void *QueueFind();
void *QueueFindAndRemove();
void *QueueFindAndRemoveType();
void *QueueFindType();
void *QueueFindTypeAndRemove();
void *QueueGet();
QueueItem QueueHead();
void *QueueItemElement();
int QueueItemType();
void *QueueLook();
Queue QueueNew();
QueueItem QueueNext();
void QueuePut();
void QueuePutOnPriority();
QueueItem QueueSeek();
int QueueSize();
QueueItem QueueTail();
#endif /* __ANSI_C__ */
#endif /* QUEUE_H */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,293 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright T. Mantadelis, A. Kimmig, B. Gutmann *
* and Katholieke Universiteit Leuven 2008 *
* *
* Author: Bernd Gutmann *
* File: problogmath.c *
* $Date:: 2009-12-06 00:55:33 +0100 (Sun, 06 Dec 2009) $ *
* $Revision:: 2919 $ *
* *
* *
********************************************************************************
* *
* The "Artistic License" *
* *
* Preamble *
* *
* The intent of this document is to state the conditions under which a *
* Package may be copied, such that the Copyright Holder maintains some *
* semblance of artistic control over the development of the package, *
* while giving the users of the package the right to use and distribute *
* the Package in a more-or-less customary fashion, plus the right to make *
* reasonable modifications. *
* *
* Definitions: *
* *
* "Package" refers to the collection of files distributed by the *
* Copyright Holder, and derivatives of that collection of files *
* created through textual modification. *
* *
* "Standard Version" refers to such a Package if it has not been *
* modified, or has been modified in accordance with the wishes *
* of the Copyright Holder as specified below. *
* *
* "Copyright Holder" is whoever is named in the copyright or *
* copyrights for the package. *
* *
* "You" is you, if you're thinking about copying or distributing *
* this Package. *
* *
* "Reasonable copying fee" is whatever you can justify on the *
* basis of media cost, duplication charges, time of people involved, *
* and so on. (You will not be required to justify it to the *
* Copyright Holder, but only to the computing community at large *
* as a market that must bear the fee.) *
* *
* "Freely Available" means that no fee is charged for the item *
* itself, though there may be fees involved in handling the item. *
* It also means that recipients of the item may redistribute it *
* under the same conditions they received it. *
* *
* 1. You may make and give away verbatim copies of the source form of the *
* Standard Version of this Package without restriction, provided that you *
* duplicate all of the original copyright notices and associated disclaimers. *
* *
* 2. You may apply bug fixes, portability fixes and other modifications *
* derived from the Public Domain or from the Copyright Holder. A Package *
* modified in such a way shall still be considered the Standard Version. *
* *
* 3. You may otherwise modify your copy of this Package in any way, provided *
* that you insert a prominent notice in each changed file stating how and *
* when you changed that file, and provided that you do at least ONE of the *
* following: *
* *
* a) place your modifications in the Public Domain or otherwise make them *
* Freely Available, such as by posting said modifications to Usenet or *
* an equivalent medium, or placing the modifications on a major archive *
* site such as uunet.uu.net, or by allowing the Copyright Holder to include *
* your modifications in the Standard Version of the Package. *
* *
* b) use the modified Package only within your corporation or organization. *
* *
* c) rename any non-standard executables so the names do not conflict *
* with standard executables, which must also be provided, and provide *
* a separate manual page for each non-standard executable that clearly *
* documents how it differs from the Standard Version. *
* *
* d) make other distribution arrangements with the Copyright Holder. *
* *
* 4. You may distribute the programs of this Package in object code or *
* executable form, provided that you do at least ONE of the following: *
* *
* a) distribute a Standard Version of the executables and library files, *
* together with instructions (in the manual page or equivalent) on where *
* to get the Standard Version. *
* *
* b) accompany the distribution with the machine-readable source of *
* the Package with your modifications. *
* *
* c) give non-standard executables non-standard names, and clearly *
* document the differences in manual pages (or equivalent), together *
* with instructions on where to get the Standard Version. *
* *
* d) make other distribution arrangements with the Copyright Holder. *
* *
* 5. You may charge a reasonable copying fee for any distribution of this *
* Package. You may charge any fee you choose for support of this *
* Package. You may not charge a fee for this Package itself. However, *
* you may distribute this Package in aggregate with other (possibly *
* commercial) programs as part of a larger (possibly commercial) software *
* distribution provided that you do not advertise this Package as a *
* product of your own. You may embed this Package's interpreter within *
* an executable of yours (by linking); this shall be construed as a mere *
* form of aggregation, provided that the complete Standard Version of the *
* interpreter is so embedded. *
* *
* 6. The scripts and library files supplied as input to or produced as *
* output from the programs of this Package do not automatically fall *
* under the copyright of this Package, but belong to whoever generated *
* them, and may be sold commercially, and may be aggregated with this *
* Package. If such scripts or library files are aggregated with this *
* Package via the so-called "undump" or "unexec" methods of producing a *
* binary executable image, then distribution of such an image shall *
* neither be construed as a distribution of this Package nor shall it *
* fall under the restrictions of Paragraphs 3 and 4, provided that you do *
* not represent such an executable image as a Standard Version of this *
* Package. *
* *
* 7. C subroutines (or comparably compiled subroutines in other *
* languages) supplied by you and linked into this Package in order to *
* emulate subroutines and variables of the language defined by this *
* Package shall not be considered part of this Package, but are the *
* equivalent of input as in Paragraph 6, provided these subroutines do *
* not change the language in any way that would cause it to fail the *
* regression tests for the language. *
* *
* 8. Aggregation of this Package with a commercial distribution is always *
* permitted provided that the use of this Package is embedded; that is, *
* when no overt attempt is made to make this Package's interfaces visible *
* to the end user of the commercial distribution. Such use shall not be *
* construed as a distribution of this Package. *
* *
* 9. The name of the Copyright Holder may not be used to endorse or promote *
* products derived from this software without specific prior written *
* permission. *
* *
* 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR *
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* The End *
* *
\******************************************************************************/
#include "problogmath.h"
double sigmoid(double x, double slope) {
return 1.0 / (1.0 + exp(-x * slope));
}
// This function calculates the accumulated density of the normal distribution
// For details see G. Marsaglia, Evaluating the Normal Distribution, Journal of Statistical Software, 2004:11(4).
double Phi(double x) {
double s=x;
double t=0.0;
double b=x;
double q=x*x;
double i=1;
// if the value is too small or too big, return
// 0/1 to avoid long computations
if (x < -10.0) {
return 0.0;
}
if (x > 10.0) {
return 1.0;
}
// t is the value from last iteration
// s is the value from the current iteration
// iterate until they are equal
while(fabs(s-t) >= DBL_MIN) {
t=s;
i+=2;
b*=q/i;
s+=b;
}
return 0.5+s*exp(-0.5*q-0.91893853320467274178);
}
// integrates the normal distribution over [low,high]
double cumulative_normal(double low, double high, double mu, double sigma) {
return Phi((high-mu)/sigma) - Phi((low-mu)/sigma);
}
// evaluates the density of the normal distribution
double normal(double x, double mu,double sigma) {
double inner=(x-mu)/sigma;
double denom=sigma*sqrt(2*3.14159265358979323846);
return exp(-inner*inner/2)/denom;
}
double cumulative_normal_dmu(double low, double high,double mu,double sigma) {
return normal(low,mu,sigma) - normal(high,mu,sigma);
}
double cumulative_normal_dsigma(double low, double high,double mu,double sigma) {
return ((mu-high)*normal(high,mu,sigma) - (mu-low)*normal(low,mu,sigma))/sigma;
}
// this function parses two strings "$a;$b" and "???_???l$ch$d" where $a-$d are (real) numbers
// it is used to parse in the parameters of continues variables from the input file
density_integral parse_density_integral_string(char *input, char *variablename) {
density_integral result;
int i;
char garbage[64], s1[64],s2[64],s3[64],s4[64];
if(sscanf(input, "%64[^;];%64[^;]", s1,s2) != 2) {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "The string should contain 2 fields seperated by ; characters.\n");
exit(EXIT_FAILURE);
}
if (IsRealNumber(s1)) {
result.mu=atof(s1);
} else {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "%s is not a number\n",s1);
exit(EXIT_FAILURE);
}
if (IsRealNumber(s2)) {
result.sigma=atof(s2);
} else {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "%s is not a number\n",s2);
exit(EXIT_FAILURE);
}
if (result.sigma<=0) {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string",input);
fprintf(stderr, "The value for sigma has to be larger than 0.\n");
exit(EXIT_FAILURE);
}
if (sscanf(variablename,"%64[^lh]l%64[^lh]h%64[^lh]",garbage,s3,s4) != 3) {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string\n",variablename);
fprintf(stderr, "The string should contain 2 fields seperated by ; characters.\n");
exit(EXIT_FAILURE);
}
// replace the d by . in s1 and s2
for(i=0; s3[i]!='\0' ; i++) {
if (s3[i]=='d') {
s3[i]='.';
}
if (s3[i]=='m') {
s3[i]='-';
}
}
for(i=0; s4[i]!='\0' ; i++) {
if (s4[i]=='d') {
s4[i]='.';
}
if (s4[i]=='m') {
s4[i]='-';
}
}
if (IsRealNumber(s3)) {
result.low=atof(s3);
} else {
fprintf(stderr, "Error at parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "%s is not a number\n",s1);
exit(EXIT_FAILURE);
}
if (IsRealNumber(s4)) {
result.high=atof(s4);
} else {
fprintf(stderr, "Error ar parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "%s is not a number\n",s1);
exit(EXIT_FAILURE);
}
if (result.low>result.high) {
fprintf(stderr, "Error ar parsing the string %s in the function parse_density_integral_string\n",input);
fprintf(stderr, "The value for low has to be larger than then value for high.\n");
exit(EXIT_FAILURE);
}
return result;
}

View File

@ -0,0 +1,168 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright T. Mantadelis, A. Kimmig, B. Gutmann *
* and Katholieke Universiteit Leuven 2008 *
* *
* Author: Bernd Gutmann *
* File: problogmath.h *
* $Date:: 2009-08-17 17:45:21 +0200 (Mon, 17 Aug 2009) $ *
* $Revision:: 1900 $ *
* *
* *
********************************************************************************
* *
* The "Artistic License" *
* *
* Preamble *
* *
* The intent of this document is to state the conditions under which a *
* Package may be copied, such that the Copyright Holder maintains some *
* semblance of artistic control over the development of the package, *
* while giving the users of the package the right to use and distribute *
* the Package in a more-or-less customary fashion, plus the right to make *
* reasonable modifications. *
* *
* Definitions: *
* *
* "Package" refers to the collection of files distributed by the *
* Copyright Holder, and derivatives of that collection of files *
* created through textual modification. *
* *
* "Standard Version" refers to such a Package if it has not been *
* modified, or has been modified in accordance with the wishes *
* of the Copyright Holder as specified below. *
* *
* "Copyright Holder" is whoever is named in the copyright or *
* copyrights for the package. *
* *
* "You" is you, if you're thinking about copying or distributing *
* this Package. *
* *
* "Reasonable copying fee" is whatever you can justify on the *
* basis of media cost, duplication charges, time of people involved, *
* and so on. (You will not be required to justify it to the *
* Copyright Holder, but only to the computing community at large *
* as a market that must bear the fee.) *
* *
* "Freely Available" means that no fee is charged for the item *
* itself, though there may be fees involved in handling the item. *
* It also means that recipients of the item may redistribute it *
* under the same conditions they received it. *
* *
* 1. You may make and give away verbatim copies of the source form of the *
* Standard Version of this Package without restriction, provided that you *
* duplicate all of the original copyright notices and associated disclaimers. *
* *
* 2. You may apply bug fixes, portability fixes and other modifications *
* derived from the Public Domain or from the Copyright Holder. A Package *
* modified in such a way shall still be considered the Standard Version. *
* *
* 3. You may otherwise modify your copy of this Package in any way, provided *
* that you insert a prominent notice in each changed file stating how and *
* when you changed that file, and provided that you do at least ONE of the *
* following: *
* *
* a) place your modifications in the Public Domain or otherwise make them *
* Freely Available, such as by posting said modifications to Usenet or *
* an equivalent medium, or placing the modifications on a major archive *
* site such as uunet.uu.net, or by allowing the Copyright Holder to include *
* your modifications in the Standard Version of the Package. *
* *
* b) use the modified Package only within your corporation or organization. *
* *
* c) rename any non-standard executables so the names do not conflict *
* with standard executables, which must also be provided, and provide *
* a separate manual page for each non-standard executable that clearly *
* documents how it differs from the Standard Version. *
* *
* d) make other distribution arrangements with the Copyright Holder. *
* *
* 4. You may distribute the programs of this Package in object code or *
* executable form, provided that you do at least ONE of the following: *
* *
* a) distribute a Standard Version of the executables and library files, *
* together with instructions (in the manual page or equivalent) on where *
* to get the Standard Version. *
* *
* b) accompany the distribution with the machine-readable source of *
* the Package with your modifications. *
* *
* c) give non-standard executables non-standard names, and clearly *
* document the differences in manual pages (or equivalent), together *
* with instructions on where to get the Standard Version. *
* *
* d) make other distribution arrangements with the Copyright Holder. *
* *
* 5. You may charge a reasonable copying fee for any distribution of this *
* Package. You may charge any fee you choose for support of this *
* Package. You may not charge a fee for this Package itself. However, *
* you may distribute this Package in aggregate with other (possibly *
* commercial) programs as part of a larger (possibly commercial) software *
* distribution provided that you do not advertise this Package as a *
* product of your own. You may embed this Package's interpreter within *
* an executable of yours (by linking); this shall be construed as a mere *
* form of aggregation, provided that the complete Standard Version of the *
* interpreter is so embedded. *
* *
* 6. The scripts and library files supplied as input to or produced as *
* output from the programs of this Package do not automatically fall *
* under the copyright of this Package, but belong to whoever generated *
* them, and may be sold commercially, and may be aggregated with this *
* Package. If such scripts or library files are aggregated with this *
* Package via the so-called "undump" or "unexec" methods of producing a *
* binary executable image, then distribution of such an image shall *
* neither be construed as a distribution of this Package nor shall it *
* fall under the restrictions of Paragraphs 3 and 4, provided that you do *
* not represent such an executable image as a Standard Version of this *
* Package. *
* *
* 7. C subroutines (or comparably compiled subroutines in other *
* languages) supplied by you and linked into this Package in order to *
* emulate subroutines and variables of the language defined by this *
* Package shall not be considered part of this Package, but are the *
* equivalent of input as in Paragraph 6, provided these subroutines do *
* not change the language in any way that would cause it to fail the *
* regression tests for the language. *
* *
* 8. Aggregation of this Package with a commercial distribution is always *
* permitted provided that the use of this Package is embedded; that is, *
* when no overt attempt is made to make this Package's interfaces visible *
* to the end user of the commercial distribution. Such use shall not be *
* construed as a distribution of this Package. *
* *
* 9. The name of the Copyright Holder may not be used to endorse or promote *
* products derived from this software without specific prior written *
* permission. *
* *
* 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR *
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* The End *
* *
\******************************************************************************/
#include <math.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _density_integral {
double low;
double high;
double mu;
double sigma;
} density_integral;
double sigmoid(double x, double slope);
double Phi(double x);
double cumulative_normal(double low, double high, double sigma, double mu);
double cumulative_normal_dmu(double low, double high,double mu,double sigma);
double cumulative_normal_dsigma(double low, double high,double mu,double sigma);
density_integral parse_density_integral_string(char *input, char *variablename);

View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include "pqueue.h"
#include "iqueue.h"
//http://www.koders.com/c/fid7B82D8DDECE4EDC672F17D970458033C4079A615.aspx?s=queue
#define INT_VALUE 1000
//typedef int (*ComparisonFunction)(void*, void*);
int compare_int (const int *a, const int *b)
{
fprintf(stderr,"comparing %i %i \n",*a,*b);
int temp = *a - *b;
// return (a<b) ? 1 : -1;
// return -1;
if (temp < 0)
return 1;
else if (temp > 0)
return -1;
else
return 0;
}
int main (int argc, char* argv[]) {
int val1 = 1;
int val2 = 2;
int val3 = 3;
int val4 = 4;
Queue q = QueueNew();
QueuePutOnPriority(q, &val1, INT_VALUE,(ComparisonFunction)compare_int);
QueuePutOnPriority(q, &val3, INT_VALUE,(ComparisonFunction)compare_int);
QueuePutOnPriority(q, &val2, INT_VALUE,(ComparisonFunction)compare_int);
QueuePutOnPriority(q, &val4, INT_VALUE,(ComparisonFunction)compare_int);
QueueItem qptr = q->head;
while (qptr != NULL) {
int* val = (int*) qptr->element;
printf("value: %d\n", *val);
qptr = qptr->next;
}
QueueIterator qiter = QueueIteratorNew(q, 1);
while (qiter->currentItem != NULL) {
int* val = (int*) qiter->currentItem->element;
printf("iterator value: %d\n", *val);
QueueIteratorAdvance(qiter);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,339 @@
/******************************************************************************\
* *
* SimpleCUDD library (www.cs.kuleuven.be/~theo/tools/simplecudd.html) *
* SimpleCUDD was developed at Katholieke Universiteit Leuven(www.kuleuven.be) *
* *
* Copyright Katholieke Universiteit Leuven 2008 *
* *
* Author: Theofrastos Mantadelis *
* File: simplecudd.h *
* *
********************************************************************************
* *
* Artistic License 2.0 *
* *
* Copyright (c) 2000-2006, The Perl Foundation. *
* *
* Everyone is permitted to copy and distribute verbatim copies of this license *
* document, but changing it is not allowed. *
* *
* Preamble *
* *
* This license establishes the terms under which a given free software Package *
* may be copied, modified, distributed, and/or redistributed. The intent is *
* that the Copyright Holder maintains some artistic control over the *
* development of that Package while still keeping the Package available as *
* open source and free software. *
* *
* You are always permitted to make arrangements wholly outside of this license *
* directly with the Copyright Holder of a given Package. If the terms of this *
* license do not permit the full use that you propose to make of the Package, *
* you should contact the Copyright Holder and seek a different licensing *
* arrangement. *
* Definitions *
* *
* "Copyright Holder" means the individual(s) or organization(s) named in the *
* copyright notice for the entire Package. *
* *
* "Contributor" means any party that has contributed code or other material to *
* the Package, in accordance with the Copyright Holder's procedures. *
* *
* "You" and "your" means any person who would like to copy, distribute, or *
* modify the Package. *
* *
* "Package" means the collection of files distributed by the Copyright Holder, *
* and derivatives of that collection and/or of those files. A given Package *
* may consist of either the Standard Version, or a Modified Version. *
* *
* "Distribute" means providing a copy of the Package or making it accessible *
* to anyone else, or in the case of a company or organization, to others *
* outside of your company or organization. *
* *
* "Distributor Fee" means any fee that you charge for Distributing this *
* Package or providing support for this Package to another party. It does not *
* mean licensing fees. *
* *
* "Standard Version" refers to the Package if it has not been modified, or has *
* been modified only in ways explicitly requested by the Copyright Holder. *
* *
* "Modified Version" means the Package, if it has been changed, and such *
* changes were not explicitly requested by the Copyright Holder. *
* *
* "Original License" means this Artistic License as Distributed with the *
* Standard Version of the Package, in its current version or as it may be *
* modified by The Perl Foundation in the future. *
* *
* "Source" form means the source code, documentation source, and configuration *
* files for the Package. *
* *
* "Compiled" form means the compiled bytecode, object code, binary, or any *
* other form resulting from mechanical transformation or translation of the *
* Source form. *
* Permission for Use and Modification Without Distribution *
* *
* (1) You are permitted to use the Standard Version and create and use *
* Modified Versions for any purpose without restriction, provided that you do *
* not Distribute the Modified Version. *
* Permissions for Redistribution of the Standard Version *
* *
* (2) You may Distribute verbatim copies of the Source form of the Standard *
* Version of this Package in any medium without restriction, either gratis or *
* for a Distributor Fee, provided that you duplicate all of the original *
* copyright notices and associated disclaimers. At your discretion, such *
* verbatim copies may or may not include a Compiled form of the Package. *
* *
* (3) You may apply any bug fixes, portability changes, and other *
* modifications made available from the Copyright Holder. The resulting *
* Package will still be considered the Standard Version, and as such will be *
* subject to the Original License. *
* Distribution of Modified Versions of the Package as Source *
* *
* (4) You may Distribute your Modified Version as Source (either gratis or for *
* a Distributor Fee, and with or without a Compiled form of the Modified *
* Version) provided that you clearly document how it differs from the Standard *
* Version, including, but not limited to, documenting any non-standard *
* features, executables, or modules, and provided that you do at least ONE of *
* the following: *
* *
* (a) make the Modified Version available to the Copyright Holder of the *
* Standard Version, under the Original License, so that the Copyright Holder *
* may include your modifications in the Standard Version. *
* (b) ensure that installation of your Modified Version does not prevent the *
* user installing or running the Standard Version. In addition, the Modified *
* Version must bear a name that is different from the name of the Standard *
* Version. *
* (c) allow anyone who receives a copy of the Modified Version to make the *
* Source form of the Modified Version available to others under *
* (i) the Original License or *
* (ii) a license that permits the licensee to freely copy, modify and *
* redistribute the Modified Version using the same licensing terms that apply *
* to the copy that the licensee received, and requires that the Source form of *
* the Modified Version, and of any works derived from it, be made freely *
* available in that license fees are prohibited but Distributor Fees are *
* allowed. *
* Distribution of Compiled Forms of the Standard Version or Modified Versions *
* without the Source *
* *
* (5) You may Distribute Compiled forms of the Standard Version without the *
* Source, provided that you include complete instructions on how to get the *
* Source of the Standard Version. Such instructions must be valid at the time *
* of your distribution. If these instructions, at any time while you are *
* carrying out such distribution, become invalid, you must provide new *
* instructions on demand or cease further distribution. If you provide valid *
* instructions or cease distribution within thirty days after you become aware *
* that the instructions are invalid, then you do not forfeit any of your *
* rights under this license. *
* *
* (6) You may Distribute a Modified Version in Compiled form without the *
* Source, provided that you comply with Section 4 with respect to the Source *
* of the Modified Version. *
* Aggregating or Linking the Package *
* *
* (7) You may aggregate the Package (either the Standard Version or Modified *
* Version) with other packages and Distribute the resulting aggregation *
* provided that you do not charge a licensing fee for the Package. Distributor *
* Fees are permitted, and licensing fees for other components in the *
* aggregation are permitted. The terms of this license apply to the use and *
* Distribution of the Standard or Modified Versions as included in the *
* aggregation. *
* *
* (8) You are permitted to link Modified and Standard Versions with other *
* works, to embed the Package in a larger work of your own, or to build *
* stand-alone binary or bytecode versions of applications that include the *
* Package, and Distribute the result without restriction, provided the result *
* does not expose a direct interface to the Package. *
* Items That are Not Considered Part of a Modified Version *
* *
* (9) Works (including, but not limited to, modules and scripts) that merely *
* extend or make use of the Package, do not, by themselves, cause the Package *
* to be a Modified Version. In addition, such works are not considered parts *
* of the Package itself, and are not subject to the terms of this license. *
* General Provisions *
* *
* (10) Any use, modification, and distribution of the Standard or Modified *
* Versions is governed by this Artistic License. By using, modifying or *
* distributing the Package, you accept this license. Do not use, modify, or *
* distribute the Package, if you do not accept this license. *
* *
* (11) If your Modified Version has been derived from a Modified Version made *
* by someone other than you, you are nevertheless required to ensure that your *
* Modified Version complies with the requirements of this license. *
* *
* (12) This license does not grant you the right to use any trademark, service *
* mark, tradename, or logo of the Copyright Holder. *
* *
* (13) This license includes the non-exclusive, worldwide, free-of-charge *
* patent license to make, have made, use, offer to sell, sell, import and *
* otherwise transfer the Package with respect to any patent claims licensable *
* by the Copyright Holder that are necessarily infringed by the Package. If *
* you institute patent litigation (including a cross-claim or counterclaim) *
* against any party alleging that the Package constitutes direct or *
* contributory patent infringement, then this Artistic License to you shall *
* terminate on the date that such litigation is filed. *
* *
* (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER *
* AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR *
* NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. *
* UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN *
* ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
* *
* The End *
* *
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "pqueue.h"
#include "util.h"
#include "cudd.h"
#include "cuddInt.h"
#include "general.h"
#define IsHigh(manager, node) HIGH(manager) == node
#define IsLow(manager, node) LOW(manager) == node
#define HIGH(manager) Cudd_ReadOne(manager)
#define LOW(manager) Cudd_Not(Cudd_ReadOne(manager))
#define NOT(node) Cudd_Not(node)
#define GetIndex(node) Cudd_NodeReadIndex(node)
#define GetOrder(manager, node) Cudd_ReadPerm(manager, GetIndex(node))
#define GetVar(manager, index) Cudd_bddIthVar(manager, index)
#define NewVar(manager) Cudd_bddNewVar(manager)
#define KillBDD(manager) Cudd_Quit(manager)
#define GetVarCount(manager) Cudd_ReadSize(manager)
#define DEBUGON _debug = 1
#define DEBUGOFF _debug = 0
#define RAPIDLOADON _RapidLoad = 1
#define RAPIDLOADOFF _RapidLoad = 0
#define SETMAXBUFSIZE(size) _maxbufsize = size
#define BDDFILE_ERROR -1
#define BDDFILE_OTHER 0
#define BDDFILE_SCRIPT 1
#define BDDFILE_NODEDUMP 2
extern int _RapidLoad;
extern int _debug;
extern int _maxbufsize;
typedef struct _bddfileheader {
FILE *inputfile;
int version;
int varcnt;
int varstart;
int intercnt;
int filetype;
} bddfileheader;
typedef struct _namedvars {
int varcnt;
int varstart;
char **vars;
int *loaded;
double *dvalue;
int *ivalue;
void **dynvalue;
} namedvars;
/** Custom struct to store a DdNode with assigned values */
/** semantics of values depends on algorithm used */
typedef struct _hisnode {
DdNode *key;
double dvalue;
double dvalue2;// =0; //needed for expected counts
int ivalue;
void *dynvalue;
} hisnode;
typedef struct _hisqueue {
int cnt;
hisnode *thenode;
} hisqueue;
typedef struct _nodeline {
char *varname;
char *truevar;
char *falsevar;
int nodenum;
int truenode;
int falsenode;
} nodeline;
/* Initialization */
DdManager* simpleBDDinit(int varcnt);
/* BDD Generation */
DdNode* D_BDDAnd(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* D_BDDNand(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* D_BDDOr(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* D_BDDNor(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* D_BDDXor(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* D_BDDXnor(DdManager *manager, DdNode *bdd1, DdNode *bdd2);
DdNode* FileGenerateBDD(DdManager *manager, namedvars varmap, bddfileheader fileheader);
DdNode** FileGenerateBDDForest(DdManager *manager, namedvars varmap, bddfileheader fileheader);
DdNode* OnlineGenerateBDD(DdManager *manager, namedvars *varmap);
DdNode* LineParser(DdManager *manager, namedvars varmap, DdNode **inter, int maxinter, char *function, int iline);
DdNode* OnlineLineParser(DdManager *manager, namedvars *varmap, DdNode **inter, int maxinter, char *function, int iline);
DdNode* BDD_Operator(DdManager *manager, DdNode *bdd1, DdNode *bdd2, char Operator, int inegoper);
int getInterBDD(char *function);
char* getFileName(const char *function);
int GetParam(char *inputline, int iParam);
char** GetVariableOrder(char *filename, int varcnt);
int LoadVariableData(namedvars varmap, char *filename);
/* Named variables */
int ImposeOrder(DdManager *manager, const namedvars varmap, char **map);
int get_var_pos_in_map(char **map, const char *var, int varcnt);
namedvars InitNamedVars(int varcnt, int varstart);
void EnlargeNamedVars(namedvars *varmap, int newvarcnt);
int AddNamedVarAt(namedvars varmap, const char *varname, int index);
int AddNamedVar(namedvars varmap, const char *varname);
void SetNamedVarValuesAt(namedvars varmap, int index, double dvalue, int ivalue, void *dynvalue);
int SetNamedVarValues(namedvars varmap, const char *varname, double dvalue, int ivalue, void *dynvalue);
int GetNamedVarIndex(const namedvars varmap, const char *varname);
int RepairVarcnt(namedvars *varmap);
char* GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node);
char* GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node);
int all_loaded(namedvars varmap, int disp);
/* Traversal */
DdNode* HighNodeOf(DdManager *manager, DdNode *node);
DdNode* LowNodeOf(DdManager *manager, DdNode *node);
/* Traversal - History */
hisqueue* InitHistory(int varcnt);
void ReInitHistory(hisqueue *HisQueue, int varcnt);
void AddNode(hisqueue *HisQueue, int varstart, DdNode *node, double dvalue, int ivalue, void *dynvalue);
hisnode* GetNode(hisqueue *HisQueue, int varstart, DdNode *node);
int GetNodeIndex(hisqueue *HisQueue, int varstart, DdNode *node);
void onlinetraverse(DdManager *manager, namedvars varmap, hisqueue *HisQueue, DdNode *bdd);
/* Save-load */
bddfileheader ReadFileHeader(char *filename);
int CheckFileVersion(const char *version);
DdNode * LoadNodeDump(DdManager *manager, namedvars varmap, FILE *inputfile);
DdNode * LoadNodeRec(DdManager *manager, namedvars varmap, hisqueue *Nodes, FILE *inputfile, nodeline current);
DdNode * GetIfExists(DdManager *manager, namedvars varmap, hisqueue *Nodes, char *varname, int nodenum);
int SaveNodeDump(DdManager *manager, namedvars varmap, DdNode *bdd, char *filename);
void SaveExpand(DdManager *manager, namedvars varmap, hisqueue *Nodes, DdNode *Current, FILE *outputfile);
void ExpandNodes(hisqueue *Nodes, int index, int nodenum);
/* Export */
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename);
int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd, char *filename);