Exemple #1
0
    def __init__(self, name, **kwargs):
        # print("INIT:%s" % name)
        self._width = kwargs.get('width', 'auto')
        self._cb = kwargs.get('cb')
        self._desc = kwargs.get('desc', '')
        self.default = self.dd.value
        self.disabled = kwargs.get('disabled', False)
        units = kwargs.get('units')
        self.units = self.find_unit(units)
        self.valid = widgets.Valid(value=True,
                                   layout=widgets.Layout(flex='0 1 0'))
        try:
            self.dd.on_submit(lambda x: self.cb(None))
        except:
            pass
        self.dd.observe(lambda x: self.cb(x['new']), names='value')
        self.oldval = None
        self.no_cb = False
        self.name = name

        self._min = kwargs.get('min')
        self._max = kwargs.get('max')
        if self._min is not None:
            self._min = self.type(self.parse_expr(self._min, True))
        if self._max is not None:
            self._max = self.type(self.parse_expr(self._max, True))

        self._build()
 def setup(self):
     cluster_info = self._get_cluster_info()
     if not self.kubeconfig:
         print(cluster_info)
         return ipywidgets.Valid(
             value=True,
             description='Use existing service account.',
             style={'description_width': 'auto'},
             layout=ipywidgets.Layout(width='100%'))
     temp = tempfile.NamedTemporaryFile(delete=False)
     temp.write(bytearray(self.kubeconfig.value, 'utf-8'))
     temp.close()
     os.environ['KUBECONFIG'] = temp.name
     if not cluster_info:
         return ipywidgets.Valid(value=False, description='kubeconfig')
     print(cluster_info)
     return ipywidgets.Valid(value=True, description='kubeconfig')
Exemple #3
0
 def _click_function(_):
     with output:
         timesketch_set_active_sketch_func(str(sketch_field.value))
         sketch = timesketch_get_sketch_func()
         try:
             display(
                 Markdown(
                     f'Connected to sketch: {sketch.id}: **{sketch.name}**')
             )
             valid = widgets.Valid(value=True, description='Connected')
             display(valid)
             utils.ipython_bind_global('sketch', sketch)
             display(Markdown('Sketch object saved to **sketch**'))
         except KeyError:
             display(Markdown('**Unable to connect to sketch.**'))
             invalid = widgets.Valid(value=False, description='Connected')
             display(invalid)
    def __init__(self, turbine_id=0, raw_data=None):
        if raw_data is None or len(raw_data) == 0:
            raise Exception(
                "You need to pass an array with at least one row for raw data")

        self.turbine_id = turbine_id  # id of the turbine
        self.raw_data = raw_data  # buffer with the raw sensors data
        self.raw_data_idx = random.randint(0, len(raw_data) - 1)

        self.running = False  # running status

        self.halted = False  # if True you can't use this turbine anymore. create a new one.

        # components of the UI
        self.stopped_img = open('imgs/wind_turbine.png', 'rb').read()
        self.running_img = open('imgs/wind_turbine.gif', 'rb').read()
        self.button = widgets.Button(description='Start (Id: %d)' %
                                     self.turbine_id)
        self.button.on_click(self.__on_button_clicked)

        self.img = widgets.Image(value=self.stopped_img, width=150, height=170)
        self.status_label = widgets.Label(layout={'width': "150px"}, value='')

        self.vibration_status = widgets.Valid(value=False,
                                              description='Vibration')
        self.voltage_status = widgets.Valid(value=False, description='Voltage')
        self.rotation_status = widgets.Valid(value=False,
                                             description='Rotation')

        self.noise_buttons = [
            widgets.Button(description='Volt', layout={'width': '50px'}),
            widgets.Button(description='Rot', layout={'width': '50px'}),
            widgets.Button(description='Vib', layout={'width': '50px'})
        ]
        for i in self.noise_buttons:
            i.on_click(self.__on_noise_button_clicked)
        self.anomaly_status = widgets.VBox([
            self.vibration_status, self.voltage_status, self.rotation_status,
            widgets.Label("Inject noise"),
            widgets.HBox(self.noise_buttons)
        ],
                                           layout={'visibility': 'hidden'})
