Customer Banners (Ads) - SpiceUp. AX and SpotfireX Disclaimer



If you find this site useful and you want to support, buy me a coffee   to keep this site alive and without ads.

extract csv data from visualization

#get list of filtered rows
dataTable = Document.ActiveDataTableReference
rows = Document.ActiveFilteringSelectionReference.GetSelection(dataTable).AsIndexSet()

#Script configuration
delim = ","
rowDelim = "\n"
docProperty = "myDocProperty"

#generate CSV
csv = ""
for column in dataTable.Columns:
   csv += column.Name + delim

csv += rowDelim

for r in rows:
   for column in dataTable.Columns:
      csv += column.RowValues.GetFormattedValue(r) + delim
   csv+=rowDelim

#show results
print csv

Get visible rows from active visualization

myTable = Document.ActiveDataTableReference

for row in Document.ActiveFilteringSelectionReference.GetSelection(myTable).AsIndexSet():
   print row

Popup Calendar (WebPlayer compatible)


Update!


It is now easier and almost out of the box to use different date picker for date, time or even date-time by using the power of HTML5.  No jquery or other libraries needed






html
date:<span class="date">
   <SpotfireControl id="Spotfire Date Input Property Control" /> 
  </span> (use M/d/yyyy formatting to have it work properly)


 Time: <span class="time">
   <SpotfireControl id="Spotfire Time Input Property Control" />
 </span> (use this formatting: hh:mm:ss)


 Datetime:<span class="datetime">
   <SpotfireControl id="Spotfire DateTime Input Property Control" />
 </span> (use this formatting: yyyy-MM-ddThh:mm

js
[...document.querySelectorAll(".date input")].map(x => x.type="date");
[...document.querySelectorAll(".time input")].map(x => x.type="time");
[...document.querySelectorAll(".datetime input")].map(x => x.type="datetime-local");

The above script will apply the proper type attribute value to each html5 input


For the date pickers to hold the selected value, the Property Controls must be formatted accordingly. 

DataTypeFormat 
Dateyyyy-MM-dd 
TimeHH:mm 
DateTimeyyyy-MM-ddTHH:mm

Old-way


Ingredients
  • Spotfire 6.0 to Spotfire 11.4
  • TextArea
  • Input Field Property Control
  • Javascript script





Preparation
  1. Add a TextArea and right click to edit the HTML
  2. Add an Input Field Property Control wrapped by a tag with id='dt1' 
  3. Add a span html tag with id='dt1picker' next to your SpotfireControl for the calendar 
  4. Add javascript

HTML:
<span id='dt1'>
   <SpotfireControl id="ed353..YourSInputPropControl" />
</span>
<span id='dt1picker'></span>

JS:
//update document property after selection
function datePicker_onSelect(selectedDate){
 //alert(selectedDate)
 $("#dt1 input").focus()
$("#dt1 input").blur()
}

//jquery datepicker configuration
//you can comment the buttonImageOnly and buttonImage lines to show a button instead of a calendar or the image of your choice.
pickerOptions = {
 showOn: 'button', 
 buttonImageOnly: true, 
 buttonImage: 'http://staff.washington.edu/tabrooks/343INFO/UnobtrusiveDatePicker/cal-grey.gif', 
 minDate: "-36M", maxDate: "+0D",
 changeMonth: true,
 changeYear: true,
 altField:"#dt1 input",
 onSelect:datePicker_onSelect
 }

//create the date picker
document.getElementById('dt1picker').innerHTML="<input type='hidden' id='datePicker'>"
$("#datePicker").datepicker(pickerOptions);



Refer to the jquery datepicker documentation for configuration options

Popup Calendar

import clr
clr.AddReference('System.Windows.Forms')

from System.Windows.Forms import Form, MonthCalendar

#create a calendar
calendar = MonthCalendar()

#define what to do with the selected date
def onPickDate(sender,eventArgs):
selectedDate = calendar.SelectionRange.Start.ToShortDateString()
print selectedDate
Document.Properties["selectedDate"] = selectedDate

calendar.DateSelected += onPickDate

#put calendar in a form and show it
form = Form()
form.Text = "Select a date and close the form when done"
form.Controls.Add(calendar)
form.ShowDialog()

FittingModel (SF 6.0+)

# -------------------------------------------------------------------------
# Script to get the model of the logistic curve fitting
# and update a table 'Model Parameters' with it
# -------------------------------------------------------------------------

import math
from Spotfire.Dxp.Application.Visuals import VisualContent
from Spotfire.Dxp.Application.Visuals.FittingModels import FittingModelTypeIdentifiers,LogisticRegressionFittingModel

viz=visual.As[VisualContent]()
for fm in viz.FittingModels:
if fm.TypeId==FittingModelTypeIdentifiers.LogisticRegressionFittingModel:
  ds = fm.GetResultsDataSource()
  if Document.Data.Tables.Contains("Model Parameters"):
  #Replace data if table exists    table=Document.Data.Tables["Model Parameters"]
    table.ReplaceData(ds)
  else:
  #Create table if doesn't exists    Document.Data.Tables.Add("Model Parameters", ds)

# call the script yo update the Y calculationfrom System.Collections.Generic import Dictionary
from Spotfire.Dxp.Application.Scripting import ScriptDefinition
import clr

scriptDef = clr.Reference[ScriptDefinition]()
Document.ScriptManager.TryGetScript("UpdateCalcY", scriptDef)
paramDict = {"visual":visual}
params = Dictionary[str, object](paramDict)
Document.ScriptManager.ExecuteScript(scriptDef.ScriptCode, params)


# -----------------------------------------------------------------------------------------------------------------------
# Script to recalculate the Y value corresponding to the X value in property SelectedX
# using the parameters in table 'Model Parameters', created by the other script
# -----------------------------------------------------------------------------------------------------------------------

import math
from Spotfire.Dxp.Application.Visuals import VisualContent
from Spotfire.Dxp.Application.Visuals.FittingModels import FittingModelTypeIdentifiers,LogisticRegressionFittingModel
from Spotfire.Dxp.Data import DataValueCursor

viz=visual.As[VisualContent]()
x=Document.Properties['SelectedX']
if Document.Data.Tables.Contains("Model Parameters"):
  table=Document.Data.Tables["Model Parameters"]
  minCol=table.Columns['min']
  minCursor=DataValueCursor.Create[float](minCol)
  maxCol=table.Columns['max']
  maxCursor=DataValueCursor.Create[float](maxCol)
  hillCol=table.Columns['Hill']
  hillCursor=DataValueCursor.Create[float](hillCol)
  lX50Col=table.Columns['LoggedX50']
  lX50Cursor=DataValueCursor.Create[float](lX50Col)
  for row in table.GetRows(minCursor,maxCursor,hillCursor,lX50Cursor):
    y=minCursor.CurrentValue+((maxCursor.CurrentValue-minCursor.CurrentValue)/(1.00+math.pow(10,hillCursor.CurrentValue*(lX50Cursor.CurrentValue-x))))
    Document.Properties['CalcY']=y
    break;

sending emails with attachments (from gmail or corporation)

# This script gets the unique values from a column and sends an email
from Spotfire.Dxp.Application.Filters import CheckBoxFilter 
from System import IO, Net, DateTime
from System.Net import Mail, Mime
from System.Text import Encoding

#A) CONFIG THE SCRIPT OPTIONS
#A.1 Unique column values from table to export
myTable = Document.Data.Tables["A"]
myColumn = "Item"

#A.2 Email configuration 
#gmail settings    : smtp.gmail.com,  port:587 encription=True credentials=True)
#corporate settings: smtp.contoso.com,port:25  encription=False credentials=False)
SMTPClient = "smtp.gmail.com"
SMTPPort = 587
useEncription = True
useCredentials = True

fromEmail = "me@gmail.com"
toEmail ="someone@abc.com"
fromEmailUsr = fromEmail
fromEmailPwd = "secretpassword"
filename = "myAttachment" + DateTime.Now.ToString() + ".csv"
myMailSubject = "Unique Values from " + myTable.Name + "." + myColumn
myMailBody = "These are the " + myMailSubject + "sent by some Spotfire geek"

#B) EXTRACT DATA for attachment
#B.1 Get uniques from myTable
s="Magic Numbers\r\n" 
filt=Document.FilteringSchemes[0].Item[myTable].Item[myTable.Columns.Item[myColumn]].As[CheckBoxFilter]()
for value in filt.Values: s+=value


#B.2 encode results
ms = IO.MemoryStream(Encoding.UTF8.GetBytes(s))

#C) SEND MAIL
#C.1 go by a postcard or envelope
MyMailMessage = Mail.MailMessage()


#C.2 Prepare email
MyMailMessage.From = Mail.MailAddress(fromEmail)
MyMailMessage.To.Add(toEmail)
MyMailMessage.Subject = myMailSubject
MyMailMessage.Body = myMailBody
ct = Mime.ContentType(Mime.MediaTypeNames.Text.Plain); 
attach = Mail.Attachment(ms, ct) 
attach.ContentDisposition.FileName = filename 
MyMailMessage.Attachments.Add(attach)
Mail.Attachment(ms, ct)

#C.3 Go to the USPS post office (Create the SMTPClient object and specify the SMTP GMail server and port)
SMTPServer = Mail.SmtpClient(SMTPClient)
SMTPServer.Port = SMTPPort

#C.4 Drop the email in the USPS outbox with the appropiate postage
if useCredentials: SMTPServer.Credentials = Net.NetworkCredential(fromEmailUsr, fromEmailPwd)
SMTPServer.EnableSsl = useEncription
print "thanks for using USPS service"
SMTPServer.Send(MyMailMessage)


Replace Data Tables from a file (client only)

# Replace tables from file
from System.Windows.Forms import OpenFileDialog
from Spotfire.Dxp.Data import *
import clr
clr.AddReference("System.Windows.Forms")


#get filename from file chooser
d1 = OpenFileDialog()
d1.InitialDirectory='C:\myfiles\salesdata'
d1.ShowDialog()


#setup data source from selected file
myDataManager = Document.Data
ds=myDataManager.CreateFileDataSource(d1.FileName)


#replace myTable 
myTable = Document.Data.Tables["T1"] #or use a DataTable script parameter
myTable.ReplaceData(ds)

Get user information, login name, machine version, etc

from System import Environment

print "Machine Name:\t", Environment.MachineName
print "User:\t\t", Environment.UserName
print "Domain:\t\t", Environment.UserDomainName
print "Drives:\t\t", Environment.GetLogicalDrives()
print "Directory:\t\t", Environment.SystemDirectory
print "OS:\t\t",Environment.OSVersion, " (64 bit)" if Environment.Is64BitOperatingSystem else " (32 bit)"
print "Spotfire Exe:\t", Environment.CommandLine, " (64 bits)" if Environment.Is64BitProcess else " (32 bits?)"
print "Special Path:\t",Environment.ExpandEnvironmentVariables("%SystemRoot%\\a\\b\\c")
print "Temp Directory:\t", Environment.GetEnvironmentVariable("TEMP")
print "System folder:\t", Environment.GetFolderPath(Environment.SpecialFolder.System)

#username from webplayer or client
from System.Threading import Thread

print(Thread.CurrentPrincipal.Identity.Name )

Alert, Popup, MessageBox

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Foo") 


"Sort axis by" on a combination chart

Assuming you have a combination chart with 'colA' and 'colB; columns, you can sort by 'colA', 'colB' or 'none'

from Spotfire.Dxp.Application.Visuals import CategoryKey
from Spotfire.Dxp.Application.Visuals import CombinationChart

#Define sorting typesmyCategoryKey0=CategoryKey() #Same as 'None'
myCategoryKey1=CategoryKey("Sum(ColA)")
myCategoryKey2=CategoryKey("Sum(ColB)")

#Perform sorting

vis.As[CombinationChart]().SortBy=myCategoryKey1

Control XY Axis zoom scale

  1. Create a document property called 'mySlider' as integer type
  2. Add a text area and add a Property Control and link it to 'mySlider' to it.
  3. Use the script button on the slider widget if available. Otherwise use an Action Control to triger the script once happy with the slider value selection.

from Spotfire.Dxp.Application.Visuals import AxisRange
from Spotfire.Dxp.Application.Visuals import BarChart
#from Spotfire.Dxp.Data import DataPropertyClass

#viz is a scirpt parameter pointing to a barchart visual

MyChart = viz.As[BarChart]()

#read min,max from document properties

min = Document.Properties["mySlider"].Value
#max = Document.Data.Properties.GetProperty(DataPropertyClass.Document, "mySlider").Value

#apply zoom range

MyChart.YAxis.ManualZoom = True
MyChart.YAxis.ZoomRange = AxisRange(min,max);

cascading dropdowns

1. Create a drop-down list Property Control to display unique values from the Region column.

2 Create a Calculated Column called ‘Filtered State’. In the expression we should check if the Region Column value equals the value specified in the property we created earlier. If it does, it will output the value from the State Column.

if ([Region] = "${whichRegion}",[State],null)

Next step is to create the second Property Control drop-down. This one will display unique values in the newly created Filtered State Column.
The final step is to create a second Calculated Column called ‘Filtered City’. In the expression we should check if the State Column value equals the value specified in the property we just created. If it does, it will output the value from the City Column.

if ([State] = "${whichState}",[City],null)

Note: If your want to select multiple values and your document property is associated with a multiple selection listbox, then use the following expression:

if ([State] in ($map("'${whichState}'", ",")) ,[City],null)