#!/usr/bin/env perl
#!/usr/bin/perl -w
#
# Read an SQLite database file containing an fea model and plot
# non-zeros before and after renumbering.
# Albert Danial Nov 15 2003
#
use strict;
use Getopt::Std;
use vars qw ( $opt_l $opt_k );
use DBI;
use DBD::SQLite 1.00;
getopts('lk');

my $XGRAPHIC = "xgraphic"; # or supply full path if this isn't in $PATH

die "$0 [-lk] <.db file>

              Plots the incidence matrix before and after renumbering.
              Hit Q from within xgraphic to go from the before image
              to the after image, and Q a second time to quit.

	      -l   Only show lower half of the matrix.
	      -k   Keep the index file used to create the plot.
" unless @ARGV;

my $db_file       = shift @ARGV;
die "Expecting .db file to have a .db extenstion (got $db_file)\n"
    unless $db_file =~ /\.db$/i;

my $dbh = DBI->connect("dbi:SQLite:dbname=$db_file","","");
my $raa_connect = $dbh->selectall_arrayref(
                        "select nid_a,nid_b from node_connectivity");
my $rhh_new_id  = $dbh->selectall_hashref(
                        "select orig_id,new_id from renumbered_nid", 'orig_id');
my $st  = $dbh->disconnect;

my $N        = 0;  # the number of nodes in the model
my $tmp_file = "j.xy";

# Original ordering.
open  OUT, ">$tmp_file" or die "Cannot write to $tmp_file  $!\n";
foreach my $pair (@{$raa_connect}) {
    $N = $pair->[0] if $N < $pair->[0];
    next if $opt_l and ($pair->[0] > $pair->[1]);
    printf OUT "% 3d % 3d\n", $pair->[0], -$pair->[1];
}
# add the diagonal terms
for (my $i = 1; $i <= $N; $i++) { print OUT " $i -$i\n"; }
close OUT;
my $range = sprintf "-xmin=-%.1f -xmax=%.1f -ymin=-%.1f -ymax=%.1f",
                    0.311*($N+1), 1.689*($N+1), 1.066*($N+1), 0.077*($N+1);
print "R=$range\n";
system "$XGRAPHIC $range -scat $tmp_file";

# use Data::Dumper; print Dumper($rhh_new_id);

# Renumbered.
open  OUT, ">$tmp_file" or die "Cannot write to $tmp_file  $!\n";
foreach my $pair (@{$raa_connect}) {
    next if $opt_l and ($rhh_new_id->{ $pair->[0] }{new_id} > 
                        $rhh_new_id->{ $pair->[1] }{new_id});
    printf OUT "% 3d % 3d\n", $rhh_new_id->{ $pair->[0] }{new_id}, 
                             -$rhh_new_id->{ $pair->[1] }{new_id};
}

# The following query will produce the same data minus the diagonal term:
#
# select R1.new_id, R2.new_id from node_connectivity C  ,
#                                  renumbered_nid    R1 ,
#                                  renumbered_nid    R2
#    where  R1.orig_id  =  C.nid_a and
#           R2.orig_id  =  C.nid_b and
#           R1.new_id  <=  R2.new_id
#    order by R1.new_id, R2.new_id;
#

# add the diagonal terms
for (my $i = 1; $i <= $N; $i++) { print OUT " $i -$i\n"; }
close OUT;
system "$XGRAPHIC $range -scat $tmp_file";

unlink $tmp_file unless $opt_k;