def getCredentials():
    from oauth2client import file
    import httplib2
    import ipywidgets as widgets
    print("Getting the credentials from file...")
    storage = file.Storage("oauth2.dat")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        print('❗')
        display(
            widgets.Valid(value=False,
                          description='Credentials are ',
                          disabled=False))
        display(
            widgets.HTML(
                'go create a credential valid file here: <a target="_blank" href="cloud.google.auth.ipynb.ipynb">gcloud authorization notebook</a> and try again'
            ))
    else:
        http_auth = credentials.authorize(httplib2.Http())
        print('✅ Ok')
        return credentials
    def create(self):
        default_layout = widgets.Layout(width='500px')
        self.wg['url'] = widgets.Text(value='',
                                      description='URL: ',
                                      layout=default_layout)
        self.wg['update_url'] = widgets.Button(description='Update')
        self.wg['request_status'] = widgets.Valid(layout=default_layout)
        self.wg['search_filter'] = widgets.Text(value='',
                                                placeholder='Must contain',
                                                description='Filter',
                                                layout=default_layout)
        self.wg['dropdown'] = widgets.Dropdown(description='Select',
                                               layout=default_layout)
        self.wg['num_results'] = widgets.Label()

        self.wg['update_interval'] = widgets.IntSlider(value=10,
                                                       min=1,
                                                       max=60,
                                                       step=1,
                                                       layout=default_layout,
                                                       continuous_update=True)
        self.wg['interrupt_button'] = widgets.Button(description='Interrupt',
                                                     disabled=True)
        self.wg['resume_button'] = widgets.Button(description='Resume')
##############################################
##############################################
##############################################

defaultloc = 'chr5:142,903,034-142,906,867'
defaultgeneid = 'Actb'
defaultrefseqid = 'NM_007393'
defaultstrand = "-"

#### Accordian Change File Locations ####
w_default_folder = widgets.Text(
    description='RnaSeq Folder',
    value=default_track_folder,
)
w_default_folder.width = "80%"
w_default_folder_valid = widgets.Valid(value=True)
hboxdefaultfolder = widgets.HBox([w_default_folder, w_default_folder_valid])
page1 = widgets.VBox(children=[hboxdefaultfolder])

accord = widgets.Accordion(children=[page1], width="80%")
display(accord)

accord.set_title(0, 'Defaults')

#### Define Widgets ###
lookuptype_widget = widgets.RadioButtons(options={
    'By location': 'location',
    'By geneid (3\'UTR only)': "geneid"
},
                                         value='location',
                                         description='Lookup:',
# Boolean widgets
ToggleButton
widgets.ToggleButton(
    value=False,
    description='Click me',
    disabled=False,
    button_style='',  # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Description',
    icon='check')

# Checkbox
widgets.Checkbox(value=False, description='Check me', disabled=False)

# Valid
widgets.Valid(
    value=False,
    description='Valid!',
)

# Selection widgets
# Dropdown
widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Number:',
    disabled=False,
)

widgets.Dropdown(
    options={
        'One': 1,
        'Two': 2,
Exemple #9
0
widgets.ToggleButton(
    description='Click me',
    value=False,
)

# In[9]:

widgets.Checkbox(
    description='Check me',
    value=True,
)

# In[10]:

widgets.Valid(value=True, )

# In[11]:

# selection widgets
# dropdown
from IPython.display import display

w = widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Number:',
)
display(w)

# In[13]:
Exemple #10
0
def make_valid(value, description, readout):

    widg = widgets.Valid(value=value, description=description, readout=readout)

    return widg
Exemple #11
0
    def __init__(self, **kwargs):

        # Enable manual setting of the pseudopotential family
        self.set_pseudo_family_prompt = ipw.HTML("<b>&nbsp;&nbsp;Override&nbsp;</b>")
        self.set_pseudo_family = ipw.Checkbox(
            description="",
            indent=False,
            value=False,
            layout=ipw.Layout(max_width="10%"),
        )
        self.set_pseudo_family_box = ipw.HBox(
            [self.set_pseudo_family_prompt, self.set_pseudo_family],
            layout=ipw.Layout(max_width="20%"),
        )
        self.show_ui = ipw.Valid(value=True)
        self.set_pseudo_family.observe(self.set_show_ui, "value")
        self.set_pseudo_family.observe(self.set_text_color, "value")
        self.set_pseudo_family.observe(self.set_value_trait, "value")

        # Choose the DFT functional
        self.dft_functional = ipw.Dropdown(
            options=["PBE", "PBEsol"],
            value=DEFAULT_PARAMETERS["pseudo_family"].split("/")[2],
            style={"description_width": "initial"},
        )
        self.dft_functional.observe(self.set_value_trait, "value")

        self.protocol_selection = ipw.ToggleButtons(
            options=["efficiency", "precision"],
            value=DEFAULT_PARAMETERS["pseudo_family"].split("/")[3],
            layout=ipw.Layout(max_width="80%"),
        )
        self.protocol_selection.observe(self.set_value_trait, "value")

        self.dft_functional_box = ipw.VBox(
            children=[
                self.dft_functional_prompt,
                self.dft_functional,
                self.dft_functional_help,
            ],
            layout=ipw.Layout(max_width="40%"),
        )
        self.pseudo_protocol_box = ipw.VBox(
            children=[
                self.pseudo_family_prompt,
                self.protocol_selection,
                self.pseudo_family_help,
            ],
            layout=ipw.Layout(max_width="60%"),
        )
        ipw.dlink((self.show_ui, "value"), (self.protocol_selection, "disabled"))
        ipw.dlink((self.show_ui, "value"), (self.dft_functional, "disabled"))

        self.set_value_trait()

        super().__init__(
            children=[
                self.title,
                ipw.HBox(
                    [self.description, self.set_pseudo_family_box],
                    layout=ipw.Layout(height="50px", justify_content="space-between"),
                ),
                ipw.HBox([self.dft_functional_box, self.pseudo_protocol_box]),
            ]
        )
    def __init__(self, turbine_id=0, raw_data=None, client=None):
        if raw_data is None or len(raw_data) == 0:
            raise Exception(
                "You need to pass an array with at least one row for raw data")

        self.mqtt_client = client
        self.turbine_id = turbine_id  # id of the turbine
        self.raw_data = raw_data  # buffer with the raw sensors data
        self.raw_data_idx = random.randint(0, len(raw_data) - 1)

        self.running = False  # running status
        self.halted = False  # if True you can't use this turbine anymore. create a new one.

        # components of the UI
        self.stopped_img = open('../../imgs/wind_turbine.png', 'rb').read()
        self.running_img = open('../../imgs/wind_turbine.gif', 'rb').read()
        self.button = widgets.Button(description='Start (Id: %d)' %
                                     self.turbine_id)
        self.button.on_click(self.__on_button_clicked__)

        self.img = widgets.Image(value=self.stopped_img, width=150, height=170)
        self.status_label = widgets.Label(layout={'width': "150px"},
                                          value='Model loaded')

        self.vibration_status = widgets.Valid(value=False,
                                              description='Vibration')
        self.voltage_status = widgets.Valid(value=False, description='Voltage')
        self.rotation_status = widgets.Valid(value=False,
                                             description='Rotation')

        self.noise_buttons = [
            widgets.Button(description='Volt', layout={'width': '50px'}),
            widgets.Button(description='Rot', layout={'width': '50px'}),
            widgets.Button(description='Vib', layout={'width': '50px'})
        ]
        for i in self.noise_buttons:
            i.on_click(self.__on_noise_button_clicked)
        self.anomaly_status = widgets.VBox([
            self.vibration_status, self.voltage_status, self.rotation_status,
            widgets.Label("Inject noise"),
            widgets.HBox(self.noise_buttons)
        ],
                                           layout={'visibility': 'hidden'})

        # subscribe to messages from inference app
        self.turbine_update_label_topic = f'wind-turbine/{turbine_id}/label/update'
        self.mqtt_client.subscribe(self.turbine_update_label_topic,
                                   mqtt.QoS.AT_LEAST_ONCE,
                                   handler=self.__callback_update_label__)

        self.turbine_anomalies_topic = f'wind-turbine/{turbine_id}/anomalies'
        self.mqtt_client.subscribe(self.turbine_anomalies_topic,
                                   mqtt.QoS.AT_LEAST_ONCE,
                                   handler=self.__callback_update_anomalies__)

        # self.mqtt_client.subscribe_to_topics(self.turbine_id,
        #                                     self.callback_update_label,
        #                                     self.callback_update_anomalies)

        self.feature_ids = np.array(
            [8, 9, 10, 7, 22, 5,
             6])  # qX,qy,qz,qw  ,wind_seed_rps, rps, voltage
        self.feature_names = np.array(
            ['qx', 'qy', 'qz', 'qw', 'wind speed rps', 'rps', 'voltage'])
        self.data_buffer = {}
        self.raw_data_topic = 'wind-turbine/' + str(
            self.turbine_id) + '/raw-data'
        self.max_buffer_size = 500
        for j in range(self.max_buffer_size):
            self.__read_next_turbine_sample__()
Exemple #13
0
class interface(object):
    """A class to hold interface for defining sample attributes"""
    def fc2dfgeo(fc):
        # Convert a FeatureCollection into a pandas DataFrame
        # Features is a list of dict with the output
        features = fc.getInfo()['features']

        dictarr = []

        for f in features:
            # Store all attributes in a dict
            attr = f['properties']
            # and treat geometry separately
            attr['geometry'] = f['geometry']
            dictarr.append(attr)

        df = geopandas.GeoDataFrame(dictarr)
        return df

    # Set up database
    current_id = 0
    dbPath = os.getcwd() + '/measures_database'
    if not os.path.isfile(dbPath):
        conn = sqlite3.connect(dbPath)
        c = conn.cursor()
        c.execute('''CREATE TABLE measures
                 (id text, lat text, lon text, year1 text, year2 text, direction text, coverType text,
                 condition text, change text, chaOther text, confCA text,
                 class text, water text, bare text, albedo text, use text,
                 height text, transport text, impervious text, density text,
                 vegType1 text, herbaceous text, shrub text, forestPhenology text,
                 leafType text, location text, confidence real, notes text,
                 byear text, brange1 text, brange2 text)''')
        print('Database created')

    # Create widgets
    # Years slider
    years = widgets.IntRangeSlider(value=[2012, 2015],
                                   min=1990,
                                   max=2018,
                                   step=1,
                                   description='Years:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')

    # Dropdown hierachy
    drop1 = widgets.Dropdown(options=['Persistant Ice?', 'Yes', 'No'],
                             value='Persistant Ice?',
                             description='Decision 2',
                             disabled=False)

    drop2 = widgets.Dropdown(options=['Decision 3'],
                             value='Decision 3',
                             description='Decision 3',
                             disabled=False)

    drop3 = widgets.Dropdown(options=['Decision 4'],
                             value='Decision 4',
                             description='Decision 4',
                             disabled=False)

    drop4 = widgets.Dropdown(options=['Decision 5'],
                             value='Decision 5',
                             description='Decision 5',
                             disabled=False)

    drop5 = widgets.Dropdown(options=['Decision 6'],
                             value='Decision 6',
                             description='Decision 6',
                             disabled=False)

    drop6 = widgets.Dropdown(options=['Decision 7'],
                             value='Decision 7',
                             description='Decision 7',
                             disabled=False)

    drop7 = widgets.Dropdown(options=['Decision 8'],
                             value='Decision 8',
                             description='Decision 8',
                             disabled=False)
    drop8 = widgets.Dropdown(options=['Decision 9'],
                             value='Decision 9',
                             description='Decision 9',
                             disabled=False)

    drop9 = widgets.Dropdown(options=['Stable', 'Transitional', 'Break'],
                             value='Stable',
                             description='Label Type:',
                             disabled=False)

    drop0 = widgets.Dropdown(
        options=['Dominant or Secondary?', 'Dominant', 'Secondary'],
        value='Dominant or Secondary?',
        description='Decision 1',
        disabled=False)
    veg_selector = widgets.SelectMultiple(options=[
        'Veg Type', 'Cropland', 'Plantation', 'Wetland', 'Riparian/Flood'
    ],
                                          value=['Veg Type'],
                                          description='Veg Type:',
                                          disabled=True)

    change_selector = widgets.SelectMultiple(
        options=[
            'None', 'Deforestation/Logging', 'Fire', 'Insect damage',
            'Urban Dev.', 'Flooding', 'Decline/Degradation', 'Regrowth',
            'Riparian/Water shift', 'Other (Specify)'
        ],
        value=['None'],
        # rows=10,
        description='Change Agent:',
        disabled=False)

    direction = widgets.SelectMultiple(
        options=[
            'None', 'Veg Increase', 'Veg Decrease', 'Water Increase',
            'Water Decrease', 'Bare Increase', 'Bare Decrease',
            'Urban Increase', 'Urban Decrease', 'Albedo Increase',
            'Albedo Decrease'
        ],
        value=['None'],
        # rows=10,
        description='Directional Change:',
        disabled=False)
    change_other = widgets.Text(value='Specify other',
                                placeholder='Specify other',
                                description='Other:',
                                disabled=False,
                                continuous_update=True)

    break_year = widgets.IntSlider(value=2013,
                                   min=1990,
                                   max=2018,
                                   step=1,
                                   description='Break Year:',
                                   disabled=True,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')
    break_years = widgets.IntRangeSlider(value=[2012, 2015],
                                         min=1990,
                                         max=2018,
                                         step=1,
                                         description='Break Range:',
                                         disabled=True,
                                         continuous_update=False,
                                         orientation='horizontal',
                                         readout=True,
                                         readout_format='d')

    # Display current validity of sample
    valid = widgets.Valid(value=False, description='Not Saved', readout='')

    # Create button for checking validity
    validate = widgets.Button(value=False,
                              description='Validate',
                              disabled=False,
                              button_style='',
                              icon='check')

    # Save the current sample, only possible when validity has been approved
    save_button = widgets.Button(value=False,
                                 description='Save',
                                 disabled=False,
                                 button_style='')

    # Load everything
    load_button = widgets.Button(value=False,
                                 description='Load',
                                 disabled=False,
                                 button_style='')

    valid_load = widgets.Valid(value=False,
                               description='Not Loaded',
                               readout='')

    # Interpreters confidence
    confidence = widgets.IntSlider(value=0,
                                   min=0,
                                   max=3,
                                   step=1,
                                   description='Confidence:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')

    ca_confidence = widgets.IntSlider(value=0,
                                      min=0,
                                      max=3,
                                      step=1,
                                      description='',
                                      disabled=False,
                                      continuous_update=False,
                                      orientation='horizontal',
                                      readout=True,
                                      readout_format='d')

    # Notes
    notes = widgets.Textarea(
        value='Enter any useful or interesting information about the sample.',
        placeholder=
        'Enter any useful or interesting information about the sample',
        description='Notes:',
        layout=widgets.Layout(width='70%'),
        disabled=False)

    # Spreadsheet information
    spreadsheet = widgets.Text(
        value='Google Spreadsheet Credential JSON',
        placeholder='Google Spreadsheet Credential JSON',
        description='Credentials:',
        disabled=False,
        continuous_update=True)

    # MEaSUREs_ELB
    spreadName = widgets.Text(value='Google Spreadsheet Name',
                              placeholder='Google Spreadsheet Name',
                              description='Name:',
                              disabled=False,
                              continuous_update=True)
    # Sample path
    sampleWidget = widgets.Text(value='Path to sample feature collection',
                                description='Path:',
                                disabled=False,
                                continuous_update=True)

    def __init__(self):
        interface.sample_path = None
        interface.sheet = None
        interface.sheet2 = None

    def reset_drops():
        interface.drop4.set_trait('options', ['Decision 4'])
        interface.drop5.set_trait('options', ['Decision 5'])
        interface.drop6.set_trait('options', ['Decision 6'])
        interface.drop7.set_trait('options', ['Decision 7'])
        interface.drop8.set_trait('options', ['Decision 8'])
        interface.veg_selector.disabled = True

    def drop1_clicked(selection):
        """ Generate secondary class selector after initial class is chosen """
        if selection.new == 'No':
            interface.drop2.set_trait('options',
                                      ['>30% Vegetated?', 'Yes', 'No'])
        elif selection.new == 'Yes':
            interface.drop2.set_trait('options', ['Ice/Snow'])
            interface.drop3.set_trait('options',
                                      ['No other information needed'])
            interface.reset_drops()

    def drop2_clicked(selection):
        """ Generate vegetation class information after initial class is chosen """
        if '>30% Vegetated?' in interface.drop2.options:
            if selection.new == 'Yes':
                interface.drop3.set_trait('options', [
                    'Density', 'Closed (60-70%)', 'Open (30-60%)',
                    'Sparse (<30%)'
                ])
                interface.veg_selector.disabled = False
                interface.drop4.set_trait('options', ['Trees?', 'Yes', 'No'])

            elif selection.new == 'No':
                interface.drop3.set_trait(
                    'options',
                    ['Dominant Cover?', 'Water', 'Bare', 'Developed'])
                interface.drop4.set_trait('options', ['Decision 4'])
                interface.drop5.set_trait('options', ['Decision 5'])
                interface.drop6.set_trait('options', ['Decision 6'])
                interface.drop7.set_trait('options', ['Decision 7'])
                interface.drop8.set_trait('options', ['Decision 8'])
                interface.veg_selector.disabled = True

        else:
            interface.drop3.set_trait('options',
                                      ['No Other Information Needed'])

    def drop3_clicked(selection):
        """ Generate third class selector after initial class is chosen """
        if 'Dominant Cover?' in interface.drop3.options:
            interface.veg_selector.disabled = True
            if selection.new == 'Water':
                interface.drop4.set_trait('options', [
                    'Water Type', 'Shore/Inter tidal', 'Shallows', 'River',
                    'Lake/Reservoir', 'Ocean'
                ])
            elif selection.new == 'Bare':
                interface.drop4.set_trait('options', [
                    'Bare Type', 'Soil', 'Rock', 'Quarry (Active)',
                    'Beach/Sand'
                ])
            elif selection.new == 'Developed':
                interface.drop4.set_trait(
                    'options', ['Surface Albedo', 'High', 'Low', 'Mixed'])
                interface.drop5.set_trait(
                    'options', ['Use', 'Residential', 'Commercial/Industrial'])
                interface.drop6.set_trait('options', [
                    'Building Height', 'No Buildings', '1-2 Stories',
                    '3-5 Stories', '5+ Stories'
                ])
                interface.drop7.set_trait(
                    'options', ['Transport', 'Road', 'Not Applicable'])
                interface.drop8.set_trait('options', [
                    '% Impervious', 'High (60-100)', 'Medium (30-60)',
                    'Low (<30)'
                ])

    def drop4_clicked(selection):  # ERIC HERE
        """ Generate fourth class selector after initial class is chosen """
        if 'Trees?' in interface.drop4.options:
            if selection.new == 'Yes':
                interface.drop5.set_trait(
                    'options', ['Height >5m & Canopy >30%', 'Yes', 'No'])
            elif selection.new == 'No':
                interface.drop5.set_trait('options', [
                    'Herbaceous Type', 'Grassland', 'Pasture',
                    'Lawn/Urban Grass', 'Moss/Lichen'
                ])

    def drop5_clicked(selection):
        """ Generate fifth class selector after initial class is chosen """
        if 'Height >5m & Canopy >30%' in interface.drop5.options:
            if selection.new == 'Yes':
                interface.drop6.set_trait(
                    'options',
                    ['Forest Type', 'Evergreen', 'Deciduous', 'Mixed'])
                interface.drop7.set_trait(
                    'options', ['Leaf Type', 'Broad', 'Needle', 'Unsure'])
                interface.drop8.set_trait('options',
                                          ['Location', 'Interior', 'Edge'])

            elif selection.new == 'No':
                interface.drop6.set_trait(
                    'options',
                    ['Shrub Type', 'Evergreen', 'Deciduous', 'Mixed'])

    def check_val_status(selection):
        """ Check the validity of the current sample and change valid widget accordingly """
        selected_secondary_lc = False
        wrote_correct_lc = False
        if interface.second_class_drop.value != 'Secondary Class Information':
            selected_secondary_lc = True
        else:
            print("Must specify secondary class information!")
        if interface.lc.value.capitalize(
        ) == interface.textClass.value.capitalize():
            wrote_correct_lc = True
        if selected_secondary_lc and wrote_correct_lc:
            interface.valid.value = True
            interface.save_button.disabled = False

    def load_everything(sender):
        # Load Google Spreadsheet and GEE Feature Collection
        scope = [
            'https://spreadsheets.google.com/feeds' + ' ' +
            'https://www.googleapis.com/auth/drive'
        ]
        creds = ServiceAccountCredentials.from_json_keyfile_name(
            interface.spreadsheet.value, scope)
        client = gspread.authorize(creds)
        #interface.sheet = client.open(interface.spreadName.value).sheet1
        interface.sheet = client.open(
            interface.spreadName.value).get_worksheet(0)
        interface.sheet2 = client.open(
            interface.spreadName.value).get_worksheet(1)
        interface.sample_path = ee.FeatureCollection(
            interface.sampleWidget.value)
        interface.fc_df = interface.fc2dfgeo(interface.sample_path)
        if 'ID' not in interface.fc_df.columns:
            first_index = interface.fc_df.index.min()
            interface.fc_df['ID'] = interface.fc_df.index
        else:
            first_index = interface.fc_df['ID'].min()
        interface.fc_df = interface.fc_df.set_index('ID')
        interface.valid_load.value = True
        interface.valid_load.description = 'Loaded!'
        interface.current_id = first_index - 1

    def turn_on_break_years(selection):
        if selection.new == 'Break':
            interface.break_years.disabled = False
            interface.break_year.disabled = False
        else:
            interface.break_years.disabled = True
            interface.break_year.disabled = True

    # Handle widget interactions
    # Call function check_val_status when button is clicked
    validate.on_click(check_val_status)
    # Primary class selector action
    drop1.observe(drop1_clicked, 'value')
    # Secondary class selector action
    drop2.observe(drop2_clicked, 'value')
    # Third class selector action
    drop3.observe(drop3_clicked, 'value')
    drop4.observe(drop4_clicked, 'value')
    drop5.observe(drop5_clicked, 'value')

    drop9.observe(turn_on_break_years, 'value')

    # Load database and sample
    load_button.on_click(load_everything)
Exemple #14
0
 def token(token_success):
     token = widgets.Valid(value=token_success, description="Token")
     return token
Exemple #15
0
    def __init__(self):
        self.project_name = w.Text(description="Project",
                                   value="",
                                   placeholder="Enter the project name")
        self.project_exists = w.Label(
            "A project cannot be an empty string or an existing directory.")
        w.Valid(value=False, description=" ")

        def update_validity(path):
            if os.path.isdir(path) or path == "":
                self.project_exists.value = "A project cannot be an empty string or an existing directory."
            else:
                self.project_exists.value = "Valid new project name."
            self.update_create_button()

        w.interactive(update_validity, path=self.project_name)
        self.tabs = {
            "dictionary_mutation":
            wc.w_table(
                "dictionary_mutation", configurations["dictionary_mutation"],
                "float_widget",
                "<h2>Mutation parameters</h2><p>Set the values of the different mutation rates in the <code>dictionary_mutation</code> dictionary. For more information about <code>dictionary_mutation</code>, see the <a href=\"{}parameters.html#mutation-parameters-dictionary-mutation\">documentation</a>. </p>"
                .format(doc_url)),
            "dictionary_ranges":
            wc.w_table(
                "dictionary_ranges", configurations["dictionary_ranges"],
                "float_range_widget",
                "<h2>Kinetic parameters</h2><p> Set the ranges over which the kinetic parameters can evolve. These parameters are stored in the <code>dictionary_ranges</code> dictionary. For more information about <code>dictionary_ranges</code>, see the <a href=\"{}parameters.html#kinetic-parameters-dictionary-ranges\">documentation</a>. </p>"
                .format(doc_url)),
            "restart":
            wf.w_restart(
                infos=
                "<h2>Restart</h2><p>For now restart needs to be defined manually in the initialization file of an existing project.</p><p>This tab can be used to set the frequency at which a complete generation is saved. For more information about restart, see the <a href=\"{}parameters.html#restart-parameters-prmt-restart\">documentation</a>.</p>"
                .format(doc_url)),
            "prmt":
            wc.prmt_widget(
                values=configurations["prmt"],
                infos=
                "<h2>General simulation parameters</h2><p>Set the global settings in the <code>prmt</code> dictionary to define how phievo should work. More information is available in the <a href=\"{}parameters.html#general-simulation-parameters-prmt\">documentation</a>.</p>"
                .format(doc_url)),
            "init":
            inet.init_network_widget(),
            "cfile":
            wc.ccode_widget(
                "cfile",
                configurations["cfile"],
                infos=
                "<h2>cfiles</h2>\n<p>You may leave these settings as default, blank files will be created in the project directory and can be updated before starting a simulation. The files that already have a setting should be modified by advanced users only.</p><p><b>Note:</b> It is important that you update the dummy fitness.c file created by this utility since its default value returns 1 for all the networks. For more information about the C files, see the <a href=\"{}create_new_project.html#run-a-simulation\">documentation</a>.</p>"
                .format(doc_url))
        }
        self.w_tab = w.Tab()
        self.w_tab.children = [
            self.tabs[key].get_widget() for key in sorted(self.tabs)
        ]
        for i, name in enumerate(sorted(self.tabs)):
            self.w_tab.set_title(i, tab_labels[name])

        self.create_button = w.Button(description="Write project",
                                      button_style="info",
                                      disabled=True)
        self.create_button.on_click(self.write)
        self.create_info = w.HTML("Please enter a valid project directory.")

        def update_ninput(val):
            self.tabs["init"].nb_inputs = self.tabs["prmt"].obj_dict[
                "ninput"].value.value
            self.tabs["init"].update_counters()

        w.interactive(update_ninput,
                      val=self.tabs["prmt"].obj_dict["ninput"].value)

        def update_noutput(val):
            self.tabs["init"].nb_outputs = self.tabs["prmt"].obj_dict[
                "noutput"].value.value
            self.tabs["init"].update_counters()

        w.interactive(update_noutput,
                      val=self.tabs["prmt"].obj_dict["noutput"].value)
Exemple #16
0
def token_widget():
    token = widgets.Valid(value=token_success, description='Token')
    return token